@rebasepro/common 0.5.0 → 0.6.1

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.es.js CHANGED
@@ -1,2536 +1,2174 @@
1
1
  import { EntityReference, EntityRelation, getDataSourceCapabilities } from "@rebasepro/types";
2
- import { mergeDeep, toSnakeCase, generateForeignKeyName, getIn as getIn$1, isDefaultFieldConfigId, randomString, removeFunctions, deepClone } from "@rebasepro/utils";
2
+ import { deepClone, generateForeignKeyName, getIn, isDefaultFieldConfigId, mergeDeep, randomString, removeFunctions, toSnakeCase } from "@rebasepro/utils";
3
3
  import jsonLogic from "json-logic-js";
4
4
  import { deepEqual } from "fast-equals";
5
- const DEFAULT_ONE_OF_TYPE = "type";
6
- const DEFAULT_ONE_OF_VALUE = "value";
5
+ //#region src/util/common.ts
6
+ var DEFAULT_ONE_OF_TYPE = "type";
7
+ var DEFAULT_ONE_OF_VALUE = "value";
8
+ //#endregion
9
+ //#region src/util/entities.ts
7
10
  function isReadOnly(property) {
8
- if (property.ui?.readOnly) return true;
9
- if (property.type === "date") {
10
- if (property.autoValue) return true;
11
- }
12
- if (property.type === "reference") {
13
- return !property.path && !("Field" in (property.ui || {}) && property.ui?.Field);
14
- }
15
- return false;
11
+ if (property.ui?.readOnly) return true;
12
+ if (property.type === "date") {
13
+ if (property.autoValue) return true;
14
+ }
15
+ if (property.type === "reference") return !property.path && !("Field" in (property.ui || {}) && property.ui?.Field);
16
+ return false;
16
17
  }
17
18
  function isHidden(property) {
18
- return typeof property.ui?.disabled === "object" && Boolean(property.ui?.disabled.hidden);
19
+ return typeof property.ui?.disabled === "object" && Boolean(property.ui?.disabled.hidden);
19
20
  }
20
21
  function isPropertyBuilder(property) {
21
- return typeof property?.dynamicProps === "function";
22
+ return typeof property?.dynamicProps === "function";
22
23
  }
23
24
  function getDefaultValuesFor(properties) {
24
- if (!properties) return {};
25
- return Object.entries(properties).map(([key, property]) => {
26
- if (!property) return {};
27
- const value = getDefaultValueFor(property);
28
- return value === void 0 ? {} : {
29
- [key]: value
30
- };
31
- }).reduce((a, b) => ({
32
- ...a,
33
- ...b
34
- }), {});
25
+ if (!properties) return {};
26
+ return Object.entries(properties).map(([key, property]) => {
27
+ if (!property) return {};
28
+ const value = getDefaultValueFor(property);
29
+ return value === void 0 ? {} : { [key]: value };
30
+ }).reduce((a, b) => ({
31
+ ...a,
32
+ ...b
33
+ }), {});
35
34
  }
36
35
  function getDefaultValueFor(property) {
37
- if (!property) return void 0;
38
- if (isPropertyBuilder(property)) return void 0;
39
- if (property.defaultValue || property.defaultValue === null) {
40
- return property.defaultValue;
41
- } else if (property.type === "map" && property.properties) {
42
- const defaultValuesFor = getDefaultValuesFor(property.properties);
43
- if (Object.keys(defaultValuesFor).length === 0) return void 0;
44
- return defaultValuesFor;
45
- } else {
46
- return getDefaultValueFortype(property.type);
47
- }
36
+ if (!property) return void 0;
37
+ if (isPropertyBuilder(property)) return void 0;
38
+ if (property.defaultValue || property.defaultValue === null) return property.defaultValue;
39
+ else if (property.type === "map" && property.properties) {
40
+ const defaultValuesFor = getDefaultValuesFor(property.properties);
41
+ if (Object.keys(defaultValuesFor).length === 0) return void 0;
42
+ return defaultValuesFor;
43
+ } else return getDefaultValueFortype(property.type);
48
44
  }
49
45
  function getDefaultValueFortype(type) {
50
- if (type === "string") {
51
- return null;
52
- } else if (type === "number") {
53
- return null;
54
- } else if (type === "boolean") {
55
- return false;
56
- } else if (type === "date") {
57
- return null;
58
- } else if (type === "array") {
59
- return [];
60
- } else if (type === "map") {
61
- return {};
62
- } else if (type === "vector") {
63
- return null;
64
- } else if (type === "binary") {
65
- return null;
66
- } else {
67
- return null;
68
- }
69
- }
70
- function updateDateAutoValues({
71
- inputValues,
72
- properties,
73
- status,
74
- timestampNowValue
75
- }) {
76
- return traverseValuesProperties(inputValues, properties, (inputValue, property) => {
77
- if (property.type === "date") {
78
- if (status === "existing" && property.autoValue === "on_update") {
79
- return timestampNowValue;
80
- } else if ((status === "new" || status === "copy") && (property.autoValue === "on_update" || property.autoValue === "on_create")) {
81
- return timestampNowValue;
82
- } else {
83
- return inputValue;
84
- }
85
- } else {
86
- return inputValue;
87
- }
88
- }) ?? {};
89
- }
46
+ if (type === "string") return null;
47
+ else if (type === "number") return null;
48
+ else if (type === "boolean") return false;
49
+ else if (type === "date") return null;
50
+ else if (type === "array") return [];
51
+ else if (type === "map") return {};
52
+ else if (type === "vector") return null;
53
+ else if (type === "binary") return null;
54
+ else return null;
55
+ }
56
+ /**
57
+ * Update the automatic values in an entity before save
58
+ * @group Driver
59
+ */
60
+ function updateDateAutoValues({ inputValues, properties, status, timestampNowValue }) {
61
+ return traverseValuesProperties(inputValues, properties, (inputValue, property) => {
62
+ if (property.type === "date") if (status === "existing" && property.autoValue === "on_update") return timestampNowValue;
63
+ else if ((status === "new" || status === "copy") && (property.autoValue === "on_update" || property.autoValue === "on_create")) return timestampNowValue;
64
+ else return inputValue;
65
+ else return inputValue;
66
+ }) ?? {};
67
+ }
68
+ /**
69
+ * Add missing required fields, expected in the collection, to the values of an entity
70
+ * @param values
71
+ * @param properties
72
+ * @group Driver
73
+ */
90
74
  function sanitizeData(values, properties) {
91
- const result = values;
92
- Object.entries(properties).forEach(([key, property]) => {
93
- if (values && values[key] !== void 0) result[key] = values[key];
94
- else if (property.validation?.required) result[key] = null;
95
- });
96
- return result;
75
+ const result = values;
76
+ Object.entries(properties).forEach(([key, property]) => {
77
+ if (values && values[key] !== void 0) result[key] = values[key];
78
+ else if (property.validation?.required) result[key] = null;
79
+ });
80
+ return result;
97
81
  }
98
82
  function getReferenceFrom(entity) {
99
- if (typeof entity.id !== "string") throw new Error("Only string IDs are supported in references");
100
- return new EntityReference({
101
- id: entity.id,
102
- path: entity.path,
103
- driver: entity.driver,
104
- databaseId: entity.databaseId
105
- });
83
+ if (typeof entity.id !== "string") throw new Error("Only string IDs are supported in references");
84
+ return new EntityReference({
85
+ id: entity.id,
86
+ path: entity.path,
87
+ driver: entity.driver,
88
+ databaseId: entity.databaseId
89
+ });
106
90
  }
107
91
  function getRelationFrom(entity) {
108
- return new EntityRelation(entity.id, entity.path, entity);
109
- }
110
- function normalizeToEntityRelation(value) {
111
- if (value instanceof EntityRelation) return value;
112
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
113
- const obj = value;
114
- const isRelationLike = obj.__type === "relation" || obj.__type === "reference" || typeof obj.isEntityRelation === "function" && obj.isEntityRelation() || typeof obj.isEntityReference === "function" && obj.isEntityReference();
115
- if (!isRelationLike) return null;
116
- return new EntityRelation(obj.id, obj.path, obj.data);
92
+ return new EntityRelation(entity.id, entity.path, entity);
93
+ }
94
+ /**
95
+ * Normalize a value into a proper EntityRelation instance.
96
+ * Handles EntityRelation class instances, and plain objects
97
+ * with `__type === "relation"` or an `isEntityRelation()` method.
98
+ *
99
+ * When `propertyType` is `"relation"`, also accepts plain objects that
100
+ * have `id` and `path` fields — these are relation-shaped objects from
101
+ * edge cases in the data pipeline (REST fallback, stale cache, custom data source).
102
+ *
103
+ * Returns null if the value cannot be coerced.
104
+ */
105
+ function normalizeToEntityRelation(value, propertyType) {
106
+ if (value instanceof EntityRelation) return value;
107
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
108
+ const obj = value;
109
+ 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;
110
+ return new EntityRelation(obj.id, obj.path, obj.data);
117
111
  }
118
112
  function traverseValuesProperties(inputValues, properties, operation) {
119
- const safeInputValues = inputValues ?? {};
120
- const updatedValues = Object.entries(properties).map(([key, property]) => {
121
- const inputValue = safeInputValues && safeInputValues[key];
122
- const updatedValue = traverseValueProperty(inputValue, property, operation);
123
- if (updatedValue === null) return null;
124
- if (updatedValue === void 0) return void 0;
125
- return {
126
- [key]: updatedValue
127
- };
128
- }).reduce((a, b) => ({
129
- ...a,
130
- ...b
131
- }), {});
132
- const result = mergeDeep(safeInputValues, updatedValues);
133
- if (!result || Object.keys(result).length === 0) return void 0;
134
- return result;
113
+ const safeInputValues = inputValues ?? {};
114
+ const result = mergeDeep(safeInputValues, Object.entries(properties).map(([key, property]) => {
115
+ const updatedValue = traverseValueProperty(safeInputValues && safeInputValues[key], property, operation);
116
+ if (updatedValue === null) return null;
117
+ if (updatedValue === void 0) return void 0;
118
+ return { [key]: updatedValue };
119
+ }).reduce((a, b) => ({
120
+ ...a,
121
+ ...b
122
+ }), {}));
123
+ if (!result || Object.keys(result).length === 0) return void 0;
124
+ return result;
135
125
  }
136
126
  function traverseValueProperty(inputValue, property, operation) {
137
- let value;
138
- if (property.type === "map" && property.properties) {
139
- value = traverseValuesProperties(inputValue, property.properties, operation);
140
- } else if (property.type === "array") {
141
- const of = property.of;
142
- if (of && Array.isArray(inputValue) && !Array.isArray(of)) {
143
- value = inputValue.map((e) => traverseValueProperty(e, of, operation));
144
- } else if (of && Array.isArray(inputValue) && Array.isArray(of)) {
145
- value = inputValue.map((e, i) => {
146
- if (i < of.length) return traverseValueProperty(e, of[i], operation);
147
- return null;
148
- }).filter(Boolean);
149
- } else if (property.oneOf && Array.isArray(inputValue)) {
150
- const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;
151
- const valueField = property.oneOf?.valueField ?? DEFAULT_ONE_OF_VALUE;
152
- value = inputValue.map((e) => {
153
- if (e === null) return null;
154
- if (typeof e !== "object") return e;
155
- const rec = e;
156
- const type = rec[typeField];
157
- const childProperty = property.oneOf?.properties[type];
158
- if (!type || !childProperty) return e;
159
- return {
160
- [typeField]: type,
161
- [valueField]: traverseValueProperty(rec[valueField], childProperty, operation)
162
- };
163
- });
164
- } else {
165
- value = inputValue;
166
- }
167
- } else {
168
- value = operation(inputValue, property);
169
- }
170
- return value;
171
- }
127
+ let value;
128
+ if (property.type === "map" && property.properties) value = traverseValuesProperties(inputValue, property.properties, operation);
129
+ else if (property.type === "array") {
130
+ const of = property.of;
131
+ if (of && Array.isArray(inputValue) && !Array.isArray(of)) value = inputValue.map((e) => traverseValueProperty(e, of, operation));
132
+ else if (of && Array.isArray(inputValue) && Array.isArray(of)) value = inputValue.map((e, i) => {
133
+ if (i < of.length) return traverseValueProperty(e, of[i], operation);
134
+ return null;
135
+ }).filter(Boolean);
136
+ else if (property.oneOf && Array.isArray(inputValue)) {
137
+ const typeField = property.oneOf?.typeField ?? "type";
138
+ const valueField = property.oneOf?.valueField ?? "value";
139
+ value = inputValue.map((e) => {
140
+ if (e === null) return null;
141
+ if (typeof e !== "object") return e;
142
+ const rec = e;
143
+ const type = rec[typeField];
144
+ const childProperty = property.oneOf?.properties[type];
145
+ if (!type || !childProperty) return e;
146
+ return {
147
+ [typeField]: type,
148
+ [valueField]: traverseValueProperty(rec[valueField], childProperty, operation)
149
+ };
150
+ });
151
+ } else value = inputValue;
152
+ } else value = operation(inputValue, property);
153
+ return value;
154
+ }
155
+ /**
156
+ * Create a lightweight relation stub for CMS views.
157
+ * Replaces inline `{ id, path, __type: "relation" }` object literals.
158
+ */
172
159
  function createRelationRef(id, path) {
173
- return {
174
- id,
175
- path,
176
- __type: "relation"
177
- };
178
- }
160
+ return {
161
+ id,
162
+ path,
163
+ __type: "relation"
164
+ };
165
+ }
166
+ /**
167
+ * Create a hydrated relation reference that includes the full entity data.
168
+ * Used when entity data has been pre-fetched (e.g., via batch loading or JOINs).
169
+ */
179
170
  function createRelationRefWithData(id, path, data) {
180
- return {
181
- id,
182
- path,
183
- __type: "relation",
184
- data
185
- };
186
- }
171
+ return {
172
+ id,
173
+ path,
174
+ __type: "relation",
175
+ data
176
+ };
177
+ }
178
+ //#endregion
179
+ //#region src/util/collections.ts
187
180
  function sortProperties(properties, propertiesOrder) {
188
- try {
189
- const propertiesKeys = Object.keys(properties);
190
- if (!propertiesOrder || propertiesOrder.length === 0) {
191
- return propertiesKeys.map((key) => {
192
- const property = properties[key];
193
- if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) {
194
- return {
195
- [key]: {
196
- ...property,
197
- properties: sortProperties(property.properties, property.propertiesOrder)
198
- }
199
- };
200
- } else {
201
- return {
202
- [key]: property
203
- };
204
- }
205
- }).reduce((a, b) => ({
206
- ...a,
207
- ...b
208
- }), {});
209
- }
210
- const validOrderKeys = propertiesOrder.filter((key) => {
211
- return !key.includes(".") && properties[key];
212
- });
213
- const processedKeys = new Set(validOrderKeys);
214
- const orderedResult = validOrderKeys.map((key) => {
215
- const property = properties[key];
216
- if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) {
217
- return {
218
- [key]: {
219
- ...property,
220
- properties: sortProperties(property.properties, property.propertiesOrder)
221
- }
222
- };
223
- } else {
224
- return {
225
- [key]: property
226
- };
227
- }
228
- }).reduce((a, b) => ({
229
- ...a,
230
- ...b
231
- }), {});
232
- const missingProperties = propertiesKeys.filter((key) => !processedKeys.has(key)).map((key) => {
233
- const property = properties[key];
234
- if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) {
235
- return {
236
- [key]: {
237
- ...property,
238
- properties: sortProperties(property.properties, property.propertiesOrder)
239
- }
240
- };
241
- } else {
242
- return {
243
- [key]: property
244
- };
245
- }
246
- }).reduce((a, b) => ({
247
- ...a,
248
- ...b
249
- }), {});
250
- return {
251
- ...orderedResult,
252
- ...missingProperties
253
- };
254
- } catch (e) {
255
- console.error("Error sorting properties", e);
256
- return properties;
257
- }
181
+ try {
182
+ const propertiesKeys = Object.keys(properties);
183
+ if (!propertiesOrder || propertiesOrder.length === 0) return propertiesKeys.map((key) => {
184
+ const property = properties[key];
185
+ if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) return { [key]: {
186
+ ...property,
187
+ properties: sortProperties(property.properties, property.propertiesOrder)
188
+ } };
189
+ else return { [key]: property };
190
+ }).reduce((a, b) => ({
191
+ ...a,
192
+ ...b
193
+ }), {});
194
+ const validOrderKeys = propertiesOrder.filter((key) => {
195
+ return !key.includes(".") && properties[key];
196
+ });
197
+ const processedKeys = new Set(validOrderKeys);
198
+ const orderedResult = validOrderKeys.map((key) => {
199
+ const property = properties[key];
200
+ if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) return { [key]: {
201
+ ...property,
202
+ properties: sortProperties(property.properties, property.propertiesOrder)
203
+ } };
204
+ else return { [key]: property };
205
+ }).reduce((a, b) => ({
206
+ ...a,
207
+ ...b
208
+ }), {});
209
+ const missingProperties = propertiesKeys.filter((key) => !processedKeys.has(key)).map((key) => {
210
+ const property = properties[key];
211
+ if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) return { [key]: {
212
+ ...property,
213
+ properties: sortProperties(property.properties, property.propertiesOrder)
214
+ } };
215
+ else return { [key]: property };
216
+ }).reduce((a, b) => ({
217
+ ...a,
218
+ ...b
219
+ }), {});
220
+ return {
221
+ ...orderedResult,
222
+ ...missingProperties
223
+ };
224
+ } catch (e) {
225
+ console.error("Error sorting properties", e);
226
+ return properties;
227
+ }
258
228
  }
259
229
  function resolveDefaultSelectedView(defaultSelectedView, params) {
260
- if (!defaultSelectedView) {
261
- return void 0;
262
- } else if (typeof defaultSelectedView === "string") {
263
- return defaultSelectedView;
264
- } else {
265
- return defaultSelectedView(params);
266
- }
230
+ if (!defaultSelectedView) return;
231
+ else if (typeof defaultSelectedView === "string") return defaultSelectedView;
232
+ else return defaultSelectedView(params);
267
233
  }
268
234
  function getLocalChangesBackup(collection) {
269
- if (!collection.localChangesBackup) {
270
- return "manual_apply";
271
- }
272
- return collection.localChangesBackup;
273
- }
235
+ if (!collection.localChangesBackup) return "manual_apply";
236
+ return collection.localChangesBackup;
237
+ }
238
+ /**
239
+ * Returns the primary keys for an entity collection by inspecting the properties
240
+ * and finding any properties with `isId`.
241
+ * Fallbacks to `["id"]` if no properties are marked as `isId: true`.
242
+ * @param collection
243
+ */
274
244
  function getPrimaryKeys(collection) {
275
- const properties = collection.properties;
276
- if (!properties) {
277
- return ["id"];
278
- }
279
- const ids = Object.entries(properties).filter(([key, prop]) => typeof prop === "object" && prop !== null && "isId" in prop && Boolean(prop.isId)).map(([key]) => key);
280
- if (ids.length > 0) {
281
- return ids;
282
- }
283
- return ["id"];
284
- }
245
+ const properties = collection.properties;
246
+ if (!properties) return ["id"];
247
+ const ids = Object.entries(properties).filter(([key, prop]) => typeof prop === "object" && prop !== null && "isId" in prop && Boolean(prop.isId)).map(([key]) => key);
248
+ if (ids.length > 0) return ids;
249
+ return ["id"];
250
+ }
251
+ //#endregion
252
+ //#region src/util/enums.ts
285
253
  function enumToObjectEntries(enumValues) {
286
- if (Array.isArray(enumValues)) {
287
- return enumValues;
288
- } else {
289
- return Object.entries(enumValues).map(([id, value]) => {
290
- if (typeof value === "string") {
291
- return {
292
- id,
293
- label: value
294
- };
295
- } else {
296
- return {
297
- ...value,
298
- id
299
- };
300
- }
301
- });
302
- }
254
+ if (Array.isArray(enumValues)) return enumValues;
255
+ else return Object.entries(enumValues).map(([id, value]) => {
256
+ if (typeof value === "string") return {
257
+ id,
258
+ label: value
259
+ };
260
+ else return {
261
+ ...value,
262
+ id
263
+ };
264
+ });
303
265
  }
304
266
  function getLabelOrConfigFrom(enumValues, key) {
305
- if (key === null || key === void 0) return void 0;
306
- return enumValues.find((entry) => String(entry.id) === String(key));
307
- }
308
- const COLLECTION_PATH_SEPARATOR = "::";
267
+ if (key === null || key === void 0) return void 0;
268
+ return enumValues.find((entry) => String(entry.id) === String(key));
269
+ }
270
+ //#endregion
271
+ //#region src/util/paths.ts
272
+ var COLLECTION_PATH_SEPARATOR = "::";
273
+ /**
274
+ * Remove the entity ids from a given path
275
+ * `products/B44RG6APH/locales` => `products::locales`
276
+ * @param path
277
+ */
309
278
  function stripCollectionPath(path) {
310
- return segmentsToStrippedPath(fullPathToCollectionSegments(path));
279
+ return segmentsToStrippedPath(fullPathToCollectionSegments(path));
311
280
  }
312
281
  function segmentsToStrippedPath(paths) {
313
- if (paths.length === 1) return paths[0];
314
- return paths.reduce((a, b) => `${a}${COLLECTION_PATH_SEPARATOR}${b}`);
315
- }
282
+ if (paths.length === 1) return paths[0];
283
+ return paths.reduce((a, b) => `${a}::${b}`);
284
+ }
285
+ /**
286
+ * Extract the collection path routes
287
+ * `products/B44RG6APH/locales` => [`products`, `locales`]
288
+ * @param path
289
+ */
316
290
  function fullPathToCollectionSegments(path) {
317
- return path.split("/").filter((e, i) => i % 2 === 0);
291
+ return path.split("/").filter((e, i) => i % 2 === 0);
318
292
  }
293
+ //#endregion
294
+ //#region src/util/relations.ts
319
295
  function sanitizeRelation(relation, sourceCollection, resolveCollection) {
320
- if (!relation.target) {
321
- throw new Error("Relation is missing a `target` collection.");
322
- }
323
- const rawTarget = relation.target;
324
- let targetCollection;
325
- if (typeof rawTarget === "string") {
326
- if (resolveCollection) {
327
- targetCollection = resolveCollection(rawTarget);
328
- }
329
- if (!targetCollection) {
330
- targetCollection = {
331
- slug: rawTarget,
332
- name: rawTarget
333
- };
334
- }
335
- } else if (typeof rawTarget === "function") {
336
- const evaluated = rawTarget();
337
- if (typeof evaluated === "string") {
338
- if (resolveCollection) {
339
- targetCollection = resolveCollection(evaluated);
340
- }
341
- if (!targetCollection) {
342
- targetCollection = {
343
- slug: evaluated,
344
- name: evaluated
345
- };
346
- }
347
- } else {
348
- targetCollection = evaluated;
349
- }
350
- } else if (rawTarget && typeof rawTarget === "object") {
351
- targetCollection = rawTarget;
352
- }
353
- if (!targetCollection) {
354
- throw new Error("Relation is missing a valid `target` collection.");
355
- }
356
- const newRelation = {
357
- ...relation
358
- };
359
- newRelation.target = () => {
360
- if (typeof rawTarget === "string") {
361
- return resolveCollection && resolveCollection(rawTarget) || targetCollection;
362
- } else if (typeof rawTarget === "function") {
363
- const evaluated = rawTarget();
364
- if (typeof evaluated === "string") {
365
- return resolveCollection && resolveCollection(evaluated) || targetCollection;
366
- }
367
- return evaluated;
368
- }
369
- return targetCollection;
370
- };
371
- if (!newRelation.relationName) {
372
- newRelation.relationName = toSnakeCase(targetCollection.slug);
373
- }
374
- if (!newRelation.direction) {
375
- if (newRelation.foreignKeyOnTarget) newRelation.direction = "inverse";
376
- else if (newRelation.through) newRelation.direction = "owning";
377
- else if (newRelation.cardinality === "many") newRelation.direction = "inverse";
378
- else newRelation.direction = "owning";
379
- }
380
- if (!newRelation.joinPath) {
381
- const sourceName = toSnakeCase(sourceCollection.slug ?? sourceCollection.name);
382
- if (newRelation.cardinality === "one" && newRelation.direction === "owning") {
383
- if (!newRelation.localKey) {
384
- newRelation.localKey = generateForeignKeyName(newRelation.relationName);
385
- }
386
- } else if (newRelation.cardinality === "one" && newRelation.direction === "inverse") {
387
- if (!newRelation.foreignKeyOnTarget) {
388
- let foundForeignKey = false;
389
- try {
390
- const targetRelations = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? targetCollection.relations || [] : [];
391
- for (const targetRel of targetRelations) {
392
- if (targetRel.direction === "owning" && targetRel.cardinality === "one" && targetRel.localKey) {
393
- try {
394
- const targetRelTarget = targetRel.target();
395
- if (targetRelTarget.slug === sourceCollection.slug) {
396
- newRelation.foreignKeyOnTarget = targetRel.localKey;
397
- foundForeignKey = true;
398
- break;
399
- }
400
- } catch (e) {
401
- continue;
402
- }
403
- }
404
- }
405
- } catch (e) {
406
- }
407
- if (!foundForeignKey) {
408
- const keyPrefix = newRelation.inverseRelationName ? toSnakeCase(newRelation.inverseRelationName) : sourceName;
409
- newRelation.foreignKeyOnTarget = generateForeignKeyName(keyPrefix);
410
- }
411
- }
412
- } else if (newRelation.cardinality === "many" && newRelation.direction === "inverse") {
413
- let isManyToManyInverse = false;
414
- if (newRelation.inverseRelationName && !newRelation.foreignKeyOnTarget) {
415
- try {
416
- const targetRelations = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? targetCollection.relations || [] : [];
417
- for (const targetRel of targetRelations) {
418
- if (targetRel.cardinality === "many" && (targetRel.direction === "owning" || !targetRel.direction) && targetRel.relationName === newRelation.inverseRelationName) {
419
- isManyToManyInverse = true;
420
- break;
421
- }
422
- }
423
- if (!isManyToManyInverse && targetCollection.properties) {
424
- for (const [propKey, prop] of Object.entries(targetCollection.properties)) {
425
- if (prop.type !== "relation") continue;
426
- const relProp = prop;
427
- const relName = relProp.relationName || propKey;
428
- if (relName === newRelation.inverseRelationName && relProp.cardinality === "many" && (relProp.direction === "owning" || !relProp.direction)) {
429
- isManyToManyInverse = true;
430
- break;
431
- }
432
- }
433
- }
434
- } catch (e) {
435
- }
436
- }
437
- if (!isManyToManyInverse && !newRelation.foreignKeyOnTarget) {
438
- newRelation.foreignKeyOnTarget = generateForeignKeyName(sourceName);
439
- }
440
- } else if (newRelation.cardinality === "many" && newRelation.direction === "owning") {
441
- const sourceTableName = getTableName(sourceCollection);
442
- const targetTableName = getTableName(targetCollection);
443
- newRelation.through = {
444
- table: newRelation.through?.table ?? [sourceTableName, targetTableName].sort().join("_"),
445
- sourceColumn: newRelation.through?.sourceColumn ?? generateForeignKeyName(sourceName),
446
- targetColumn: newRelation.through?.targetColumn ?? generateForeignKeyName(newRelation.relationName)
447
- };
448
- }
449
- }
450
- if (newRelation.cardinality === "one" && newRelation.direction === "owning" && !newRelation.localKey && !newRelation.joinPath) {
451
- 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}'`);
452
- }
453
- if (newRelation.cardinality === "one" && newRelation.direction === "inverse" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath) {
454
- 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}'`);
455
- }
456
- if (newRelation.cardinality === "many" && newRelation.direction === "inverse" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath && !newRelation.inverseRelationName) {
457
- 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}'`);
458
- }
459
- return newRelation;
460
- }
461
- const _resolvedRelationsCache = /* @__PURE__ */ new WeakMap();
296
+ if (!relation.target) throw new Error("Relation is missing a `target` collection.");
297
+ const rawTarget = relation.target;
298
+ let targetCollection;
299
+ if (typeof rawTarget === "string") {
300
+ if (resolveCollection) targetCollection = resolveCollection(rawTarget);
301
+ if (!targetCollection) targetCollection = {
302
+ slug: rawTarget,
303
+ name: rawTarget
304
+ };
305
+ } else if (typeof rawTarget === "function") {
306
+ const evaluated = rawTarget();
307
+ if (typeof evaluated === "string") {
308
+ if (resolveCollection) targetCollection = resolveCollection(evaluated);
309
+ if (!targetCollection) targetCollection = {
310
+ slug: evaluated,
311
+ name: evaluated
312
+ };
313
+ } else targetCollection = evaluated;
314
+ } else if (rawTarget && typeof rawTarget === "object") targetCollection = rawTarget;
315
+ if (!targetCollection) throw new Error("Relation is missing a valid `target` collection.");
316
+ const newRelation = { ...relation };
317
+ newRelation.target = () => {
318
+ if (typeof rawTarget === "string") return resolveCollection && resolveCollection(rawTarget) || targetCollection;
319
+ else if (typeof rawTarget === "function") {
320
+ const evaluated = rawTarget();
321
+ if (typeof evaluated === "string") return resolveCollection && resolveCollection(evaluated) || targetCollection;
322
+ return evaluated;
323
+ }
324
+ return targetCollection;
325
+ };
326
+ if (!newRelation.relationName) newRelation.relationName = toSnakeCase(targetCollection.slug);
327
+ if (!newRelation.direction) if (newRelation.foreignKeyOnTarget) newRelation.direction = "inverse";
328
+ else if (newRelation.through) newRelation.direction = "owning";
329
+ else if (newRelation.cardinality === "many") newRelation.direction = "inverse";
330
+ else newRelation.direction = "owning";
331
+ if (!newRelation.joinPath) {
332
+ const sourceName = toSnakeCase(sourceCollection.slug ?? sourceCollection.name);
333
+ if (newRelation.cardinality === "one" && newRelation.direction === "owning") {
334
+ if (!newRelation.localKey) newRelation.localKey = generateForeignKeyName(newRelation.relationName);
335
+ } else if (newRelation.cardinality === "one" && newRelation.direction === "inverse") {
336
+ if (!newRelation.foreignKeyOnTarget) {
337
+ let foundForeignKey = false;
338
+ try {
339
+ const targetRelations = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? targetCollection.relations || [] : [];
340
+ for (const targetRel of targetRelations) if (targetRel.direction === "owning" && targetRel.cardinality === "one" && targetRel.localKey) try {
341
+ if (targetRel.target().slug === sourceCollection.slug) {
342
+ newRelation.foreignKeyOnTarget = targetRel.localKey;
343
+ foundForeignKey = true;
344
+ break;
345
+ }
346
+ } catch (e) {
347
+ continue;
348
+ }
349
+ } catch (e) {}
350
+ if (!foundForeignKey) newRelation.foreignKeyOnTarget = generateForeignKeyName(newRelation.inverseRelationName ? toSnakeCase(newRelation.inverseRelationName) : sourceName);
351
+ }
352
+ } else if (newRelation.cardinality === "many" && newRelation.direction === "inverse") {
353
+ let isManyToManyInverse = false;
354
+ if (newRelation.inverseRelationName && !newRelation.foreignKeyOnTarget) try {
355
+ const targetRelations = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? targetCollection.relations || [] : [];
356
+ for (const targetRel of targetRelations) if (targetRel.cardinality === "many" && (targetRel.direction === "owning" || !targetRel.direction) && targetRel.relationName === newRelation.inverseRelationName) {
357
+ isManyToManyInverse = true;
358
+ break;
359
+ }
360
+ if (!isManyToManyInverse && targetCollection.properties) for (const [propKey, prop] of Object.entries(targetCollection.properties)) {
361
+ if (prop.type !== "relation") continue;
362
+ const relProp = prop;
363
+ if ((relProp.relationName || propKey) === newRelation.inverseRelationName && relProp.cardinality === "many" && (relProp.direction === "owning" || !relProp.direction)) {
364
+ isManyToManyInverse = true;
365
+ break;
366
+ }
367
+ }
368
+ } catch (e) {}
369
+ if (!isManyToManyInverse && !newRelation.foreignKeyOnTarget) newRelation.foreignKeyOnTarget = generateForeignKeyName(sourceName);
370
+ } else if (newRelation.cardinality === "many" && newRelation.direction === "owning") {
371
+ const sourceTableName = getTableName(sourceCollection);
372
+ const targetTableName = getTableName(targetCollection);
373
+ newRelation.through = {
374
+ table: newRelation.through?.table ?? [sourceTableName, targetTableName].sort().join("_"),
375
+ sourceColumn: newRelation.through?.sourceColumn ?? generateForeignKeyName(sourceName),
376
+ targetColumn: newRelation.through?.targetColumn ?? generateForeignKeyName(newRelation.relationName)
377
+ };
378
+ }
379
+ }
380
+ 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}'`);
381
+ 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}'`);
382
+ 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}'`);
383
+ return newRelation;
384
+ }
385
+ /** WeakMap cache — same collection instance always yields the same relation map. */
386
+ var _resolvedRelationsCache = /* @__PURE__ */ new WeakMap();
462
387
  function resolveCollectionRelations(collection) {
463
- const cached = _resolvedRelationsCache.get(collection);
464
- if (cached) return cached;
465
- if (!getDataSourceCapabilities(collection.driver).supportsRelations) return {};
466
- const relCollection = collection;
467
- const relations = {};
468
- const registeredRelationNames = /* @__PURE__ */ new Set();
469
- if (relCollection.relations) {
470
- relCollection.relations.forEach((relation) => {
471
- try {
472
- const normalizedRelation = sanitizeRelation(relation, collection);
473
- const relationKey = normalizedRelation.relationName;
474
- if (relationKey) {
475
- relations[relationKey] = normalizedRelation;
476
- registeredRelationNames.add(relationKey);
477
- }
478
- } catch (e) {
479
- }
480
- });
481
- }
482
- if (collection.properties) {
483
- Object.entries(collection.properties).forEach(([propKey, prop]) => {
484
- const relation = resolvePropertyRelation({
485
- propertyKey: propKey,
486
- property: prop,
487
- sourceCollection: collection
488
- });
489
- if (relation) {
490
- if (relations[propKey]) return;
491
- if (!relation.relationName) {
492
- relation.relationName = propKey;
493
- }
494
- const normalizedRelation = sanitizeRelation(relation, collection);
495
- relations[propKey] = normalizedRelation;
496
- registeredRelationNames.add(normalizedRelation.relationName ?? propKey);
497
- }
498
- });
499
- }
500
- _resolvedRelationsCache.set(collection, relations);
501
- return relations;
502
- }
503
- function resolvePropertyRelation({
504
- propertyKey,
505
- property,
506
- sourceCollection
507
- }) {
508
- if (property.type !== "relation") return void 0;
509
- const relProp = property;
510
- if (relProp.target) {
511
- return {
512
- relationName: relProp.relationName || propertyKey,
513
- target: relProp.target,
514
- cardinality: relProp.cardinality || "one",
515
- direction: relProp.direction || "owning",
516
- inverseRelationName: relProp.inverseRelationName,
517
- localKey: relProp.localKey,
518
- foreignKeyOnTarget: relProp.foreignKeyOnTarget,
519
- through: relProp.through,
520
- joinPath: relProp.joinPath,
521
- onUpdate: relProp.onUpdate,
522
- onDelete: relProp.onDelete,
523
- overrides: relProp.overrides
524
- };
525
- }
526
- console.warn(`Unrecognized or missing relation target for property '${propertyKey}' in collection '${sourceCollection.slug}'`);
527
- return void 0;
388
+ const cached = _resolvedRelationsCache.get(collection);
389
+ if (cached) return cached;
390
+ if (!getDataSourceCapabilities(collection.driver).supportsRelations) return {};
391
+ const relCollection = collection;
392
+ const relations = {};
393
+ const registeredRelationNames = /* @__PURE__ */ new Set();
394
+ if (relCollection.relations) relCollection.relations.forEach((relation) => {
395
+ try {
396
+ const normalizedRelation = sanitizeRelation(relation, collection);
397
+ const relationKey = normalizedRelation.relationName;
398
+ if (relationKey) {
399
+ relations[relationKey] = normalizedRelation;
400
+ registeredRelationNames.add(relationKey);
401
+ }
402
+ } catch (e) {}
403
+ });
404
+ if (collection.properties) Object.entries(collection.properties).forEach(([propKey, prop]) => {
405
+ const relation = resolvePropertyRelation({
406
+ propertyKey: propKey,
407
+ property: prop,
408
+ sourceCollection: collection
409
+ });
410
+ if (relation) {
411
+ if (relations[propKey]) return;
412
+ if (!relation.relationName) relation.relationName = propKey;
413
+ const normalizedRelation = sanitizeRelation(relation, collection);
414
+ relations[propKey] = normalizedRelation;
415
+ registeredRelationNames.add(normalizedRelation.relationName ?? propKey);
416
+ }
417
+ });
418
+ _resolvedRelationsCache.set(collection, relations);
419
+ return relations;
420
+ }
421
+ function resolvePropertyRelation({ propertyKey, property, sourceCollection }) {
422
+ if (property.type !== "relation") return void 0;
423
+ const relProp = property;
424
+ if (relProp.target) return {
425
+ relationName: relProp.relationName || propertyKey,
426
+ target: relProp.target,
427
+ cardinality: relProp.cardinality || "one",
428
+ direction: relProp.direction || "owning",
429
+ inverseRelationName: relProp.inverseRelationName,
430
+ localKey: relProp.localKey,
431
+ foreignKeyOnTarget: relProp.foreignKeyOnTarget,
432
+ through: relProp.through,
433
+ joinPath: relProp.joinPath,
434
+ onUpdate: relProp.onUpdate,
435
+ onDelete: relProp.onDelete,
436
+ overrides: relProp.overrides
437
+ };
438
+ console.warn(`Unrecognized or missing relation target for property '${propertyKey}' in collection '${sourceCollection.slug}'`);
528
439
  }
529
440
  function getTableName(collection) {
530
- if (getDataSourceCapabilities(collection.driver).supportsRelations) {
531
- return collection.table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
532
- }
533
- return toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
441
+ if (getDataSourceCapabilities(collection.driver).supportsRelations) return collection.table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
442
+ return toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
534
443
  }
535
444
  function getTableVarName(tableName) {
536
- return tableName.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
445
+ return tableName.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
537
446
  }
538
447
  function getEnumVarName(tableName, propName) {
539
- const tableVar = getTableVarName(tableName);
540
- const propVar = propName.charAt(0).toUpperCase() + propName.slice(1);
541
- return `${tableVar}${propVar}`;
448
+ return `${getTableVarName(tableName)}${propName.charAt(0).toUpperCase() + propName.slice(1)}`;
542
449
  }
543
450
  function getColumnName(fullColumn) {
544
- return fullColumn.includes(".") ? fullColumn.split(".").pop() : fullColumn;
545
- }
451
+ return fullColumn.includes(".") ? fullColumn.split(".").pop() : fullColumn;
452
+ }
453
+ /**
454
+ * Look up a relation by key with forgiving normalization.
455
+ *
456
+ * `resolveCollectionRelations` stores each relation under a single canonical
457
+ * key (no aliases). This helper tries the given key as-is, then falls back to
458
+ * slug form (underscores → hyphens) and snake_case form (hyphens → underscores)
459
+ * so that callers that receive a key from external input (URL path segments,
460
+ * user-provided config, etc.) can still find the right entry.
461
+ */
546
462
  function findRelation(resolvedRelations, key) {
547
- if (resolvedRelations[key]) return resolvedRelations[key];
548
- const slugKey = key.replace(/_/g, "-");
549
- if (slugKey !== key && resolvedRelations[slugKey]) return resolvedRelations[slugKey];
550
- const snakeKey = key.replace(/-/g, "_");
551
- if (snakeKey !== key && resolvedRelations[snakeKey]) return resolvedRelations[snakeKey];
552
- return void 0;
553
- }
463
+ if (resolvedRelations[key]) return resolvedRelations[key];
464
+ const slugKey = key.replace(/_/g, "-");
465
+ if (slugKey !== key && resolvedRelations[slugKey]) return resolvedRelations[slugKey];
466
+ const snakeKey = key.replace(/-/g, "_");
467
+ if (snakeKey !== key && resolvedRelations[snakeKey]) return resolvedRelations[snakeKey];
468
+ }
469
+ //#endregion
470
+ //#region src/util/resolutions.ts
554
471
  function resolveProperty(props) {
555
- const {
556
- property,
557
- ignoreMissingFields = false,
558
- ...rest
559
- } = props;
560
- let resultProperty;
561
- if (isPropertyBuilder(property)) {
562
- const path = rest.path;
563
- if (!path) {
564
- resultProperty = property;
565
- } else {
566
- const usedPropertyValue = rest.propertyKey ? getIn$1(rest.values, rest.propertyKey) : void 0;
567
- const dynamicProps = property.dynamicProps?.({
568
- ...rest,
569
- path,
570
- propertyValue: usedPropertyValue,
571
- values: rest.values ?? {},
572
- previousValues: rest.previousValues ?? rest.values ?? {}
573
- });
574
- resultProperty = mergeDeep(property, dynamicProps ?? {});
575
- }
576
- } else {
577
- resultProperty = property;
578
- }
579
- if (resultProperty?.dynamicProps && rest.path) {
580
- const path = rest.path;
581
- const usedPropertyValue = rest.propertyKey ? getIn$1(rest.values, rest.propertyKey) : void 0;
582
- const dynamicPropsResult = resultProperty.dynamicProps({
583
- ...rest,
584
- path,
585
- propertyValue: usedPropertyValue,
586
- values: rest.values ?? {},
587
- previousValues: rest.previousValues ?? rest.values ?? {}
588
- });
589
- if (dynamicPropsResult) {
590
- resultProperty = mergeDeep(resultProperty, dynamicPropsResult);
591
- }
592
- }
593
- let resolvedProperty;
594
- if (resultProperty?.type === "map" && resultProperty.properties) {
595
- const properties = resolveProperties({
596
- ignoreMissingFields,
597
- ...rest,
598
- properties: resultProperty.properties
599
- });
600
- resolvedProperty = {
601
- ...resultProperty,
602
- properties
603
- };
604
- } else if (resultProperty?.type === "array") {
605
- resolvedProperty = resultProperty;
606
- } else if ((resultProperty?.type === "string" || resultProperty?.type === "number") && resultProperty.enum) {
607
- resolvedProperty = resolvePropertyEnum(resultProperty);
608
- } else {
609
- resolvedProperty = resultProperty;
610
- }
611
- if (resolvedProperty?.propertyConfig && !isDefaultFieldConfigId(resolvedProperty.propertyConfig)) {
612
- const cmsFields = rest.propertyConfigs;
613
- if (!cmsFields && !ignoreMissingFields) {
614
- 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`);
615
- }
616
- const customField = cmsFields?.[resolvedProperty.propertyConfig];
617
- if (!customField) {
618
- 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`);
619
- return resolvedProperty;
620
- }
621
- if (customField.property) {
622
- const restConfigProperty = {
623
- ...customField.property
624
- };
625
- delete restConfigProperty.propertyConfig;
626
- const customFieldProperty = resolveProperty({
627
- property: {
628
- name: "",
629
- ...restConfigProperty
630
- },
631
- ignoreMissingFields,
632
- ...rest
633
- });
634
- if (customFieldProperty) {
635
- resolvedProperty = mergeDeep(customFieldProperty, resolvedProperty);
636
- }
637
- }
638
- }
639
- return resolvedProperty;
472
+ const { property, ignoreMissingFields = false, ...rest } = props;
473
+ let resultProperty;
474
+ if (isPropertyBuilder(property)) {
475
+ const path = rest.path;
476
+ if (!path) resultProperty = property;
477
+ else {
478
+ const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : void 0;
479
+ const dynamicProps = property.dynamicProps?.({
480
+ ...rest,
481
+ path,
482
+ propertyValue: usedPropertyValue,
483
+ values: rest.values ?? {},
484
+ previousValues: rest.previousValues ?? rest.values ?? {}
485
+ });
486
+ resultProperty = mergeDeep(property, dynamicProps ?? {});
487
+ }
488
+ } else resultProperty = property;
489
+ if (resultProperty?.dynamicProps && rest.path) {
490
+ const path = rest.path;
491
+ const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : void 0;
492
+ const dynamicPropsResult = resultProperty.dynamicProps({
493
+ ...rest,
494
+ path,
495
+ propertyValue: usedPropertyValue,
496
+ values: rest.values ?? {},
497
+ previousValues: rest.previousValues ?? rest.values ?? {}
498
+ });
499
+ if (dynamicPropsResult) resultProperty = mergeDeep(resultProperty, dynamicPropsResult);
500
+ }
501
+ let resolvedProperty;
502
+ if (resultProperty?.type === "map" && resultProperty.properties) {
503
+ const properties = resolveProperties({
504
+ ignoreMissingFields,
505
+ ...rest,
506
+ properties: resultProperty.properties
507
+ });
508
+ resolvedProperty = {
509
+ ...resultProperty,
510
+ properties
511
+ };
512
+ } else if (resultProperty?.type === "array") resolvedProperty = resultProperty;
513
+ else if ((resultProperty?.type === "string" || resultProperty?.type === "number") && resultProperty.enum) resolvedProperty = resolvePropertyEnum(resultProperty);
514
+ else resolvedProperty = resultProperty;
515
+ if (resolvedProperty?.propertyConfig && !isDefaultFieldConfigId(resolvedProperty.propertyConfig)) {
516
+ const cmsFields = rest.propertyConfigs;
517
+ 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`);
518
+ const customField = cmsFields?.[resolvedProperty.propertyConfig];
519
+ if (!customField) {
520
+ 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`);
521
+ return resolvedProperty;
522
+ }
523
+ if (customField.property) {
524
+ const restConfigProperty = { ...customField.property };
525
+ delete restConfigProperty.propertyConfig;
526
+ const customFieldProperty = resolveProperty({
527
+ property: {
528
+ name: "",
529
+ ...restConfigProperty
530
+ },
531
+ ignoreMissingFields,
532
+ ...rest
533
+ });
534
+ if (customFieldProperty) resolvedProperty = mergeDeep(customFieldProperty, resolvedProperty);
535
+ }
536
+ }
537
+ return resolvedProperty;
640
538
  }
641
539
  function resolveRelationProperty(property, relations, propertyKey) {
642
- if (property.relation) {
643
- return property;
644
- }
645
- const name = property.relationName || propertyKey;
646
- const relation = name ? relations.find((rel) => rel.relationName === name) : void 0;
647
- if (!relation) {
648
- throw Error(`Relation ${name ?? "(unnamed)"} not found`);
649
- }
650
- return {
651
- ...property,
652
- relation
653
- };
654
- }
540
+ if (property.relation) return property;
541
+ const name = property.relationName || propertyKey;
542
+ const relation = name ? relations.find((rel) => rel.relationName === name) : void 0;
543
+ if (!relation) throw Error(`Relation ${name ?? "(unnamed)"} not found`);
544
+ return {
545
+ ...property,
546
+ relation
547
+ };
548
+ }
549
+ /**
550
+ * Resolve enum aliases for a string or number property
551
+ * @param property
552
+ */
655
553
  function resolvePropertyEnum(property) {
656
- if (typeof property.enum === "object") {
657
- return {
658
- ...property,
659
- enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? []
660
- };
661
- }
662
- return property;
663
- }
664
- function resolveProperties({
665
- propertyKey,
666
- properties,
667
- ignoreMissingFields,
668
- ...props
669
- }) {
670
- return Object.entries(properties).map(([key, property]) => {
671
- const childResolvedProperty = resolveProperty({
672
- propertyKey: propertyKey ? `${propertyKey}.${key}` : void 0,
673
- property,
674
- ignoreMissingFields,
675
- ...props
676
- });
677
- if (!childResolvedProperty) return {};
678
- return {
679
- [key]: childResolvedProperty
680
- };
681
- }).filter((a) => a !== null).reduce((a, b) => ({
682
- ...a,
683
- ...b
684
- }), {});
685
- }
686
- function resolveArrayProperties({
687
- propertyKey,
688
- property,
689
- ignoreMissingFields = false,
690
- ...props
691
- }) {
692
- const propertyValue = propertyKey ? getIn$1(props.values, propertyKey) : void 0;
693
- if (property.of) {
694
- if (Array.isArray(property.of)) {
695
- return property.of.map((p, index) => {
696
- return resolveProperty({
697
- propertyKey: `${propertyKey}.${index}`,
698
- property: p,
699
- ignoreMissingFields,
700
- ...props,
701
- index
702
- });
703
- });
704
- } else {
705
- const of = property.of;
706
- const resolvedProperties = getArrayResolvedProperties({
707
- propertyValue,
708
- propertyKey,
709
- property,
710
- ignoreMissingFields,
711
- ...props
712
- });
713
- const {
714
- values,
715
- previousValues,
716
- ...rest
717
- } = props;
718
- const ofProperty = resolveProperty({
719
- // we don't want to pass the values of the parent entity
720
- property: of,
721
- ignoreMissingFields,
722
- ...rest
723
- });
724
- if (!ofProperty && !ignoreMissingFields) throw Error("When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property");
725
- return resolvedProperties;
726
- }
727
- } else if (property.oneOf) {
728
- const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;
729
- const resolvedProperties = Array.isArray(propertyValue) ? propertyValue.map((v, index) => {
730
- const type = v && v[typeField];
731
- const childProperty = property.oneOf?.properties[type];
732
- if (!type || !childProperty) return null;
733
- return resolveProperty({
734
- propertyKey: `${propertyKey}.${index}`,
735
- property: childProperty,
736
- ignoreMissingFields,
737
- ...props
738
- });
739
- }).filter((e) => Boolean(e)) : [];
740
- return resolvedProperties;
741
- } else if (!("Field" in (property.ui || {}) && property.ui?.Field)) {
742
- throw Error(`The array property (${propertyKey}) needs to declare an 'of' or a 'oneOf' property, or provide a custom \`Field\` component`);
743
- } else {
744
- return [];
745
- }
746
- }
747
- function getArrayResolvedProperties({
748
- propertyKey,
749
- propertyValue,
750
- property,
751
- ...props
752
- }) {
753
- const of = property.of;
754
- if (!of) throw Error(`Trying to resolve an array property (${propertyKey}) without providing an 'of' property`);
755
- return Array.isArray(propertyValue) ? propertyValue.map((v, index) => {
756
- return resolveProperty({
757
- propertyKey: `${propertyKey}.${index}`,
758
- property: Array.isArray(of) ? of[index] : of,
759
- ...props,
760
- index
761
- });
762
- }).filter((e) => Boolean(e)) : [];
554
+ if (typeof property.enum === "object") return {
555
+ ...property,
556
+ enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? []
557
+ };
558
+ return property;
559
+ }
560
+ /**
561
+ * Resolve enums and arrays for properties
562
+ * @param properties
563
+ * @param value
564
+ */
565
+ function resolveProperties({ propertyKey, properties, ignoreMissingFields, ...props }) {
566
+ return Object.entries(properties).map(([key, property]) => {
567
+ const childResolvedProperty = resolveProperty({
568
+ propertyKey: propertyKey ? `${propertyKey}.${key}` : void 0,
569
+ property,
570
+ ignoreMissingFields,
571
+ ...props
572
+ });
573
+ if (!childResolvedProperty) return {};
574
+ return { [key]: childResolvedProperty };
575
+ }).filter((a) => a !== null).reduce((a, b) => ({
576
+ ...a,
577
+ ...b
578
+ }), {});
579
+ }
580
+ function resolveArrayProperties({ propertyKey, property, ignoreMissingFields = false, ...props }) {
581
+ const propertyValue = propertyKey ? getIn(props.values, propertyKey) : void 0;
582
+ if (property.of) if (Array.isArray(property.of)) return property.of.map((p, index) => {
583
+ return resolveProperty({
584
+ propertyKey: `${propertyKey}.${index}`,
585
+ property: p,
586
+ ignoreMissingFields,
587
+ ...props,
588
+ index
589
+ });
590
+ });
591
+ else {
592
+ const of = property.of;
593
+ const resolvedProperties = getArrayResolvedProperties({
594
+ propertyValue,
595
+ propertyKey,
596
+ property,
597
+ ignoreMissingFields,
598
+ ...props
599
+ });
600
+ const { values, previousValues, ...rest } = props;
601
+ if (!resolveProperty({
602
+ property: of,
603
+ ignoreMissingFields,
604
+ ...rest
605
+ }) && !ignoreMissingFields) throw Error("When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property");
606
+ return resolvedProperties;
607
+ }
608
+ else if (property.oneOf) {
609
+ const typeField = property.oneOf?.typeField ?? "type";
610
+ return Array.isArray(propertyValue) ? propertyValue.map((v, index) => {
611
+ const type = v && v[typeField];
612
+ const childProperty = property.oneOf?.properties[type];
613
+ if (!type || !childProperty) return null;
614
+ return resolveProperty({
615
+ propertyKey: `${propertyKey}.${index}`,
616
+ property: childProperty,
617
+ ignoreMissingFields,
618
+ ...props
619
+ });
620
+ }).filter((e) => Boolean(e)) : [];
621
+ } 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`);
622
+ else return [];
623
+ }
624
+ function getArrayResolvedProperties({ propertyKey, propertyValue, property, ...props }) {
625
+ const of = property.of;
626
+ if (!of) throw Error(`Trying to resolve an array property (${propertyKey}) without providing an 'of' property`);
627
+ return Array.isArray(propertyValue) ? propertyValue.map((v, index) => {
628
+ return resolveProperty({
629
+ propertyKey: `${propertyKey}.${index}`,
630
+ property: Array.isArray(of) ? of[index] : of,
631
+ ...props,
632
+ index
633
+ });
634
+ }).filter((e) => Boolean(e)) : [];
763
635
  }
764
636
  function resolveEnumValues(input) {
765
- if (typeof input === "object") {
766
- return Object.entries(input).map(([id, value]) => typeof value === "string" ? {
767
- id,
768
- label: value
769
- } : value);
770
- } else if (Array.isArray(input)) {
771
- return input;
772
- } else {
773
- return void 0;
774
- }
637
+ if (typeof input === "object") return Object.entries(input).map(([id, value]) => typeof value === "string" ? {
638
+ id,
639
+ label: value
640
+ } : value);
641
+ else if (Array.isArray(input)) return input;
642
+ else return;
775
643
  }
776
644
  function getSubcollections(collection) {
777
- if (collection.childCollections) {
778
- return collection.childCollections() ?? [];
779
- }
780
- if (getDataSourceCapabilities(collection.driver).supportsSubcollections && collection.subcollections) {
781
- return collection.subcollections() ?? [];
782
- }
783
- if (getDataSourceCapabilities(collection.driver).supportsRelations) {
784
- const resolvedRelations = resolveCollectionRelations(collection);
785
- const manyRelations = Object.values(resolvedRelations).filter((r) => r.cardinality === "many");
786
- return manyRelations.map((r) => {
787
- const target = r.target();
788
- if (!target) return void 0;
789
- const relationKey = r.relationName || target.slug;
790
- let customName;
791
- if (collection.properties) {
792
- const prop = Object.entries(collection.properties).find(([_, p]) => p.type === "relation" && p.relationName === relationKey);
793
- if (prop && prop[1].name) {
794
- customName = prop[1].name;
795
- }
796
- }
797
- const baseOverrides = {
798
- slug: relationKey
799
- };
800
- if (customName) {
801
- baseOverrides.name = customName;
802
- baseOverrides.singularName = customName;
803
- }
804
- const targetWithOverrides = {
805
- ...target,
806
- ...baseOverrides
807
- };
808
- return r.overrides ? mergeDeep(targetWithOverrides, r.overrides) : targetWithOverrides;
809
- }).filter((c) => Boolean(c));
810
- }
811
- return [];
812
- }
645
+ if (collection.childCollections) return collection.childCollections() ?? [];
646
+ if (getDataSourceCapabilities(collection.driver).supportsSubcollections && collection.subcollections) return collection.subcollections() ?? [];
647
+ if (getDataSourceCapabilities(collection.driver).supportsRelations) {
648
+ const resolvedRelations = resolveCollectionRelations(collection);
649
+ return Object.values(resolvedRelations).filter((r) => r.cardinality === "many").map((r) => {
650
+ const target = r.target();
651
+ if (!target) return void 0;
652
+ const relationKey = r.relationName || target.slug;
653
+ let customName;
654
+ if (collection.properties) {
655
+ const prop = Object.entries(collection.properties).find(([_, p]) => p.type === "relation" && p.relationName === relationKey);
656
+ if (prop && prop[1].name) customName = prop[1].name;
657
+ }
658
+ const baseOverrides = { slug: relationKey };
659
+ if (customName) {
660
+ baseOverrides.name = customName;
661
+ baseOverrides.singularName = customName;
662
+ }
663
+ const targetWithOverrides = {
664
+ ...target,
665
+ ...baseOverrides
666
+ };
667
+ return r.overrides ? mergeDeep(targetWithOverrides, r.overrides) : targetWithOverrides;
668
+ }).filter((c) => Boolean(c));
669
+ }
670
+ return [];
671
+ }
672
+ //#endregion
673
+ //#region src/util/permissions.ts
813
674
  function evaluateAST(sqlString, auth, entity) {
814
- if (!entity) return true;
815
- let cleanedSQL = sqlString.trim();
816
- while (cleanedSQL.startsWith("(") && cleanedSQL.endsWith(")")) {
817
- let openCount = 0;
818
- let isEnclosing = true;
819
- for (let i = 0; i < cleanedSQL.length - 1; i++) {
820
- if (cleanedSQL[i] === "(") openCount++;
821
- else if (cleanedSQL[i] === ")") openCount--;
822
- if (openCount === 0) {
823
- isEnclosing = false;
824
- break;
825
- }
826
- }
827
- if (isEnclosing) {
828
- cleanedSQL = cleanedSQL.substring(1, cleanedSQL.length - 1).trim();
829
- } else {
830
- break;
831
- }
832
- }
833
- const splitByTopLevel = (str, delimiter) => {
834
- const parts = [];
835
- let current = "";
836
- let openCount = 0;
837
- let i = 0;
838
- while (i < str.length) {
839
- if (str[i] === "(") openCount++;
840
- else if (str[i] === ")") openCount--;
841
- if (openCount === 0 && str.substring(i).toUpperCase().startsWith(delimiter)) {
842
- parts.push(current);
843
- current = "";
844
- i += delimiter.length;
845
- } else {
846
- current += str[i];
847
- i++;
848
- }
849
- }
850
- parts.push(current);
851
- return parts;
852
- };
853
- const orParts = splitByTopLevel(cleanedSQL, " OR ");
854
- if (orParts.length > 1) {
855
- return orParts.some((part) => evaluateAST(part, auth, entity));
856
- }
857
- const andParts = splitByTopLevel(cleanedSQL, " AND ");
858
- if (andParts.length > 1) {
859
- return andParts.every((part) => evaluateAST(part, auth, entity));
860
- }
861
- const upperSQL = cleanedSQL.toUpperCase();
862
- if (upperSQL.includes(" IN ") || upperSQL.includes(" EXISTS ")) {
863
- return true;
864
- }
865
- const roleIntersectMatch = cleanedSQL.match(/string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*&&\s*ARRAY\[(.*?)\]/i);
866
- if (roleIntersectMatch && roleIntersectMatch[1]) {
867
- const requiredRoles = roleIntersectMatch[1].split(",").map((r) => r.trim().replace(/'/g, ""));
868
- const userRoles = auth.user?.roles || [];
869
- return requiredRoles.some((r) => userRoles.includes(r));
870
- }
871
- const roleContainMatch = cleanedSQL.match(/string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*@>\s*ARRAY\[(.*?)\]/i);
872
- if (roleContainMatch && roleContainMatch[1]) {
873
- const requiredRoles = roleContainMatch[1].split(",").map((r) => r.trim().replace(/'/g, ""));
874
- const userRoles = auth.user?.roles || [];
875
- return requiredRoles.every((r) => userRoles.includes(r));
876
- }
877
- const pattern1 = new RegExp("^\\{?([a-zA-Z0-9_]+)\\}?\\s*=\\s*(?:current_setting\\s*\\(\\s*'app\\.user_id'\\s*\\)|auth\\.uid\\(\\))");
878
- const pattern2 = new RegExp("^(?:current_setting\\s*\\(\\s*'app\\.user_id'\\s*\\)|auth\\.uid\\(\\))\\s*=\\s*\\{?([a-zA-Z0-9_]+)\\}?");
879
- const match1 = cleanedSQL.match(pattern1);
880
- if (match1 && match1[1]) {
881
- return entity.values[match1[1]] === auth.user?.uid;
882
- }
883
- const match2 = cleanedSQL.match(pattern2);
884
- if (match2 && match2[1]) {
885
- return entity.values[match2[1]] === auth.user?.uid;
886
- }
887
- const simpleEqualityMatch = cleanedSQL.match(/^\{?([\w_]+)\}?\s*(=|!=)\s*'([^']+)'$/i);
888
- if (simpleEqualityMatch) {
889
- const field = simpleEqualityMatch[1];
890
- const operator = simpleEqualityMatch[2];
891
- const value = simpleEqualityMatch[3];
892
- const entityValue = entity.values[field];
893
- if (operator === "=") return entityValue === value;
894
- if (operator === "!=") return entityValue !== value;
895
- }
896
- return true;
675
+ if (!entity) return true;
676
+ let cleanedSQL = sqlString.trim();
677
+ while (cleanedSQL.startsWith("(") && cleanedSQL.endsWith(")")) {
678
+ let openCount = 0;
679
+ let isEnclosing = true;
680
+ for (let i = 0; i < cleanedSQL.length - 1; i++) {
681
+ if (cleanedSQL[i] === "(") openCount++;
682
+ else if (cleanedSQL[i] === ")") openCount--;
683
+ if (openCount === 0) {
684
+ isEnclosing = false;
685
+ break;
686
+ }
687
+ }
688
+ if (isEnclosing) cleanedSQL = cleanedSQL.substring(1, cleanedSQL.length - 1).trim();
689
+ else break;
690
+ }
691
+ const splitByTopLevel = (str, delimiter) => {
692
+ const parts = [];
693
+ let current = "";
694
+ let openCount = 0;
695
+ let i = 0;
696
+ while (i < str.length) {
697
+ if (str[i] === "(") openCount++;
698
+ else if (str[i] === ")") openCount--;
699
+ if (openCount === 0 && str.substring(i).toUpperCase().startsWith(delimiter)) {
700
+ parts.push(current);
701
+ current = "";
702
+ i += delimiter.length;
703
+ } else {
704
+ current += str[i];
705
+ i++;
706
+ }
707
+ }
708
+ parts.push(current);
709
+ return parts;
710
+ };
711
+ const orParts = splitByTopLevel(cleanedSQL, " OR ");
712
+ if (orParts.length > 1) return orParts.some((part) => evaluateAST(part, auth, entity));
713
+ const andParts = splitByTopLevel(cleanedSQL, " AND ");
714
+ if (andParts.length > 1) return andParts.every((part) => evaluateAST(part, auth, entity));
715
+ const upperSQL = cleanedSQL.toUpperCase();
716
+ if (upperSQL.includes(" IN ") || upperSQL.includes(" EXISTS ")) return true;
717
+ const roleIntersectMatch = cleanedSQL.match(/string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*&&\s*ARRAY\[(.*?)\]/i);
718
+ if (roleIntersectMatch && roleIntersectMatch[1]) {
719
+ const requiredRoles = roleIntersectMatch[1].split(",").map((r) => r.trim().replace(/'/g, ""));
720
+ const userRoles = auth.user?.roles || [];
721
+ return requiredRoles.some((r) => userRoles.includes(r));
722
+ }
723
+ const roleContainMatch = cleanedSQL.match(/string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*@>\s*ARRAY\[(.*?)\]/i);
724
+ if (roleContainMatch && roleContainMatch[1]) {
725
+ const requiredRoles = roleContainMatch[1].split(",").map((r) => r.trim().replace(/'/g, ""));
726
+ const userRoles = auth.user?.roles || [];
727
+ return requiredRoles.every((r) => userRoles.includes(r));
728
+ }
729
+ const pattern1 = /* @__PURE__ */ new RegExp("^\\{?([a-zA-Z0-9_]+)\\}?\\s*=\\s*(?:current_setting\\s*\\(\\s*'app\\.user_id'\\s*\\)|auth\\.uid\\(\\))");
730
+ const pattern2 = /* @__PURE__ */ new RegExp("^(?:current_setting\\s*\\(\\s*'app\\.user_id'\\s*\\)|auth\\.uid\\(\\))\\s*=\\s*\\{?([a-zA-Z0-9_]+)\\}?");
731
+ const match1 = cleanedSQL.match(pattern1);
732
+ if (match1 && match1[1]) return entity.values[match1[1]] === auth.user?.uid;
733
+ const match2 = cleanedSQL.match(pattern2);
734
+ if (match2 && match2[1]) return entity.values[match2[1]] === auth.user?.uid;
735
+ const simpleEqualityMatch = cleanedSQL.match(/^\{?([\w_]+)\}?\s*(=|!=)\s*'([^']+)'$/i);
736
+ if (simpleEqualityMatch) {
737
+ const field = simpleEqualityMatch[1];
738
+ const operator = simpleEqualityMatch[2];
739
+ const value = simpleEqualityMatch[3];
740
+ const entityValue = entity.values[field];
741
+ if (operator === "=") return entityValue === value;
742
+ if (operator === "!=") return entityValue !== value;
743
+ }
744
+ return true;
897
745
  }
898
746
  function evaluateRule(rule, auth, entity) {
899
- if (rule.access === "public") return true;
900
- if (rule.ownerField) {
901
- if (!entity) ;
902
- else {
903
- if (entity.values[rule.ownerField] !== auth.user?.uid) return false;
904
- }
905
- }
906
- if (rule.using && !evaluateAST(rule.using, auth, entity)) return false;
907
- if (rule.withCheck && !evaluateAST(rule.withCheck, auth, entity)) return false;
908
- return true;
747
+ if (rule.access === "public") return true;
748
+ if (rule.ownerField) {
749
+ if (!entity) {} else if (entity.values[rule.ownerField] !== auth.user?.uid) return false;
750
+ }
751
+ if (rule.using && !evaluateAST(rule.using, auth, entity)) return false;
752
+ if (rule.withCheck && !evaluateAST(rule.withCheck, auth, entity)) return false;
753
+ return true;
909
754
  }
910
755
  function checkOperation(collection, authContext, entity, targetOperation) {
911
- const securityRules = getDataSourceCapabilities(collection.driver).supportsRLS ? collection.securityRules : void 0;
912
- if (!securityRules || securityRules.length === 0) {
913
- return true;
914
- }
915
- const applicableRules = securityRules.filter((r) => r.operation === targetOperation || r.operation === "all" || r.operations?.includes(targetOperation) || r.operations?.includes("all"));
916
- if (applicableRules.length === 0) return false;
917
- const userRoleIds = authContext.user?.roles ?? [];
918
- const userRoles = [...userRoleIds, "public"];
919
- const roleApplicableRules = applicableRules.filter((rule) => {
920
- if (!rule.roles || rule.roles.length === 0) return true;
921
- return rule.roles.some((r) => userRoles.includes(r));
922
- });
923
- if (roleApplicableRules.length === 0) return false;
924
- let grantedByPermissive = false;
925
- let deniedByRestrictive = false;
926
- for (const rule of roleApplicableRules) {
927
- const mode = rule.mode || "permissive";
928
- const passed = evaluateRule(rule, authContext, entity);
929
- if (mode === "restrictive" && !passed) {
930
- deniedByRestrictive = true;
931
- break;
932
- }
933
- if (mode === "permissive" && passed) {
934
- grantedByPermissive = true;
935
- }
936
- }
937
- if (deniedByRestrictive) return false;
938
- const hasPermissive = roleApplicableRules.some((r) => (r.mode || "permissive") === "permissive");
939
- if (hasPermissive) {
940
- return grantedByPermissive;
941
- } else {
942
- return false;
943
- }
756
+ const securityRules = getDataSourceCapabilities(collection.driver).supportsRLS ? collection.securityRules : void 0;
757
+ if (!securityRules || securityRules.length === 0) return true;
758
+ const applicableRules = securityRules.filter((r) => r.operation === targetOperation || r.operation === "all" || r.operations?.includes(targetOperation) || r.operations?.includes("all"));
759
+ if (applicableRules.length === 0) return false;
760
+ const userRoles = [...authContext.user?.roles ?? [], "public"];
761
+ const roleApplicableRules = applicableRules.filter((rule) => {
762
+ if (!rule.roles || rule.roles.length === 0) return true;
763
+ return rule.roles.some((r) => userRoles.includes(r));
764
+ });
765
+ if (roleApplicableRules.length === 0) return false;
766
+ let grantedByPermissive = false;
767
+ let deniedByRestrictive = false;
768
+ for (const rule of roleApplicableRules) {
769
+ const mode = rule.mode || "permissive";
770
+ const passed = evaluateRule(rule, authContext, entity);
771
+ if (mode === "restrictive" && !passed) {
772
+ deniedByRestrictive = true;
773
+ break;
774
+ }
775
+ if (mode === "permissive" && passed) grantedByPermissive = true;
776
+ }
777
+ if (deniedByRestrictive) return false;
778
+ if (roleApplicableRules.some((r) => (r.mode || "permissive") === "permissive")) return grantedByPermissive;
779
+ else return false;
944
780
  }
945
781
  function canReadCollection(collection, authContext) {
946
- return checkOperation(collection, authContext, null, "select");
782
+ return checkOperation(collection, authContext, null, "select");
947
783
  }
948
784
  function canEditEntity(collection, authContext, path, entity) {
949
- return checkOperation(collection, authContext, entity, "update");
785
+ return checkOperation(collection, authContext, entity, "update");
950
786
  }
951
787
  function canCreateEntity(collection, authContext, path, entity) {
952
- return checkOperation(collection, authContext, entity, "insert");
788
+ return checkOperation(collection, authContext, entity, "insert");
953
789
  }
954
790
  function canDeleteEntity(collection, authContext, path, entity) {
955
- return checkOperation(collection, authContext, entity, "delete");
791
+ return checkOperation(collection, authContext, entity, "delete");
956
792
  }
793
+ //#endregion
794
+ //#region src/util/references.ts
957
795
  function getEntityImagePreviewPropertyKey(collection) {
958
- for (const key in collection.properties) {
959
- const property = collection.properties[key];
960
- if (property.type === "string" && property.storage?.acceptedFiles?.includes("image/*")) {
961
- return key;
962
- }
963
- }
964
- for (const key in collection.properties) {
965
- const property = collection.properties[key];
966
- if (property.type === "array" && !Array.isArray(property.of) && property.of?.type === "string" && property.of.storage?.acceptedFiles?.includes("image/*")) {
967
- return key;
968
- }
969
- }
970
- for (const key in collection.properties) {
971
- const property = collection.properties[key];
972
- if (property.type === "string" && property.ui?.url === "image") {
973
- return key;
974
- }
975
- }
976
- for (const key in collection.properties) {
977
- const property = collection.properties[key];
978
- if (property.type === "array" && property.of && !Array.isArray(property.of) && property.of.type === "string" && property.of.url === "image") {
979
- return key;
980
- }
981
- }
982
- for (const key in collection.properties) {
983
- const property = collection.properties[key];
984
- if (property.type === "string" && property.storage && !property.storage.acceptedFiles) {
985
- return key;
986
- }
987
- }
988
- for (const key in collection.properties) {
989
- const property = collection.properties[key];
990
- if (property.type === "array" && !Array.isArray(property.of) && property.of?.type === "string" && property.of.storage && !property.of.storage.acceptedFiles) {
991
- return key;
992
- }
993
- }
994
- return void 0;
995
- }
796
+ for (const key in collection.properties) {
797
+ const property = collection.properties[key];
798
+ if (property.type === "string" && property.storage?.acceptedFiles?.includes("image/*")) return key;
799
+ }
800
+ for (const key in collection.properties) {
801
+ const property = collection.properties[key];
802
+ if (property.type === "array" && !Array.isArray(property.of) && property.of?.type === "string" && property.of.storage?.acceptedFiles?.includes("image/*")) return key;
803
+ }
804
+ for (const key in collection.properties) {
805
+ const property = collection.properties[key];
806
+ if (property.type === "string" && property.ui?.url === "image") return key;
807
+ }
808
+ for (const key in collection.properties) {
809
+ const property = collection.properties[key];
810
+ if (property.type === "array" && property.of && !Array.isArray(property.of) && property.of.type === "string" && property.of.url === "image") return key;
811
+ }
812
+ for (const key in collection.properties) {
813
+ const property = collection.properties[key];
814
+ if (property.type === "string" && property.storage && !property.storage.acceptedFiles) return key;
815
+ }
816
+ for (const key in collection.properties) {
817
+ const property = collection.properties[key];
818
+ if (property.type === "array" && !Array.isArray(property.of) && property.of?.type === "string" && property.of.storage && !property.of.storage.acceptedFiles) return key;
819
+ }
820
+ }
821
+ //#endregion
822
+ //#region src/util/navigation_utils.ts
996
823
  function removeInitialAndTrailingSlashes(s) {
997
- return removeInitialSlash(removeTrailingSlash(s));
824
+ return removeInitialSlash(removeTrailingSlash(s));
998
825
  }
999
826
  function removeInitialSlash(s) {
1000
- if (s.startsWith("/")) return s.slice(1);
1001
- else return s;
827
+ if (s.startsWith("/")) return s.slice(1);
828
+ else return s;
1002
829
  }
1003
830
  function removeTrailingSlash(s) {
1004
- if (s.endsWith("/")) return s.slice(0, -1);
1005
- else return s;
831
+ if (s.endsWith("/")) return s.slice(0, -1);
832
+ else return s;
1006
833
  }
1007
834
  function addInitialSlash(s) {
1008
- if (s.startsWith("/")) return s;
1009
- else return `/${s}`;
835
+ if (s.startsWith("/")) return s;
836
+ else return `/${s}`;
1010
837
  }
1011
838
  function getLastSegment(path) {
1012
- const cleanPath = removeInitialAndTrailingSlashes(path);
1013
- if (cleanPath.includes("/")) {
1014
- const segments = cleanPath.split("/");
1015
- return segments[segments.length - 1];
1016
- }
1017
- return cleanPath;
839
+ const cleanPath = removeInitialAndTrailingSlashes(path);
840
+ if (cleanPath.includes("/")) {
841
+ const segments = cleanPath.split("/");
842
+ return segments[segments.length - 1];
843
+ }
844
+ return cleanPath;
1018
845
  }
1019
846
  function resolveCollectionPathIds(path, allCollections) {
1020
- let remainingPath = removeInitialAndTrailingSlashes(path);
1021
- if (!remainingPath) {
1022
- return "";
1023
- }
1024
- let currentCollections = allCollections;
1025
- const resolvedPathParts = [];
1026
- while (remainingPath.length > 0) {
1027
- if (!currentCollections || currentCollections.length === 0) {
1028
- console.warn(`resolveCollectionPathIds: Path structure implies subcollections, but none found before segment starting with "${remainingPath}" in original path "${path}". Appending remaining original path.`);
1029
- resolvedPathParts.push(remainingPath);
1030
- remainingPath = "";
1031
- break;
1032
- }
1033
- let foundMatch = false;
1034
- const potentialMatches = currentCollections.flatMap((col) => [{
1035
- col,
1036
- match: col.slug
1037
- }]).filter((p) => p.match && remainingPath.startsWith(p.match)).sort((a, b) => b.match.length - a.match.length);
1038
- if (potentialMatches.length > 0) {
1039
- const {
1040
- col: foundCollection,
1041
- match: matchString
1042
- } = potentialMatches[0];
1043
- resolvedPathParts.push(foundCollection.slug);
1044
- remainingPath = removeInitialSlash(remainingPath.substring(matchString.length));
1045
- if (remainingPath.length === 0) {
1046
- foundMatch = true;
1047
- break;
1048
- }
1049
- const idSeparatorIndex = remainingPath.indexOf("/");
1050
- let entityId;
1051
- if (idSeparatorIndex > -1) {
1052
- entityId = remainingPath.substring(0, idSeparatorIndex);
1053
- remainingPath = remainingPath.substring(idSeparatorIndex + 1);
1054
- } else {
1055
- entityId = remainingPath;
1056
- remainingPath = "";
1057
- console.warn(`resolveCollectionPathIds: Path seems to end with an entity ID "${entityId}" instead of a collection segment in original path "${path}". This might indicate an invalid input path.`);
1058
- }
1059
- resolvedPathParts.push(entityId);
1060
- currentCollections = getSubcollections(foundCollection);
1061
- foundMatch = true;
1062
- if (!currentCollections && remainingPath.length > 0) {
1063
- 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.`);
1064
- resolvedPathParts.push(remainingPath);
1065
- remainingPath = "";
1066
- break;
1067
- }
1068
- }
1069
- if (!foundMatch) {
1070
- console.warn(`resolveCollectionPathIds: Collection definition not found for segment starting with "${remainingPath}" in original path "${path}". Appending remaining original path.`);
1071
- resolvedPathParts.push(remainingPath);
1072
- remainingPath = "";
1073
- break;
1074
- }
1075
- }
1076
- return resolvedPathParts.join("/");
1077
- }
847
+ let remainingPath = removeInitialAndTrailingSlashes(path);
848
+ if (!remainingPath) return "";
849
+ let currentCollections = allCollections;
850
+ const resolvedPathParts = [];
851
+ while (remainingPath.length > 0) {
852
+ if (!currentCollections || currentCollections.length === 0) {
853
+ console.warn(`resolveCollectionPathIds: Path structure implies subcollections, but none found before segment starting with "${remainingPath}" in original path "${path}". Appending remaining original path.`);
854
+ resolvedPathParts.push(remainingPath);
855
+ remainingPath = "";
856
+ break;
857
+ }
858
+ let foundMatch = false;
859
+ const potentialMatches = currentCollections.flatMap((col) => [{
860
+ col,
861
+ match: col.slug
862
+ }]).filter((p) => p.match && remainingPath.startsWith(p.match)).sort((a, b) => b.match.length - a.match.length);
863
+ if (potentialMatches.length > 0) {
864
+ const { col: foundCollection, match: matchString } = potentialMatches[0];
865
+ resolvedPathParts.push(foundCollection.slug);
866
+ remainingPath = removeInitialSlash(remainingPath.substring(matchString.length));
867
+ if (remainingPath.length === 0) {
868
+ foundMatch = true;
869
+ break;
870
+ }
871
+ const idSeparatorIndex = remainingPath.indexOf("/");
872
+ let entityId;
873
+ if (idSeparatorIndex > -1) {
874
+ entityId = remainingPath.substring(0, idSeparatorIndex);
875
+ remainingPath = remainingPath.substring(idSeparatorIndex + 1);
876
+ } else {
877
+ entityId = remainingPath;
878
+ remainingPath = "";
879
+ console.warn(`resolveCollectionPathIds: Path seems to end with an entity ID "${entityId}" instead of a collection segment in original path "${path}". This might indicate an invalid input path.`);
880
+ }
881
+ resolvedPathParts.push(entityId);
882
+ currentCollections = getSubcollections(foundCollection);
883
+ foundMatch = true;
884
+ if (!currentCollections && remainingPath.length > 0) {
885
+ 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.`);
886
+ resolvedPathParts.push(remainingPath);
887
+ remainingPath = "";
888
+ break;
889
+ }
890
+ }
891
+ if (!foundMatch) {
892
+ console.warn(`resolveCollectionPathIds: Collection definition not found for segment starting with "${remainingPath}" in original path "${path}". Appending remaining original path.`);
893
+ resolvedPathParts.push(remainingPath);
894
+ remainingPath = "";
895
+ break;
896
+ }
897
+ }
898
+ return resolvedPathParts.join("/");
899
+ }
900
+ /**
901
+ * Find the corresponding view at any depth for a given path.
902
+ * Note that path or segments of the paths can be collection aliases.
903
+ * @param slugOrPath
904
+ * @param collections
905
+ */
1078
906
  function getCollectionBySlugWithin(slugOrPath, collections) {
1079
- const subpaths = removeInitialAndTrailingSlashes(slugOrPath).split("/");
1080
- if (subpaths.length % 2 === 0) {
1081
- throw Error(`getCollectionBySlug: Collection paths must have an odd number of segments: ${slugOrPath}`);
1082
- }
1083
- const subpathCombinations = getCollectionPathsCombinations(subpaths);
1084
- let result;
1085
- for (let i = 0; i < subpathCombinations.length; i++) {
1086
- const subpathCombination = subpathCombinations[i];
1087
- const navigationEntry = collections && collections.sort((a, b) => (a.slug ?? "").localeCompare(b.slug ?? "")).find((entry) => entry.slug === subpathCombination);
1088
- if (navigationEntry) {
1089
- if (subpathCombination === slugOrPath) {
1090
- result = navigationEntry;
1091
- } else if (getSubcollections(navigationEntry).length > 0) {
1092
- const newPath = slugOrPath.replace(subpathCombination, "").split("/").slice(2).join("/");
1093
- if (newPath.length > 0) result = getCollectionBySlugWithin(newPath, getSubcollections(navigationEntry));
1094
- }
1095
- }
1096
- if (result) break;
1097
- }
1098
- return result;
1099
- }
907
+ const subpaths = removeInitialAndTrailingSlashes(slugOrPath).split("/");
908
+ if (subpaths.length % 2 === 0) throw Error(`getCollectionBySlug: Collection paths must have an odd number of segments: ${slugOrPath}`);
909
+ const subpathCombinations = getCollectionPathsCombinations(subpaths);
910
+ let result;
911
+ for (let i = 0; i < subpathCombinations.length; i++) {
912
+ const subpathCombination = subpathCombinations[i];
913
+ const navigationEntry = collections && collections.sort((a, b) => (a.slug ?? "").localeCompare(b.slug ?? "")).find((entry) => entry.slug === subpathCombination);
914
+ if (navigationEntry) {
915
+ if (subpathCombination === slugOrPath) result = navigationEntry;
916
+ else if (getSubcollections(navigationEntry).length > 0) {
917
+ const newPath = slugOrPath.replace(subpathCombination, "").split("/").slice(2).join("/");
918
+ if (newPath.length > 0) result = getCollectionBySlugWithin(newPath, getSubcollections(navigationEntry));
919
+ }
920
+ }
921
+ if (result) break;
922
+ }
923
+ return result;
924
+ }
925
+ /**
926
+ * Get the subcollection combinations from a path:
927
+ * "sites/es/locales" => ["sites/es/locales", "sites"]
928
+ * @param subpaths
929
+ */
1100
930
  function getCollectionPathsCombinations(subpaths) {
1101
- const entries = subpaths.length > 0 && subpaths.length % 2 === 0 ? subpaths.splice(0, subpaths.length - 1) : subpaths;
1102
- const length = entries.length;
1103
- const result = [];
1104
- for (let i = length; i > 0; i = i - 2) {
1105
- result.push(entries.slice(0, i).join("/"));
1106
- }
1107
- return result;
1108
- }
931
+ const entries = subpaths.length > 0 && subpaths.length % 2 === 0 ? subpaths.splice(0, subpaths.length - 1) : subpaths;
932
+ const length = entries.length;
933
+ const result = [];
934
+ for (let i = length; i > 0; i = i - 2) result.push(entries.slice(0, i).join("/"));
935
+ return result;
936
+ }
937
+ //#endregion
938
+ //#region src/util/navigation_from_path.ts
1109
939
  function getNavigationEntriesFromPath(props) {
1110
- const {
1111
- path,
1112
- collections = [],
1113
- currentFullPath
1114
- } = props;
1115
- const subpaths = removeInitialAndTrailingSlashes(path).split("/");
1116
- const subpathCombinations = getCollectionPathsCombinations(subpaths);
1117
- const result = [];
1118
- for (let i = 0; i < subpathCombinations.length; i++) {
1119
- const subpathCombination = subpathCombinations[i];
1120
- const collection = collections && collections.find((entry) => entry.slug === subpathCombination);
1121
- if (collection) {
1122
- const collectionPath = currentFullPath && currentFullPath.length > 0 ? currentFullPath + "/" + collection.slug : collection.slug;
1123
- result.push({
1124
- type: "collection",
1125
- id: collection.slug,
1126
- slug: collectionPath,
1127
- path: collectionPath,
1128
- collection
1129
- });
1130
- const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
1131
- const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
1132
- if (nextSegments.length > 0) {
1133
- const entityId = nextSegments[0];
1134
- const path2 = collectionPath + "/" + entityId;
1135
- result.push({
1136
- type: "entity",
1137
- entityId,
1138
- slug: collectionPath,
1139
- path: path2,
1140
- parentCollection: collection
1141
- });
1142
- if (nextSegments.length > 1) {
1143
- const newPath = nextSegments.slice(1).join("/");
1144
- if (!collection) {
1145
- throw Error("collection not found resolving path: " + collection);
1146
- }
1147
- const entityViews = collection.entityViews;
1148
- const customView = entityViews && entityViews.map((entry) => resolveEntityView(entry, props.contextEntityViews)).filter((v) => v != null).find((entry) => entry.key === newPath);
1149
- const subcollections = getSubcollections(collection);
1150
- if (customView) {
1151
- result.push({
1152
- type: "custom_view",
1153
- slug: collectionPath,
1154
- entityId,
1155
- path: path2 + "/" + customView.key,
1156
- view: customView
1157
- });
1158
- } else if (subcollections) {
1159
- result.push(...getNavigationEntriesFromPath({
1160
- path: newPath,
1161
- collections: subcollections,
1162
- currentFullPath: path2,
1163
- contextEntityViews: props.contextEntityViews
1164
- }));
1165
- }
1166
- }
1167
- }
1168
- break;
1169
- }
1170
- }
1171
- return result;
940
+ const { path, collections = [], currentFullPath } = props;
941
+ const subpathCombinations = getCollectionPathsCombinations(removeInitialAndTrailingSlashes(path).split("/"));
942
+ const result = [];
943
+ for (let i = 0; i < subpathCombinations.length; i++) {
944
+ const subpathCombination = subpathCombinations[i];
945
+ const collection = collections && collections.find((entry) => entry.slug === subpathCombination);
946
+ if (collection) {
947
+ const collectionPath = currentFullPath && currentFullPath.length > 0 ? currentFullPath + "/" + collection.slug : collection.slug;
948
+ result.push({
949
+ type: "collection",
950
+ id: collection.slug,
951
+ slug: collectionPath,
952
+ path: collectionPath,
953
+ collection
954
+ });
955
+ const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
956
+ const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
957
+ if (nextSegments.length > 0) {
958
+ const entityId = nextSegments[0];
959
+ const path = collectionPath + "/" + entityId;
960
+ result.push({
961
+ type: "entity",
962
+ entityId,
963
+ slug: collectionPath,
964
+ path,
965
+ parentCollection: collection
966
+ });
967
+ if (nextSegments.length > 1) {
968
+ const newPath = nextSegments.slice(1).join("/");
969
+ if (!collection) throw Error("collection not found resolving path: " + collection);
970
+ const entityViews = collection.entityViews;
971
+ const customView = entityViews && entityViews.map((entry) => resolveEntityView(entry, props.contextEntityViews)).filter((v) => v != null).find((entry) => entry.key === newPath);
972
+ const subcollections = getSubcollections(collection);
973
+ if (customView) result.push({
974
+ type: "custom_view",
975
+ slug: collectionPath,
976
+ entityId,
977
+ path: path + "/" + customView.key,
978
+ view: customView
979
+ });
980
+ else if (subcollections) result.push(...getNavigationEntriesFromPath({
981
+ path: newPath,
982
+ collections: subcollections,
983
+ currentFullPath: path,
984
+ contextEntityViews: props.contextEntityViews
985
+ }));
986
+ }
987
+ }
988
+ break;
989
+ }
990
+ }
991
+ return result;
1172
992
  }
1173
993
  function resolveEntityView(entityView, contextEntityViews) {
1174
- if (typeof entityView === "string") {
1175
- return contextEntityViews?.find((entry) => entry.key === entityView);
1176
- } else {
1177
- return entityView;
1178
- }
994
+ if (typeof entityView === "string") return contextEntityViews?.find((entry) => entry.key === entityView);
995
+ else return entityView;
1179
996
  }
997
+ //#endregion
998
+ //#region src/util/parent_references_from_path.ts
1180
999
  function getParentReferencesFromPath(props) {
1181
- const {
1182
- path,
1183
- collections = [],
1184
- currentFullPath
1185
- } = props;
1186
- const subpaths = removeInitialAndTrailingSlashes(path).split("/");
1187
- const subpathCombinations = getCollectionPathsCombinations(subpaths);
1188
- const result = [];
1189
- for (let i = 0; i < subpathCombinations.length; i++) {
1190
- const subpathCombination = subpathCombinations[i];
1191
- const collection = collections && collections.find((entry) => entry.slug === subpathCombination);
1192
- if (collection) {
1193
- const collectionPath = currentFullPath && currentFullPath.length > 0 ? currentFullPath + "/" + collection.slug : collection.slug;
1194
- const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
1195
- const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
1196
- if (nextSegments.length > 0) {
1197
- const entityId = nextSegments[0];
1198
- const path2 = collectionPath + "/" + entityId;
1199
- result.push(new EntityReference({
1200
- id: entityId,
1201
- path: collectionPath
1202
- }));
1203
- if (nextSegments.length > 1) {
1204
- const newPath = nextSegments.slice(1).join("/");
1205
- if (!collection) {
1206
- throw Error("collection not found resolving path: " + collection);
1207
- }
1208
- if (getSubcollections(collection).length > 0) {
1209
- result.push(...getParentReferencesFromPath({
1210
- path: newPath,
1211
- collections: getSubcollections(collection),
1212
- currentFullPath: path2
1213
- }));
1214
- }
1215
- }
1216
- }
1217
- break;
1218
- }
1219
- }
1220
- return result;
1221
- }
1000
+ const { path, collections = [], currentFullPath } = props;
1001
+ const subpathCombinations = getCollectionPathsCombinations(removeInitialAndTrailingSlashes(path).split("/"));
1002
+ const result = [];
1003
+ for (let i = 0; i < subpathCombinations.length; i++) {
1004
+ const subpathCombination = subpathCombinations[i];
1005
+ const collection = collections && collections.find((entry) => entry.slug === subpathCombination);
1006
+ if (collection) {
1007
+ const collectionPath = currentFullPath && currentFullPath.length > 0 ? currentFullPath + "/" + collection.slug : collection.slug;
1008
+ const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
1009
+ const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
1010
+ if (nextSegments.length > 0) {
1011
+ const entityId = nextSegments[0];
1012
+ const path = collectionPath + "/" + entityId;
1013
+ result.push(new EntityReference({
1014
+ id: entityId,
1015
+ path: collectionPath
1016
+ }));
1017
+ if (nextSegments.length > 1) {
1018
+ const newPath = nextSegments.slice(1).join("/");
1019
+ if (!collection) throw Error("collection not found resolving path: " + collection);
1020
+ if (getSubcollections(collection).length > 0) result.push(...getParentReferencesFromPath({
1021
+ path: newPath,
1022
+ collections: getSubcollections(collection),
1023
+ currentFullPath: path
1024
+ }));
1025
+ }
1026
+ }
1027
+ break;
1028
+ }
1029
+ }
1030
+ return result;
1031
+ }
1032
+ //#endregion
1033
+ //#region src/util/builders.ts
1034
+ /**
1035
+ * Identity function we use to defeat the type system of Typescript and build
1036
+ * collection views with all its properties
1037
+ * @param collection
1038
+ * @group Builder
1039
+ */
1222
1040
  function buildCollection(collection) {
1223
- return collection;
1224
- }
1041
+ return collection;
1042
+ }
1043
+ /**
1044
+ * Identity function we use to defeat the type system of Typescript and preserve
1045
+ * the property keys.
1046
+ * @param property
1047
+ * @group Builder
1048
+ */
1225
1049
  function buildProperty(property) {
1226
- return property;
1227
- }
1050
+ return property;
1051
+ }
1052
+ /**
1053
+ * Identity function we use to defeat the type system of Typescript and preserve
1054
+ * the properties keys.
1055
+ * @param properties
1056
+ * @group Builder
1057
+ */
1228
1058
  function buildProperties(properties) {
1229
- return properties;
1230
- }
1059
+ return properties;
1060
+ }
1061
+ /**
1062
+ * Identity function we use to defeat the type system of Typescript and preserve
1063
+ * the properties keys.
1064
+ * @param propertiesOrBuilder
1065
+ * @group Builder
1066
+ */
1231
1067
  function buildPropertiesOrBuilder(propertiesOrBuilder) {
1232
- return propertiesOrBuilder;
1233
- }
1068
+ return propertiesOrBuilder;
1069
+ }
1070
+ /**
1071
+ * Identity function we use to defeat the type system of Typescript and preserve
1072
+ * the properties keys.
1073
+ * @param enumValues
1074
+ * @group Builder
1075
+ */
1234
1076
  function buildEnum(enumValues) {
1235
- return enumValues;
1236
- }
1077
+ return enumValues;
1078
+ }
1079
+ /**
1080
+ * Identity function we use to defeat the type system of Typescript and preserve
1081
+ * the properties keys.
1082
+ * @param enumValueConfig
1083
+ * @group Builder
1084
+ */
1237
1085
  function buildEnumValueConfig(enumValueConfig) {
1238
- return enumValueConfig;
1239
- }
1086
+ return enumValueConfig;
1087
+ }
1088
+ /**
1089
+ * Identity function we use to defeat the type system of Typescript and preserve
1090
+ * the properties keys.
1091
+ * @param callbacks
1092
+ * @group Builder
1093
+ */
1240
1094
  function buildEntityCallbacks(callbacks) {
1241
- return callbacks;
1242
- }
1095
+ return callbacks;
1096
+ }
1097
+ /**
1098
+ * Identity function we use to defeat the type system of Typescript and build
1099
+ * additional field delegates views with all its properties
1100
+ * @param additionalFieldDelegate
1101
+ * @group Builder
1102
+ */
1243
1103
  function buildAdditionalFieldDelegate(additionalFieldDelegate) {
1244
- return additionalFieldDelegate;
1245
- }
1246
- async function resolveStorageFilenameString({
1247
- input,
1248
- storage,
1249
- values,
1250
- entityId,
1251
- path,
1252
- property,
1253
- file,
1254
- propertyKey
1255
- }) {
1256
- let result;
1257
- if (typeof input === "function") {
1258
- result = await input({
1259
- path,
1260
- entityId,
1261
- values,
1262
- property,
1263
- file,
1264
- storage,
1265
- propertyKey
1266
- });
1267
- if (!result) console.warn("Storage callback returned empty result. Using default name value");
1268
- } else {
1269
- result = replacePlaceholders({
1270
- file,
1271
- input,
1272
- entityId,
1273
- propertyKey,
1274
- path
1275
- });
1276
- }
1277
- if (!result) result = randomString() + "_" + file.name;
1278
- return result;
1279
- }
1280
- function resolveStoragePathString({
1281
- input,
1282
- storage,
1283
- values,
1284
- entityId,
1285
- path,
1286
- property,
1287
- file,
1288
- propertyKey
1289
- }) {
1290
- let result;
1291
- if (typeof input === "function") {
1292
- result = input({
1293
- path,
1294
- entityId,
1295
- values,
1296
- property,
1297
- file,
1298
- storage,
1299
- propertyKey
1300
- });
1301
- if (!result) console.warn("Storage callback returned empty result. Using default name value");
1302
- } else {
1303
- result = replacePlaceholders({
1304
- file,
1305
- input,
1306
- entityId,
1307
- propertyKey,
1308
- path
1309
- });
1310
- }
1311
- if (!result) result = randomString() + "_" + file.name;
1312
- return result;
1313
- }
1314
- function replacePlaceholders({
1315
- file,
1316
- input,
1317
- entityId,
1318
- propertyKey,
1319
- path
1320
- }) {
1321
- const ext = file.name.split(".").pop();
1322
- let result = input.replace("{propertyKey}", propertyKey).replace("{rand}", randomString()).replace("{file}", file.name).replace("{file.type}", file.type);
1323
- if (entityId) {
1324
- result = result.replace("{entityId}", String(entityId));
1325
- }
1326
- if (path) {
1327
- result = result.replace("{path}", path);
1328
- }
1329
- if (ext) {
1330
- result = result.replace("{file.ext}", ext);
1331
- const name = file.name.replace(`.${ext}`, "");
1332
- result = result.replace("{file.name}", name);
1333
- }
1334
- if (!result) result = randomString() + "_" + file.name;
1335
- return result;
1336
- }
1104
+ return additionalFieldDelegate;
1105
+ }
1106
+ //#endregion
1107
+ //#region src/util/storage.ts
1108
+ async function resolveStorageFilenameString({ input, storage, values, entityId, path, property, file, propertyKey }) {
1109
+ let result;
1110
+ if (typeof input === "function") {
1111
+ result = await input({
1112
+ path,
1113
+ entityId,
1114
+ values,
1115
+ property,
1116
+ file,
1117
+ storage,
1118
+ propertyKey
1119
+ });
1120
+ if (!result) console.warn("Storage callback returned empty result. Using default name value");
1121
+ } else result = replacePlaceholders({
1122
+ file,
1123
+ input,
1124
+ entityId,
1125
+ propertyKey,
1126
+ path
1127
+ });
1128
+ if (!result) result = randomString() + "_" + file.name;
1129
+ return result;
1130
+ }
1131
+ function resolveStoragePathString({ input, storage, values, entityId, path, property, file, propertyKey }) {
1132
+ let result;
1133
+ if (typeof input === "function") {
1134
+ result = input({
1135
+ path,
1136
+ entityId,
1137
+ values,
1138
+ property,
1139
+ file,
1140
+ storage,
1141
+ propertyKey
1142
+ });
1143
+ if (!result) console.warn("Storage callback returned empty result. Using default name value");
1144
+ } else result = replacePlaceholders({
1145
+ file,
1146
+ input,
1147
+ entityId,
1148
+ propertyKey,
1149
+ path
1150
+ });
1151
+ if (!result) result = randomString() + "_" + file.name;
1152
+ return result;
1153
+ }
1154
+ function replacePlaceholders({ file, input, entityId, propertyKey, path }) {
1155
+ const ext = file.name.split(".").pop();
1156
+ let result = input.replace("{propertyKey}", propertyKey).replace("{rand}", randomString()).replace("{file}", file.name).replace("{file.type}", file.type);
1157
+ if (entityId) result = result.replace("{entityId}", String(entityId));
1158
+ if (path) result = result.replace("{path}", path);
1159
+ if (ext) {
1160
+ result = result.replace("{file.ext}", ext);
1161
+ const name = file.name.replace(`.${ext}`, "");
1162
+ result = result.replace("{file.name}", name);
1163
+ }
1164
+ if (!result) result = randomString() + "_" + file.name;
1165
+ return result;
1166
+ }
1167
+ //#endregion
1168
+ //#region src/util/callbacks.ts
1169
+ /**
1170
+ * Helper function to recursively check if there are any callbacks in the properties.
1171
+ */
1337
1172
  function hasPropertyCallbacks(properties, callbackName) {
1338
- if (!properties) return false;
1339
- for (const property of Object.values(properties)) {
1340
- if (property.callbacks?.[callbackName]) return true;
1341
- if (property.type === "map" && property.properties) {
1342
- if (hasPropertyCallbacks(property.properties, callbackName)) return true;
1343
- } else if (property.type === "array" && property.of) {
1344
- const ofs = Array.isArray(property.of) ? property.of : [property.of];
1345
- for (const of of ofs) {
1346
- if (of.callbacks?.[callbackName]) return true;
1347
- if (of.type === "map" && of.properties && hasPropertyCallbacks(of.properties, callbackName)) return true;
1348
- }
1349
- }
1350
- }
1351
- return false;
1352
- }
1173
+ if (!properties) return false;
1174
+ for (const property of Object.values(properties)) {
1175
+ if (property.callbacks?.[callbackName]) return true;
1176
+ if (property.type === "map" && property.properties) {
1177
+ if (hasPropertyCallbacks(property.properties, callbackName)) return true;
1178
+ } else if (property.type === "array" && property.of) {
1179
+ const ofs = Array.isArray(property.of) ? property.of : [property.of];
1180
+ for (const of of ofs) {
1181
+ if (of.callbacks?.[callbackName]) return true;
1182
+ if (of.type === "map" && of.properties && hasPropertyCallbacks(of.properties, callbackName)) return true;
1183
+ }
1184
+ }
1185
+ }
1186
+ return false;
1187
+ }
1188
+ /**
1189
+ * Recursively process properties to apply field-level hooks.
1190
+ */
1353
1191
  async function processProperties(properties, values, previousValues, propsContext, callbackName) {
1354
- if (!values || typeof values !== "object") return values;
1355
- const result = {
1356
- ...values
1357
- };
1358
- for (const [key, property] of Object.entries(properties)) {
1359
- if (result[key] === void 0) continue;
1360
- let currentValue = result[key];
1361
- const previousValue = previousValues?.[key];
1362
- if (property.type === "array" && Array.isArray(currentValue)) {
1363
- if (property.of && !Array.isArray(property.of)) {
1364
- currentValue = await Promise.all(currentValue.map(async (item, index) => {
1365
- const prevItem = Array.isArray(previousValue) ? previousValue[index] : void 0;
1366
- const singlePropData = {
1367
- "_tmp": property.of
1368
- };
1369
- const res = await processProperties(singlePropData, {
1370
- "_tmp": item
1371
- }, {
1372
- "_tmp": prevItem
1373
- }, propsContext, callbackName);
1374
- return res["_tmp"];
1375
- }));
1376
- }
1377
- } else if (property.type === "map" && property.properties && typeof currentValue === "object") {
1378
- currentValue = await processProperties(property.properties, currentValue, previousValue ?? {}, propsContext, callbackName);
1379
- }
1380
- if (property.callbacks?.[callbackName]) {
1381
- const cbRes = await Promise.resolve(property.callbacks[callbackName]({
1382
- ...propsContext,
1383
- value: currentValue,
1384
- previousValue
1385
- }));
1386
- if (cbRes !== void 0) {
1387
- currentValue = cbRes;
1388
- }
1389
- }
1390
- result[key] = currentValue;
1391
- }
1392
- return result;
1393
- }
1394
- const buildPropertyCallbacks = (properties) => {
1395
- if (!properties) return void 0;
1396
- const propertyCallbacks = {};
1397
- if (hasPropertyCallbacks(properties, "afterRead")) {
1398
- propertyCallbacks.afterRead = async (props) => {
1399
- const processedValues = await processProperties(properties, props.entity.values, props.entity.values, props, "afterRead");
1400
- return {
1401
- ...props.entity,
1402
- values: processedValues
1403
- };
1404
- };
1405
- }
1406
- if (hasPropertyCallbacks(properties, "beforeSave")) {
1407
- propertyCallbacks.beforeSave = async (props) => {
1408
- return await processProperties(properties, props.values, props.previousValues ?? {}, props, "beforeSave");
1409
- };
1410
- }
1411
- return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : void 0;
1192
+ if (!values || typeof values !== "object") return values;
1193
+ const result = { ...values };
1194
+ for (const [key, property] of Object.entries(properties)) {
1195
+ if (result[key] === void 0) continue;
1196
+ let currentValue = result[key];
1197
+ const previousValue = previousValues?.[key];
1198
+ if (property.type === "array" && Array.isArray(currentValue)) {
1199
+ if (property.of && !Array.isArray(property.of)) currentValue = await Promise.all(currentValue.map(async (item, index) => {
1200
+ const prevItem = Array.isArray(previousValue) ? previousValue[index] : void 0;
1201
+ return (await processProperties({ "_tmp": property.of }, { "_tmp": item }, { "_tmp": prevItem }, propsContext, callbackName))["_tmp"];
1202
+ }));
1203
+ } else if (property.type === "map" && property.properties && typeof currentValue === "object") currentValue = await processProperties(property.properties, currentValue, previousValue ?? {}, propsContext, callbackName);
1204
+ if (property.callbacks?.[callbackName]) {
1205
+ const cbRes = await Promise.resolve(property.callbacks[callbackName]({
1206
+ ...propsContext,
1207
+ value: currentValue,
1208
+ previousValue
1209
+ }));
1210
+ if (cbRes !== void 0) currentValue = cbRes;
1211
+ }
1212
+ result[key] = currentValue;
1213
+ }
1214
+ return result;
1215
+ }
1216
+ /**
1217
+ * Helper function to extract field-level PropertyCallbacks from a properties schema
1218
+ * and wrap them into an EntityCallbacks object recursively.
1219
+ */
1220
+ var buildPropertyCallbacks = (properties) => {
1221
+ if (!properties) return void 0;
1222
+ const propertyCallbacks = {};
1223
+ if (hasPropertyCallbacks(properties, "afterRead")) propertyCallbacks.afterRead = async (props) => {
1224
+ const processedValues = await processProperties(properties, props.entity.values, props.entity.values, props, "afterRead");
1225
+ return {
1226
+ ...props.entity,
1227
+ values: processedValues
1228
+ };
1229
+ };
1230
+ if (hasPropertyCallbacks(properties, "beforeSave")) propertyCallbacks.beforeSave = async (props) => {
1231
+ return await processProperties(properties, props.values, props.previousValues ?? {}, props, "beforeSave");
1232
+ };
1233
+ return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : void 0;
1412
1234
  };
1413
- function getIn(obj, path) {
1414
- if (!obj || !path) return void 0;
1415
- return path.split(".").reduce((acc, part) => acc && acc[part], obj);
1416
- }
1417
- let operationsRegistered = false;
1235
+ //#endregion
1236
+ //#region src/util/conditions.ts
1237
+ /**
1238
+ * Access a nested property from an object via dot notation.
1239
+ */
1240
+ function getIn$1(obj, path) {
1241
+ if (!obj || !path) return void 0;
1242
+ return path.split(".").reduce((acc, part) => acc && acc[part], obj);
1243
+ }
1244
+ var operationsRegistered = false;
1245
+ /**
1246
+ * Register custom JSON Logic operations for Rebase.
1247
+ * Call this once at app initialization.
1248
+ */
1418
1249
  function registerConditionOperations() {
1419
- if (operationsRegistered) return;
1420
- jsonLogic.add_operation("hasRole", function(roleId) {
1421
- return this?.user?.roles?.includes(roleId) ?? false;
1422
- });
1423
- jsonLogic.add_operation("hasAnyRole", function(roleIds) {
1424
- if (!this?.user?.roles || !Array.isArray(roleIds)) return false;
1425
- return roleIds.some((role) => this.user.roles.includes(role));
1426
- });
1427
- jsonLogic.add_operation("isToday", (timestamp) => {
1428
- if (!timestamp) return false;
1429
- const date = new Date(timestamp);
1430
- const today = /* @__PURE__ */ new Date();
1431
- return date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
1432
- });
1433
- jsonLogic.add_operation("isPast", (timestamp) => {
1434
- if (!timestamp) return false;
1435
- return timestamp < Date.now();
1436
- });
1437
- jsonLogic.add_operation("isFuture", (timestamp) => {
1438
- if (!timestamp) return false;
1439
- return timestamp > Date.now();
1440
- });
1441
- operationsRegistered = true;
1442
- }
1250
+ if (operationsRegistered) return;
1251
+ jsonLogic.add_operation("hasRole", function(roleId) {
1252
+ return this?.user?.roles?.includes(roleId) ?? false;
1253
+ });
1254
+ jsonLogic.add_operation("hasAnyRole", function(roleIds) {
1255
+ if (!this?.user?.roles || !Array.isArray(roleIds)) return false;
1256
+ return roleIds.some((role) => this.user.roles.includes(role));
1257
+ });
1258
+ jsonLogic.add_operation("isToday", (timestamp) => {
1259
+ if (!timestamp) return false;
1260
+ const date = new Date(timestamp);
1261
+ const today = /* @__PURE__ */ new Date();
1262
+ return date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
1263
+ });
1264
+ jsonLogic.add_operation("isPast", (timestamp) => {
1265
+ if (!timestamp) return false;
1266
+ return timestamp < Date.now();
1267
+ });
1268
+ jsonLogic.add_operation("isFuture", (timestamp) => {
1269
+ if (!timestamp) return false;
1270
+ return timestamp > Date.now();
1271
+ });
1272
+ operationsRegistered = true;
1273
+ }
1274
+ /**
1275
+ * Evaluate a JSON Logic rule against the given context.
1276
+ */
1443
1277
  function evaluateCondition(rule, context) {
1444
- registerConditionOperations();
1445
- return jsonLogic.apply(rule, context);
1278
+ registerConditionOperations();
1279
+ return jsonLogic.apply(rule, context);
1446
1280
  }
1281
+ /**
1282
+ * Convert a value to a format suitable for JSON Logic evaluation.
1283
+ * Specifically handles Date objects by converting them to Unix timestamps.
1284
+ */
1447
1285
  function serializeValueForConditions(value) {
1448
- if (value === null || value === void 0) {
1449
- return value;
1450
- }
1451
- if (value instanceof Date) {
1452
- return value.getTime();
1453
- }
1454
- if (typeof value?.toMillis === "function") {
1455
- return value.toMillis();
1456
- }
1457
- if (typeof value?.toDate === "function") {
1458
- return value.toDate().getTime();
1459
- }
1460
- if (Array.isArray(value)) {
1461
- return value.map(serializeValueForConditions);
1462
- }
1463
- if (typeof value === "object") {
1464
- const result = {};
1465
- for (const key of Object.keys(value)) {
1466
- result[key] = serializeValueForConditions(value[key]);
1467
- }
1468
- return result;
1469
- }
1470
- return value;
1471
- }
1286
+ if (value === null || value === void 0) return value;
1287
+ if (value instanceof Date) return value.getTime();
1288
+ if (typeof value?.toMillis === "function") return value.toMillis();
1289
+ if (typeof value?.toDate === "function") return value.toDate().getTime();
1290
+ if (Array.isArray(value)) return value.map(serializeValueForConditions);
1291
+ if (typeof value === "object") {
1292
+ const result = {};
1293
+ for (const key of Object.keys(value)) result[key] = serializeValueForConditions(value[key]);
1294
+ return result;
1295
+ }
1296
+ return value;
1297
+ }
1298
+ /**
1299
+ * Build a ConditionContext from the current property resolution context.
1300
+ */
1472
1301
  function buildConditionContext(params) {
1473
- const {
1474
- propertyKey,
1475
- values,
1476
- previousValues,
1477
- path,
1478
- entityId,
1479
- index,
1480
- authController
1481
- } = params;
1482
- const user = authController.user;
1483
- const serializedValues = serializeValueForConditions(values ?? {});
1484
- const serializedPreviousValues = serializeValueForConditions(previousValues ?? values ?? {});
1485
- return {
1486
- values: serializedValues,
1487
- previousValues: serializedPreviousValues,
1488
- propertyValue: propertyKey ? getIn(serializedValues, propertyKey) : void 0,
1489
- path,
1490
- entityId,
1491
- isNew: !entityId,
1492
- index,
1493
- user: {
1494
- uid: user?.uid ?? "",
1495
- email: user?.email ?? null,
1496
- displayName: user?.displayName ?? null,
1497
- photoURL: user?.photoURL ?? null,
1498
- roles: (user?.roles ?? []).map((r) => typeof r === "string" ? r : r.id)
1499
- },
1500
- now: Date.now()
1501
- };
1502
- }
1302
+ const { propertyKey, values, previousValues, path, entityId, index, authController } = params;
1303
+ const user = authController.user;
1304
+ const serializedValues = serializeValueForConditions(values ?? {});
1305
+ return {
1306
+ values: serializedValues,
1307
+ previousValues: serializeValueForConditions(previousValues ?? values ?? {}),
1308
+ propertyValue: propertyKey ? getIn$1(serializedValues, propertyKey) : void 0,
1309
+ path,
1310
+ entityId,
1311
+ isNew: !entityId,
1312
+ index,
1313
+ user: {
1314
+ uid: user?.uid ?? "",
1315
+ email: user?.email ?? null,
1316
+ displayName: user?.displayName ?? null,
1317
+ photoURL: user?.photoURL ?? null,
1318
+ roles: (user?.roles ?? []).map((r) => typeof r === "string" ? r : r.id)
1319
+ },
1320
+ now: Date.now()
1321
+ };
1322
+ }
1323
+ /**
1324
+ * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.
1325
+ */
1503
1326
  function applyPropertyConditions(property, context) {
1504
- const {
1505
- conditions
1506
- } = property;
1507
- if (!conditions) return property;
1508
- const result = {
1509
- ...property
1510
- };
1511
- if (conditions.disabled) {
1512
- const isDisabled = evaluateCondition(conditions.disabled, context);
1513
- if (isDisabled) {
1514
- result.ui = result.ui || {};
1515
- result.ui.disabled = {
1516
- clearOnDisabled: conditions.clearOnDisabled ?? false,
1517
- disabledMessage: conditions.disabledMessage,
1518
- hidden: false
1519
- };
1520
- }
1521
- }
1522
- if (conditions.hidden) {
1523
- const isHidden2 = evaluateCondition(conditions.hidden, context);
1524
- if (isHidden2) {
1525
- result.ui = result.ui || {};
1526
- result.ui.disabled = {
1527
- ...typeof result.ui?.disabled === "object" ? result.ui.disabled : {},
1528
- hidden: true,
1529
- clearOnDisabled: conditions.clearOnDisabled ?? false
1530
- };
1531
- }
1532
- }
1533
- if (conditions.readOnly) {
1534
- const isReadOnly2 = evaluateCondition(conditions.readOnly, context);
1535
- if (isReadOnly2) {
1536
- result.ui = result.ui || {};
1537
- result.ui.readOnly = true;
1538
- }
1539
- }
1540
- if (conditions.required !== void 0) {
1541
- const isRequired = evaluateCondition(conditions.required, context);
1542
- result.validation = {
1543
- ...result.validation,
1544
- required: isRequired,
1545
- requiredMessage: conditions.requiredMessage
1546
- };
1547
- }
1548
- if (context.isNew && conditions.defaultValue !== void 0) {
1549
- result.defaultValue = evaluateCondition(conditions.defaultValue, context);
1550
- }
1551
- if ("enum" in result && result.enum && (conditions.enumConditions || conditions.allowedEnumValues || conditions.excludedEnumValues)) {
1552
- result.enum = applyEnumConditions(result.enum, conditions, context);
1553
- }
1554
- if (result.type === "reference") {
1555
- if (conditions.referencePath) {
1556
- result.path = evaluateCondition(conditions.referencePath, context);
1557
- }
1558
- if (conditions.referenceFilter) {
1559
- result.fixedFilter = evaluateCondition(conditions.referenceFilter, context);
1560
- }
1561
- }
1562
- if (result.type === "array") {
1563
- if (conditions.canAddElements !== void 0) {
1564
- result.canAddElements = evaluateCondition(conditions.canAddElements, context);
1565
- }
1566
- if (conditions.sortable !== void 0) {
1567
- result.sortable = evaluateCondition(conditions.sortable, context);
1568
- }
1569
- }
1570
- return result;
1571
- }
1327
+ const { conditions } = property;
1328
+ if (!conditions) return property;
1329
+ const result = { ...property };
1330
+ if (conditions.disabled) {
1331
+ if (evaluateCondition(conditions.disabled, context)) {
1332
+ result.ui = result.ui || {};
1333
+ result.ui.disabled = {
1334
+ clearOnDisabled: conditions.clearOnDisabled ?? false,
1335
+ disabledMessage: conditions.disabledMessage,
1336
+ hidden: false
1337
+ };
1338
+ }
1339
+ }
1340
+ if (conditions.hidden) {
1341
+ if (evaluateCondition(conditions.hidden, context)) {
1342
+ result.ui = result.ui || {};
1343
+ result.ui.disabled = {
1344
+ ...typeof result.ui?.disabled === "object" ? result.ui.disabled : {},
1345
+ hidden: true,
1346
+ clearOnDisabled: conditions.clearOnDisabled ?? false
1347
+ };
1348
+ }
1349
+ }
1350
+ if (conditions.readOnly) {
1351
+ if (evaluateCondition(conditions.readOnly, context)) {
1352
+ result.ui = result.ui || {};
1353
+ result.ui.readOnly = true;
1354
+ }
1355
+ }
1356
+ if (conditions.required !== void 0) {
1357
+ const isRequired = evaluateCondition(conditions.required, context);
1358
+ result.validation = {
1359
+ ...result.validation,
1360
+ required: isRequired,
1361
+ requiredMessage: conditions.requiredMessage
1362
+ };
1363
+ }
1364
+ if (context.isNew && conditions.defaultValue !== void 0) result.defaultValue = evaluateCondition(conditions.defaultValue, context);
1365
+ if ("enum" in result && result.enum && (conditions.enumConditions || conditions.allowedEnumValues || conditions.excludedEnumValues)) result.enum = applyEnumConditions(result.enum, conditions, context);
1366
+ if (result.type === "reference") {
1367
+ if (conditions.referencePath) result.path = evaluateCondition(conditions.referencePath, context);
1368
+ if (conditions.referenceFilter) result.fixedFilter = evaluateCondition(conditions.referenceFilter, context);
1369
+ }
1370
+ if (result.type === "array") {
1371
+ if (conditions.canAddElements !== void 0) result.canAddElements = evaluateCondition(conditions.canAddElements, context);
1372
+ if (conditions.sortable !== void 0) result.sortable = evaluateCondition(conditions.sortable, context);
1373
+ }
1374
+ return result;
1375
+ }
1376
+ /**
1377
+ * Convert an object with numeric keys back to an array.
1378
+ * Firestore stores arrays as {"0": "a", "1": "b"} to avoid nested arrays.
1379
+ */
1572
1380
  function objectToArray(obj) {
1573
- if (Array.isArray(obj)) return obj.map(String);
1574
- if (obj && typeof obj === "object") {
1575
- const keys = Object.keys(obj);
1576
- if (keys.length > 0 && keys.every((k) => !isNaN(Number(k)))) {
1577
- return keys.sort((a, b) => Number(a) - Number(b)).map((k) => obj[k]).filter((v) => typeof v === "string" || typeof v === "number").map(String);
1578
- }
1579
- }
1580
- return [];
1581
- }
1381
+ if (Array.isArray(obj)) return obj.map(String);
1382
+ if (obj && typeof obj === "object") {
1383
+ const keys = Object.keys(obj);
1384
+ 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);
1385
+ }
1386
+ return [];
1387
+ }
1388
+ /**
1389
+ * Apply enum-specific conditions to filter and modify enum values.
1390
+ */
1582
1391
  function applyEnumConditions(enumValues, conditions, context) {
1583
- let result = [...enumValues];
1584
- if (conditions.allowedEnumValues) {
1585
- const allowed = evaluateCondition(conditions.allowedEnumValues, context);
1586
- const allowedArray = objectToArray(allowed);
1587
- if (allowedArray.length > 0) {
1588
- result = result.filter((ev) => allowedArray.includes(String(ev.id)));
1589
- }
1590
- }
1591
- if (conditions.excludedEnumValues) {
1592
- const excluded = evaluateCondition(conditions.excludedEnumValues, context);
1593
- const excludedArray = objectToArray(excluded);
1594
- if (excludedArray.length > 0) {
1595
- result = result.filter((ev) => !excludedArray.includes(String(ev.id)));
1596
- }
1597
- }
1598
- if (conditions.enumConditions) {
1599
- result = result.map((ev) => {
1600
- const evConditions = conditions.enumConditions?.[ev.id];
1601
- if (!evConditions) return ev;
1602
- if (evConditions.hidden && evaluateCondition(evConditions.hidden, context)) {
1603
- return null;
1604
- }
1605
- if (evConditions.disabled && evaluateCondition(evConditions.disabled, context)) {
1606
- return {
1607
- ...ev,
1608
- disabled: true
1609
- };
1610
- }
1611
- return ev;
1612
- }).filter((ev) => ev !== null);
1613
- }
1614
- return result;
1615
- }
1616
- class CollectionRegistry {
1617
- // Normalized runtime layer (used by Data Grid / UI)
1618
- collectionsByTableName = /* @__PURE__ */ new Map();
1619
- collectionsBySlug = /* @__PURE__ */ new Map();
1620
- rootCollections = [];
1621
- cachedCollectionsList = null;
1622
- // Raw configuration layer (used by Collection Editor AST generator)
1623
- rawCollectionsByTableName = /* @__PURE__ */ new Map();
1624
- rawCollectionsBySlug = /* @__PURE__ */ new Map();
1625
- rawRootCollections = [];
1626
- cachedRawCollectionsList = null;
1627
- // Snapshot of raw input for idempotency check — compared BEFORE normalization
1628
- // to avoid the issue where normalization creates new objects that always fail equality.
1629
- lastRawInputSnapshot = null;
1630
- constructor(collections) {
1631
- if (collections) {
1632
- this.registerMultiple(collections);
1633
- }
1634
- }
1635
- reset() {
1636
- this.collectionsByTableName.clear();
1637
- this.collectionsBySlug.clear();
1638
- this.rootCollections = [];
1639
- this.cachedCollectionsList = null;
1640
- this.rawCollectionsByTableName.clear();
1641
- this.rawCollectionsBySlug.clear();
1642
- this.rawRootCollections = [];
1643
- this.cachedRawCollectionsList = null;
1644
- }
1645
- /**
1646
- * Registers a collection and its subcollections recursively.
1647
- * Returns true if the collections have changed, false otherwise.
1648
- *
1649
- * Idempotent: compares the raw input (before normalization) against a stored
1650
- * snapshot. Only re-normalizes and re-registers when the raw input actually changed.
1651
- * @param collections
1652
- */
1653
- registerMultiple(collections) {
1654
- const rawSnapshot = collections.map((c) => removeFunctions(c));
1655
- if (this.lastRawInputSnapshot && deepEqual(this.lastRawInputSnapshot, rawSnapshot)) {
1656
- return false;
1657
- }
1658
- this.reset();
1659
- collections.forEach((c) => {
1660
- if (c.slug) {
1661
- this.collectionsBySlug.set(c.slug, c);
1662
- }
1663
- this.collectionsByTableName.set(getTableName(c), c);
1664
- });
1665
- const normalizedCollections = collections.map((c) => this.normalizeCollection({
1666
- ...c
1667
- }));
1668
- normalizedCollections.forEach((c, index) => {
1669
- const raw = deepClone(collections[index]);
1670
- this.rootCollections.push(c);
1671
- this.rawRootCollections.push(raw);
1672
- const normalized = this.normalizeCollection(c);
1673
- this.collectionsByTableName.set(getTableName(normalized), normalized);
1674
- this.rawCollectionsByTableName.set(getTableName(raw), raw);
1675
- if (normalized.slug) {
1676
- this.collectionsBySlug.set(normalized.slug, normalized);
1677
- }
1678
- if (raw.slug) {
1679
- this.rawCollectionsBySlug.set(raw.slug, raw);
1680
- }
1681
- });
1682
- normalizedCollections.forEach((c) => {
1683
- const subcollections = getSubcollections(c);
1684
- if (subcollections && subcollections.length > 0) {
1685
- subcollections.forEach((subCollection) => {
1686
- if (!subCollection) return;
1687
- this._registerRecursively(this.normalizeCollection({
1688
- ...subCollection
1689
- }), deepClone(subCollection));
1690
- });
1691
- }
1692
- });
1693
- this.lastRawInputSnapshot = rawSnapshot;
1694
- return true;
1695
- }
1696
- register(collection, rawCollection) {
1697
- const raw = rawCollection ? deepClone(rawCollection) : deepClone(collection);
1698
- this.rootCollections.push(collection);
1699
- this.rawRootCollections.push(raw);
1700
- this._registerRecursively(collection, raw);
1701
- }
1702
- _registerRecursively(collection, rawCollection) {
1703
- if (this.collectionsByTableName.has(getTableName(collection))) {
1704
- return;
1705
- }
1706
- const normalizedCollection = this.normalizeCollection(collection);
1707
- this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);
1708
- this.rawCollectionsByTableName.set(getTableName(rawCollection), rawCollection);
1709
- if (normalizedCollection.slug) {
1710
- this.collectionsBySlug.set(normalizedCollection.slug, normalizedCollection);
1711
- }
1712
- if (rawCollection.slug) {
1713
- this.rawCollectionsBySlug.set(rawCollection.slug, rawCollection);
1714
- }
1715
- const subcollections = getSubcollections(normalizedCollection);
1716
- if (subcollections && subcollections.length > 0) {
1717
- subcollections.forEach((subCollection) => {
1718
- if (!subCollection) return;
1719
- this._registerRecursively(this.normalizeCollection({
1720
- ...subCollection
1721
- }), deepClone(subCollection));
1722
- });
1723
- }
1724
- }
1725
- normalizeCollection(collection) {
1726
- const result = {
1727
- ...collection
1728
- };
1729
- const extractedRelations = this.extractRelationsFromProperties(result.properties);
1730
- const relResult = result;
1731
- const manualRelations = getDataSourceCapabilities(result.driver).supportsRelations ? relResult.relations ?? [] : [];
1732
- const mergedRelationsRaw = [...extractedRelations];
1733
- for (const manual of manualRelations) {
1734
- const name = manual.relationName;
1735
- if (!name) {
1736
- mergedRelationsRaw.push(manual);
1737
- } else {
1738
- const existingIndex = mergedRelationsRaw.findIndex((r) => r.relationName === name);
1739
- if (existingIndex === -1) {
1740
- mergedRelationsRaw.push(manual);
1741
- } else {
1742
- mergedRelationsRaw[existingIndex] = {
1743
- ...manual,
1744
- ...mergedRelationsRaw[existingIndex]
1745
- };
1746
- }
1747
- }
1748
- }
1749
- let mergedRelations = mergedRelationsRaw;
1750
- if (getDataSourceCapabilities(result.driver).supportsRelations) {
1751
- mergedRelations = mergedRelationsRaw.map((r) => {
1752
- try {
1753
- return sanitizeRelation(r, result, (slug) => this.get(slug));
1754
- } catch {
1755
- return r;
1756
- }
1757
- });
1758
- relResult.relations = mergedRelations;
1759
- }
1760
- const properties = this.normalizeProperties(result.properties, mergedRelations);
1761
- result.properties = properties;
1762
- if (!result.childCollections) {
1763
- if (getDataSourceCapabilities(result.driver).supportsSubcollections && result.subcollections) {
1764
- result.childCollections = result.subcollections;
1765
- } else if (getDataSourceCapabilities(result.driver).supportsRelations && relResult.relations) {
1766
- const manyRelations = relResult.relations.filter((r) => r.cardinality === "many");
1767
- if (manyRelations.length > 0) {
1768
- result.childCollections = () => manyRelations.map((r) => {
1769
- const target = r.target();
1770
- return r.overrides ? mergeDeep(target, r.overrides) : target;
1771
- });
1772
- }
1773
- }
1774
- }
1775
- return result;
1776
- }
1777
- /**
1778
- * Extract Relation[] from properties that have inline relation config (i.e. `target` is set).
1779
- * This allows developers to define relations directly on properties without a separate
1780
- * `relations[]` entry on the collection.
1781
- */
1782
- extractRelationsFromProperties(properties) {
1783
- const relations = [];
1784
- for (const [key, property] of Object.entries(properties)) {
1785
- if (property.type === "relation") {
1786
- const relProp = property;
1787
- const target = relProp.target ?? relProp.relation?.target;
1788
- if (target) {
1789
- const relationName = relProp.relationName ?? relProp.relation?.relationName ?? key;
1790
- relations.push({
1791
- relationName,
1792
- target,
1793
- cardinality: relProp.cardinality ?? relProp.relation?.cardinality ?? "one",
1794
- direction: relProp.direction ?? relProp.relation?.direction ?? "owning",
1795
- inverseRelationName: relProp.inverseRelationName ?? relProp.relation?.inverseRelationName,
1796
- localKey: relProp.localKey ?? relProp.relation?.localKey,
1797
- foreignKeyOnTarget: relProp.foreignKeyOnTarget ?? relProp.relation?.foreignKeyOnTarget,
1798
- through: relProp.through ?? relProp.relation?.through,
1799
- joinPath: relProp.joinPath ?? relProp.relation?.joinPath,
1800
- onUpdate: relProp.onUpdate ?? relProp.relation?.onUpdate,
1801
- onDelete: relProp.onDelete ?? relProp.relation?.onDelete,
1802
- overrides: relProp.overrides ?? relProp.relation?.overrides
1803
- });
1804
- }
1805
- } else if (property.type === "map" && property.properties) {
1806
- relations.push(...this.extractRelationsFromProperties(property.properties));
1807
- }
1808
- }
1809
- return relations;
1810
- }
1811
- normalizeProperties(properties, relations) {
1812
- const newProperties = {};
1813
- for (const key in properties) {
1814
- newProperties[key] = this.normalizeProperty(key, properties[key], relations);
1815
- }
1816
- return newProperties;
1817
- }
1818
- normalizeProperty(key, property, relations) {
1819
- const newProperty = {
1820
- ...property
1821
- };
1822
- if (newProperty.type === "map" && newProperty.properties) {
1823
- newProperty.properties = this.normalizeProperties(newProperty.properties, relations);
1824
- } else if (newProperty.type === "array") {
1825
- const arrayProp = newProperty;
1826
- if (arrayProp.of) {
1827
- if (Array.isArray(arrayProp.of)) {
1828
- arrayProp.of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, relations));
1829
- } else {
1830
- arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, relations);
1831
- }
1832
- } else if (arrayProp.oneOf && arrayProp.oneOf.properties) {
1833
- arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.oneOf.properties, relations);
1834
- }
1835
- } else if ((newProperty.type === "string" || newProperty.type === "number") && newProperty.enum) {
1836
- const stringOrNumberProperty = newProperty;
1837
- if (typeof stringOrNumberProperty.enum === "object" && !Array.isArray(stringOrNumberProperty.enum)) {
1838
- stringOrNumberProperty.enum = enumToObjectEntries(stringOrNumberProperty.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [];
1839
- }
1840
- } else if (newProperty.type === "relation") {
1841
- const relationProperty = newProperty;
1842
- const name = relationProperty.relationName || key;
1843
- const relation = relations.find((r) => r.relationName === name);
1844
- if (relation) {
1845
- relationProperty.relation = relation;
1846
- } else {
1847
- console.warn(`Could not find relation for property '${key}' with relationName: ${name}`);
1848
- }
1849
- }
1850
- return newProperty;
1851
- }
1852
- get(path) {
1853
- const bySlug = this.collectionsBySlug.get(path);
1854
- if (bySlug) return bySlug;
1855
- if (path.includes("-")) {
1856
- const normalized = path.replace(/-/g, "_");
1857
- const byNormalized = this.collectionsBySlug.get(normalized);
1858
- if (byNormalized) return byNormalized;
1859
- }
1860
- return this.collectionsByTableName.get(path);
1861
- }
1862
- /**
1863
- * Gets the pristine, un-normalized collection exactly as it was provided.
1864
- * Useful for the AST editor so it doesn't accidentally serialize injected metadata back to disk.
1865
- */
1866
- getRaw(path) {
1867
- const bySlug = this.rawCollectionsBySlug.get(path);
1868
- if (bySlug) return bySlug;
1869
- if (path.includes("-")) {
1870
- const normalized = path.replace(/-/g, "_");
1871
- const byNormalized = this.rawCollectionsBySlug.get(normalized);
1872
- if (byNormalized) return byNormalized;
1873
- }
1874
- return this.rawCollectionsByTableName.get(path);
1875
- }
1876
- /**
1877
- * Get collection by resolving multi-segment paths through relations
1878
- * e.g., "authors/70/posts" resolves to the posts collection
1879
- */
1880
- getCollectionByPath(collectionPath) {
1881
- if (!collectionPath.includes("/")) {
1882
- return this.get(collectionPath);
1883
- }
1884
- const pathSegments = collectionPath.split("/").filter((p) => p);
1885
- if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {
1886
- throw new Error(`Invalid relation path: ${collectionPath}. Expected format: collection/id/relation or collection/id/relation/id/relation`);
1887
- }
1888
- const rootCollectionPath = pathSegments[0];
1889
- let currentCollection = this.get(rootCollectionPath);
1890
- if (!currentCollection) {
1891
- throw new Error(`Root collection not found: ${rootCollectionPath}`);
1892
- }
1893
- for (let i = 2; i < pathSegments.length; i += 2) {
1894
- const relationKey = pathSegments[i];
1895
- if (!getDataSourceCapabilities(currentCollection.driver).supportsRelations) {
1896
- throw new Error(`Relation path navigation requires a collection that supports relations, but '${currentCollection.slug}' uses driver '${currentCollection.driver}'`);
1897
- }
1898
- const resolvedRelations = resolveCollectionRelations(currentCollection);
1899
- const relation = findRelation(resolvedRelations, relationKey);
1900
- if (!relation) {
1901
- throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);
1902
- }
1903
- const target = relation.target();
1904
- const targetRelationKey = relation.relationName || target.slug;
1905
- const targetSlug = relation.overrides?.slug ?? targetRelationKey;
1906
- currentCollection = this.get(targetSlug) || this.normalizeCollection(target);
1907
- if (i + 1 < pathSegments.length) ;
1908
- }
1909
- return currentCollection;
1910
- }
1911
- getCollections() {
1912
- if (!this.cachedCollectionsList) {
1913
- this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());
1914
- }
1915
- return this.cachedCollectionsList;
1916
- }
1917
- getRawCollections() {
1918
- if (!this.cachedRawCollectionsList) {
1919
- this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());
1920
- }
1921
- return this.cachedRawCollectionsList;
1922
- }
1923
- /**
1924
- * Resolves a multi-segment path like "products/123/locales" and returns
1925
- * information about the collections and entity IDs along the path
1926
- */
1927
- resolvePathToCollections(path) {
1928
- const pathSegments = path.split("/").filter((p) => p);
1929
- if (pathSegments.length === 0) {
1930
- throw new Error(`Invalid path: ${path}`);
1931
- }
1932
- if (pathSegments.length % 2 !== 1) {
1933
- throw new Error(`Invalid collection path: ${path}. It must have an odd number of segments.`);
1934
- }
1935
- const collections = [];
1936
- const entityIds = [];
1937
- let currentCollection = this.get(pathSegments[0]);
1938
- if (!currentCollection) {
1939
- throw new Error(`Unknown collection path or slug: ${pathSegments[0]}`);
1940
- }
1941
- collections.push(currentCollection);
1942
- for (let i = 1; i < pathSegments.length; i += 2) {
1943
- const entityId = pathSegments[i];
1944
- entityIds.push(entityId);
1945
- if (i + 1 < pathSegments.length) {
1946
- const subcollectionSlug = pathSegments[i + 1];
1947
- const subcollections = getSubcollections(currentCollection);
1948
- if (!subcollections || subcollections.length === 0) {
1949
- throw new Error(`No subcollections found for ${currentCollection.slug} in path: ${path}`);
1950
- }
1951
- const subcollection = subcollections.find((c) => c.slug === subcollectionSlug);
1952
- if (!subcollection) {
1953
- throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug}`);
1954
- }
1955
- currentCollection = this.get(subcollection.slug) || this.normalizeCollection(subcollection);
1956
- collections.push(currentCollection);
1957
- }
1958
- }
1959
- return {
1960
- collections,
1961
- entityIds,
1962
- finalCollection: currentCollection
1963
- };
1964
- }
1965
- }
1966
- const defaultUsersCollection = {
1967
- name: "Users",
1968
- singularName: "User",
1969
- slug: "users",
1970
- table: "users",
1971
- schema: "rebase",
1972
- icon: "Users",
1973
- group: "Settings",
1974
- openEntityMode: "dialog",
1975
- disableDefaultActions: ["copy"],
1976
- securityRules: [{
1977
- operation: "select",
1978
- roles: ["admin"]
1979
- }, {
1980
- operations: ["insert", "update", "delete"],
1981
- roles: ["admin"]
1982
- }],
1983
- sort: ["createdAt", "desc"],
1984
- properties: {
1985
- id: {
1986
- name: "ID",
1987
- type: "string",
1988
- isId: "uuid",
1989
- ui: {
1990
- readOnly: true
1991
- }
1992
- },
1993
- email: {
1994
- name: "Email",
1995
- type: "string",
1996
- validation: {
1997
- required: true,
1998
- unique: true
1999
- }
2000
- },
2001
- displayName: {
2002
- name: "Name",
2003
- type: "string",
2004
- columnName: "display_name",
2005
- validation: {
2006
- required: true
2007
- }
2008
- },
2009
- photoURL: {
2010
- name: "Photo URL",
2011
- type: "string",
2012
- columnName: "photo_url",
2013
- url: "image"
2014
- },
2015
- roles: {
2016
- name: "Roles",
2017
- type: "array",
2018
- columnType: "text[]",
2019
- of: {
2020
- name: "Role",
2021
- type: "string",
2022
- enum: {
2023
- admin: "Admin",
2024
- editor: "Editor",
2025
- viewer: "Viewer"
2026
- }
2027
- }
2028
- },
2029
- passwordHash: {
2030
- name: "Password Hash",
2031
- type: "string",
2032
- columnName: "password_hash",
2033
- ui: {
2034
- hideFromCollection: true,
2035
- disabled: {
2036
- hidden: true
2037
- }
2038
- }
2039
- },
2040
- emailVerified: {
2041
- name: "Email Verified",
2042
- type: "boolean",
2043
- columnName: "email_verified",
2044
- defaultValue: false,
2045
- ui: {
2046
- hideFromCollection: true,
2047
- disabled: {
2048
- hidden: true
2049
- }
2050
- }
2051
- },
2052
- emailVerificationToken: {
2053
- name: "Email Verification Token",
2054
- type: "string",
2055
- columnName: "email_verification_token",
2056
- ui: {
2057
- hideFromCollection: true,
2058
- disabled: {
2059
- hidden: true
2060
- }
2061
- }
2062
- },
2063
- emailVerificationSentAt: {
2064
- name: "Email Verification Sent At",
2065
- type: "date",
2066
- columnName: "email_verification_sent_at",
2067
- ui: {
2068
- hideFromCollection: true,
2069
- disabled: {
2070
- hidden: true
2071
- }
2072
- }
2073
- },
2074
- metadata: {
2075
- name: "Metadata",
2076
- type: "map",
2077
- defaultValue: {},
2078
- ui: {
2079
- hideFromCollection: true,
2080
- disabled: {
2081
- hidden: true
2082
- }
2083
- }
2084
- },
2085
- createdAt: {
2086
- name: "Created At",
2087
- type: "date",
2088
- columnName: "created_at",
2089
- autoValue: "on_create",
2090
- ui: {
2091
- readOnly: true
2092
- }
2093
- },
2094
- updatedAt: {
2095
- name: "Updated At",
2096
- type: "date",
2097
- columnName: "updated_at",
2098
- autoValue: "on_update",
2099
- ui: {
2100
- hideFromCollection: true,
2101
- disabled: {
2102
- hidden: true
2103
- }
2104
- }
2105
- }
2106
- },
2107
- listProperties: ["displayName", "email", "roles", "createdAt"],
2108
- propertiesOrder: ["id", "email", "displayName", "roles", "createdAt"]
1392
+ let result = [...enumValues];
1393
+ if (conditions.allowedEnumValues) {
1394
+ const allowedArray = objectToArray(evaluateCondition(conditions.allowedEnumValues, context));
1395
+ if (allowedArray.length > 0) result = result.filter((ev) => allowedArray.includes(String(ev.id)));
1396
+ }
1397
+ if (conditions.excludedEnumValues) {
1398
+ const excludedArray = objectToArray(evaluateCondition(conditions.excludedEnumValues, context));
1399
+ if (excludedArray.length > 0) result = result.filter((ev) => !excludedArray.includes(String(ev.id)));
1400
+ }
1401
+ if (conditions.enumConditions) result = result.map((ev) => {
1402
+ const evConditions = conditions.enumConditions?.[ev.id];
1403
+ if (!evConditions) return ev;
1404
+ if (evConditions.hidden && evaluateCondition(evConditions.hidden, context)) return null;
1405
+ if (evConditions.disabled && evaluateCondition(evConditions.disabled, context)) return {
1406
+ ...ev,
1407
+ disabled: true
1408
+ };
1409
+ return ev;
1410
+ }).filter((ev) => ev !== null);
1411
+ return result;
1412
+ }
1413
+ //#endregion
1414
+ //#region src/collections/CollectionRegistry.ts
1415
+ var CollectionRegistry = class {
1416
+ collectionsByTableName = /* @__PURE__ */ new Map();
1417
+ collectionsBySlug = /* @__PURE__ */ new Map();
1418
+ rootCollections = [];
1419
+ cachedCollectionsList = null;
1420
+ rawCollectionsByTableName = /* @__PURE__ */ new Map();
1421
+ rawCollectionsBySlug = /* @__PURE__ */ new Map();
1422
+ rawRootCollections = [];
1423
+ cachedRawCollectionsList = null;
1424
+ lastRawInputSnapshot = null;
1425
+ constructor(collections) {
1426
+ if (collections) this.registerMultiple(collections);
1427
+ }
1428
+ reset() {
1429
+ this.collectionsByTableName.clear();
1430
+ this.collectionsBySlug.clear();
1431
+ this.rootCollections = [];
1432
+ this.cachedCollectionsList = null;
1433
+ this.rawCollectionsByTableName.clear();
1434
+ this.rawCollectionsBySlug.clear();
1435
+ this.rawRootCollections = [];
1436
+ this.cachedRawCollectionsList = null;
1437
+ }
1438
+ /**
1439
+ * Registers a collection and its subcollections recursively.
1440
+ * Returns true if the collections have changed, false otherwise.
1441
+ *
1442
+ * Idempotent: compares the raw input (before normalization) against a stored
1443
+ * snapshot. Only re-normalizes and re-registers when the raw input actually changed.
1444
+ * @param collections
1445
+ */
1446
+ registerMultiple(collections) {
1447
+ const rawSnapshot = collections.map((c) => removeFunctions(c));
1448
+ if (this.lastRawInputSnapshot && deepEqual(this.lastRawInputSnapshot, rawSnapshot)) return false;
1449
+ this.reset();
1450
+ collections.forEach((c) => {
1451
+ if (c.slug) this.collectionsBySlug.set(c.slug, c);
1452
+ this.collectionsByTableName.set(getTableName(c), c);
1453
+ });
1454
+ const normalizedCollections = collections.map((c) => this.normalizeCollection({ ...c }));
1455
+ normalizedCollections.forEach((c, index) => {
1456
+ const raw = deepClone(collections[index]);
1457
+ this.rootCollections.push(c);
1458
+ this.rawRootCollections.push(raw);
1459
+ const normalized = this.normalizeCollection(c);
1460
+ this.collectionsByTableName.set(getTableName(normalized), normalized);
1461
+ this.rawCollectionsByTableName.set(getTableName(raw), raw);
1462
+ if (normalized.slug) this.collectionsBySlug.set(normalized.slug, normalized);
1463
+ if (raw.slug) this.rawCollectionsBySlug.set(raw.slug, raw);
1464
+ });
1465
+ normalizedCollections.forEach((c) => {
1466
+ const subcollections = getSubcollections(c);
1467
+ if (subcollections && subcollections.length > 0) subcollections.forEach((subCollection) => {
1468
+ if (!subCollection) return;
1469
+ this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));
1470
+ });
1471
+ });
1472
+ this.lastRawInputSnapshot = rawSnapshot;
1473
+ return true;
1474
+ }
1475
+ register(collection, rawCollection) {
1476
+ const raw = rawCollection ? deepClone(rawCollection) : deepClone(collection);
1477
+ this.rootCollections.push(collection);
1478
+ this.rawRootCollections.push(raw);
1479
+ this._registerRecursively(collection, raw);
1480
+ }
1481
+ _registerRecursively(collection, rawCollection) {
1482
+ if (this.collectionsByTableName.has(getTableName(collection))) return;
1483
+ const normalizedCollection = this.normalizeCollection(collection);
1484
+ this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);
1485
+ this.rawCollectionsByTableName.set(getTableName(rawCollection), rawCollection);
1486
+ if (normalizedCollection.slug) this.collectionsBySlug.set(normalizedCollection.slug, normalizedCollection);
1487
+ if (rawCollection.slug) this.rawCollectionsBySlug.set(rawCollection.slug, rawCollection);
1488
+ const subcollections = getSubcollections(normalizedCollection);
1489
+ if (subcollections && subcollections.length > 0) subcollections.forEach((subCollection) => {
1490
+ if (!subCollection) return;
1491
+ this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));
1492
+ });
1493
+ }
1494
+ normalizeCollection(collection) {
1495
+ const result = { ...collection };
1496
+ const extractedRelations = this.extractRelationsFromProperties(result.properties);
1497
+ const relResult = result;
1498
+ const manualRelations = getDataSourceCapabilities(result.driver).supportsRelations ? relResult.relations ?? [] : [];
1499
+ const mergedRelationsRaw = [...extractedRelations];
1500
+ for (const manual of manualRelations) {
1501
+ const name = manual.relationName;
1502
+ if (!name) mergedRelationsRaw.push(manual);
1503
+ else {
1504
+ const existingIndex = mergedRelationsRaw.findIndex((r) => r.relationName === name);
1505
+ if (existingIndex === -1) mergedRelationsRaw.push(manual);
1506
+ else mergedRelationsRaw[existingIndex] = {
1507
+ ...manual,
1508
+ ...mergedRelationsRaw[existingIndex]
1509
+ };
1510
+ }
1511
+ }
1512
+ let mergedRelations = mergedRelationsRaw;
1513
+ if (getDataSourceCapabilities(result.driver).supportsRelations) {
1514
+ mergedRelations = mergedRelationsRaw.map((r) => {
1515
+ try {
1516
+ return sanitizeRelation(r, result, (slug) => this.get(slug));
1517
+ } catch {
1518
+ return r;
1519
+ }
1520
+ });
1521
+ relResult.relations = mergedRelations;
1522
+ }
1523
+ result.properties = this.normalizeProperties(result.properties, mergedRelations);
1524
+ if (!result.childCollections) {
1525
+ if (getDataSourceCapabilities(result.driver).supportsSubcollections && result.subcollections) result.childCollections = result.subcollections;
1526
+ else if (getDataSourceCapabilities(result.driver).supportsRelations && relResult.relations) {
1527
+ const manyRelations = relResult.relations.filter((r) => r.cardinality === "many");
1528
+ if (manyRelations.length > 0) result.childCollections = () => manyRelations.map((r) => {
1529
+ const target = r.target();
1530
+ return r.overrides ? mergeDeep(target, r.overrides) : target;
1531
+ });
1532
+ }
1533
+ }
1534
+ return result;
1535
+ }
1536
+ /**
1537
+ * Extract Relation[] from properties that have inline relation config (i.e. `target` is set).
1538
+ * This allows developers to define relations directly on properties without a separate
1539
+ * `relations[]` entry on the collection.
1540
+ */
1541
+ extractRelationsFromProperties(properties) {
1542
+ const relations = [];
1543
+ for (const [key, property] of Object.entries(properties)) if (property.type === "relation") {
1544
+ const relProp = property;
1545
+ const target = relProp.target ?? relProp.relation?.target;
1546
+ if (target) {
1547
+ const relationName = relProp.relationName ?? relProp.relation?.relationName ?? key;
1548
+ relations.push({
1549
+ relationName,
1550
+ target,
1551
+ cardinality: relProp.cardinality ?? relProp.relation?.cardinality ?? "one",
1552
+ direction: relProp.direction ?? relProp.relation?.direction ?? "owning",
1553
+ inverseRelationName: relProp.inverseRelationName ?? relProp.relation?.inverseRelationName,
1554
+ localKey: relProp.localKey ?? relProp.relation?.localKey,
1555
+ foreignKeyOnTarget: relProp.foreignKeyOnTarget ?? relProp.relation?.foreignKeyOnTarget,
1556
+ through: relProp.through ?? relProp.relation?.through,
1557
+ joinPath: relProp.joinPath ?? relProp.relation?.joinPath,
1558
+ onUpdate: relProp.onUpdate ?? relProp.relation?.onUpdate,
1559
+ onDelete: relProp.onDelete ?? relProp.relation?.onDelete,
1560
+ overrides: relProp.overrides ?? relProp.relation?.overrides
1561
+ });
1562
+ }
1563
+ } else if (property.type === "map" && property.properties) relations.push(...this.extractRelationsFromProperties(property.properties));
1564
+ return relations;
1565
+ }
1566
+ normalizeProperties(properties, relations) {
1567
+ const newProperties = {};
1568
+ for (const key in properties) newProperties[key] = this.normalizeProperty(key, properties[key], relations);
1569
+ return newProperties;
1570
+ }
1571
+ normalizeProperty(key, property, relations) {
1572
+ const newProperty = { ...property };
1573
+ if (newProperty.type === "map" && newProperty.properties) newProperty.properties = this.normalizeProperties(newProperty.properties, relations);
1574
+ else if (newProperty.type === "array") {
1575
+ const arrayProp = newProperty;
1576
+ if (arrayProp.of) if (Array.isArray(arrayProp.of)) arrayProp.of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, relations));
1577
+ else arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, relations);
1578
+ else if (arrayProp.oneOf && arrayProp.oneOf.properties) arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.oneOf.properties, relations);
1579
+ } else if ((newProperty.type === "string" || newProperty.type === "number") && newProperty.enum) {
1580
+ const stringOrNumberProperty = newProperty;
1581
+ if (typeof stringOrNumberProperty.enum === "object" && !Array.isArray(stringOrNumberProperty.enum)) stringOrNumberProperty.enum = enumToObjectEntries(stringOrNumberProperty.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [];
1582
+ } else if (newProperty.type === "relation") {
1583
+ const relationProperty = newProperty;
1584
+ const name = relationProperty.relationName || key;
1585
+ const relation = relations.find((r) => r.relationName === name);
1586
+ if (relation) relationProperty.relation = relation;
1587
+ else console.warn(`Could not find relation for property '${key}' with relationName: ${name}`);
1588
+ }
1589
+ return newProperty;
1590
+ }
1591
+ get(path) {
1592
+ const bySlug = this.collectionsBySlug.get(path);
1593
+ if (bySlug) return bySlug;
1594
+ if (path.includes("-")) {
1595
+ const normalized = path.replace(/-/g, "_");
1596
+ const byNormalized = this.collectionsBySlug.get(normalized);
1597
+ if (byNormalized) return byNormalized;
1598
+ }
1599
+ return this.collectionsByTableName.get(path);
1600
+ }
1601
+ /**
1602
+ * Gets the pristine, un-normalized collection exactly as it was provided.
1603
+ * Useful for the AST editor so it doesn't accidentally serialize injected metadata back to disk.
1604
+ */
1605
+ getRaw(path) {
1606
+ const bySlug = this.rawCollectionsBySlug.get(path);
1607
+ if (bySlug) return bySlug;
1608
+ if (path.includes("-")) {
1609
+ const normalized = path.replace(/-/g, "_");
1610
+ const byNormalized = this.rawCollectionsBySlug.get(normalized);
1611
+ if (byNormalized) return byNormalized;
1612
+ }
1613
+ return this.rawCollectionsByTableName.get(path);
1614
+ }
1615
+ /**
1616
+ * Get collection by resolving multi-segment paths through relations
1617
+ * e.g., "authors/70/posts" resolves to the posts collection
1618
+ */
1619
+ getCollectionByPath(collectionPath) {
1620
+ if (!collectionPath.includes("/")) return this.get(collectionPath);
1621
+ const pathSegments = collectionPath.split("/").filter((p) => p);
1622
+ 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`);
1623
+ const rootCollectionPath = pathSegments[0];
1624
+ let currentCollection = this.get(rootCollectionPath);
1625
+ if (!currentCollection) throw new Error(`Root collection not found: ${rootCollectionPath}`);
1626
+ for (let i = 2; i < pathSegments.length; i += 2) {
1627
+ const relationKey = pathSegments[i];
1628
+ if (!getDataSourceCapabilities(currentCollection.driver).supportsRelations) throw new Error(`Relation path navigation requires a collection that supports relations, but '${currentCollection.slug}' uses driver '${currentCollection.driver}'`);
1629
+ const relation = findRelation(resolveCollectionRelations(currentCollection), relationKey);
1630
+ if (!relation) throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);
1631
+ const target = relation.target();
1632
+ const targetRelationKey = relation.relationName || target.slug;
1633
+ const targetSlug = relation.overrides?.slug ?? targetRelationKey;
1634
+ currentCollection = this.get(targetSlug) || this.normalizeCollection(target);
1635
+ if (i + 1 < pathSegments.length) {}
1636
+ }
1637
+ return currentCollection;
1638
+ }
1639
+ getCollections() {
1640
+ if (!this.cachedCollectionsList) this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());
1641
+ return this.cachedCollectionsList;
1642
+ }
1643
+ getRawCollections() {
1644
+ if (!this.cachedRawCollectionsList) this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());
1645
+ return this.cachedRawCollectionsList;
1646
+ }
1647
+ /**
1648
+ * Resolves a multi-segment path like "products/123/locales" and returns
1649
+ * information about the collections and entity IDs along the path
1650
+ */
1651
+ resolvePathToCollections(path) {
1652
+ const pathSegments = path.split("/").filter((p) => p);
1653
+ if (pathSegments.length === 0) throw new Error(`Invalid path: ${path}`);
1654
+ if (pathSegments.length % 2 !== 1) throw new Error(`Invalid collection path: ${path}. It must have an odd number of segments.`);
1655
+ const collections = [];
1656
+ const entityIds = [];
1657
+ let currentCollection = this.get(pathSegments[0]);
1658
+ if (!currentCollection) throw new Error(`Unknown collection path or slug: ${pathSegments[0]}`);
1659
+ collections.push(currentCollection);
1660
+ for (let i = 1; i < pathSegments.length; i += 2) {
1661
+ const entityId = pathSegments[i];
1662
+ entityIds.push(entityId);
1663
+ if (i + 1 < pathSegments.length) {
1664
+ const subcollectionSlug = pathSegments[i + 1];
1665
+ const subcollections = getSubcollections(currentCollection);
1666
+ if (!subcollections || subcollections.length === 0) throw new Error(`No subcollections found for ${currentCollection.slug} in path: ${path}`);
1667
+ const subcollection = subcollections.find((c) => c.slug === subcollectionSlug);
1668
+ if (!subcollection) throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug}`);
1669
+ currentCollection = this.get(subcollection.slug) || this.normalizeCollection(subcollection);
1670
+ collections.push(currentCollection);
1671
+ }
1672
+ }
1673
+ return {
1674
+ collections,
1675
+ entityIds,
1676
+ finalCollection: currentCollection
1677
+ };
1678
+ }
2109
1679
  };
1680
+ //#endregion
1681
+ //#region src/collections/default-collections.ts
1682
+ /**
1683
+ * Default users collection.
1684
+ *
1685
+ * Prepended to the developer's collections array by the admin and server.
1686
+ * Slug-based dedup (Map keyed by slug, last-write-wins) lets developers
1687
+ * override by defining their own collection with `slug: "users"`.
1688
+ */
1689
+ var defaultUsersCollection = {
1690
+ name: "Users",
1691
+ singularName: "User",
1692
+ slug: "users",
1693
+ auth: true,
1694
+ table: "users",
1695
+ schema: "rebase",
1696
+ icon: "Users",
1697
+ group: "Settings",
1698
+ openEntityMode: "dialog",
1699
+ disableDefaultActions: ["copy"],
1700
+ securityRules: [{
1701
+ operation: "select",
1702
+ roles: ["admin"]
1703
+ }, {
1704
+ operations: [
1705
+ "insert",
1706
+ "update",
1707
+ "delete"
1708
+ ],
1709
+ roles: ["admin"]
1710
+ }],
1711
+ sort: ["createdAt", "desc"],
1712
+ properties: {
1713
+ id: {
1714
+ name: "ID",
1715
+ type: "string",
1716
+ isId: "uuid",
1717
+ ui: { readOnly: true }
1718
+ },
1719
+ email: {
1720
+ name: "Email",
1721
+ type: "string",
1722
+ validation: {
1723
+ required: true,
1724
+ unique: true
1725
+ }
1726
+ },
1727
+ displayName: {
1728
+ name: "Name",
1729
+ type: "string",
1730
+ columnName: "display_name",
1731
+ validation: { required: true }
1732
+ },
1733
+ photoURL: {
1734
+ name: "Photo URL",
1735
+ type: "string",
1736
+ columnName: "photo_url",
1737
+ url: "image"
1738
+ },
1739
+ roles: {
1740
+ name: "Roles",
1741
+ type: "array",
1742
+ columnType: "text[]",
1743
+ of: {
1744
+ name: "Role",
1745
+ type: "string",
1746
+ enum: {
1747
+ admin: "Admin",
1748
+ editor: "Editor",
1749
+ viewer: "Viewer"
1750
+ }
1751
+ }
1752
+ },
1753
+ passwordHash: {
1754
+ name: "Password Hash",
1755
+ type: "string",
1756
+ columnName: "password_hash",
1757
+ ui: {
1758
+ hideFromCollection: true,
1759
+ disabled: { hidden: true }
1760
+ }
1761
+ },
1762
+ emailVerified: {
1763
+ name: "Email Verified",
1764
+ type: "boolean",
1765
+ columnName: "email_verified",
1766
+ defaultValue: false,
1767
+ ui: {
1768
+ hideFromCollection: true,
1769
+ disabled: { hidden: true }
1770
+ }
1771
+ },
1772
+ emailVerificationToken: {
1773
+ name: "Email Verification Token",
1774
+ type: "string",
1775
+ columnName: "email_verification_token",
1776
+ ui: {
1777
+ hideFromCollection: true,
1778
+ disabled: { hidden: true }
1779
+ }
1780
+ },
1781
+ emailVerificationSentAt: {
1782
+ name: "Email Verification Sent At",
1783
+ type: "date",
1784
+ columnName: "email_verification_sent_at",
1785
+ ui: {
1786
+ hideFromCollection: true,
1787
+ disabled: { hidden: true }
1788
+ }
1789
+ },
1790
+ metadata: {
1791
+ name: "Metadata",
1792
+ type: "map",
1793
+ keyValue: true,
1794
+ properties: {},
1795
+ defaultValue: {},
1796
+ ui: {
1797
+ hideFromCollection: true,
1798
+ disabled: { hidden: true }
1799
+ }
1800
+ },
1801
+ createdAt: {
1802
+ name: "Created At",
1803
+ type: "date",
1804
+ columnName: "created_at",
1805
+ autoValue: "on_create",
1806
+ ui: { readOnly: true }
1807
+ },
1808
+ updatedAt: {
1809
+ name: "Updated At",
1810
+ type: "date",
1811
+ columnName: "updated_at",
1812
+ autoValue: "on_update",
1813
+ ui: {
1814
+ hideFromCollection: true,
1815
+ disabled: { hidden: true }
1816
+ }
1817
+ }
1818
+ },
1819
+ listProperties: [
1820
+ "displayName",
1821
+ "email",
1822
+ "roles",
1823
+ "createdAt"
1824
+ ],
1825
+ propertiesOrder: [
1826
+ "id",
1827
+ "email",
1828
+ "displayName",
1829
+ "roles",
1830
+ "createdAt"
1831
+ ]
1832
+ };
1833
+ //#endregion
1834
+ //#region src/data/query_builder.ts
2110
1835
  function or(...conditions) {
2111
- return {
2112
- type: "or",
2113
- conditions
2114
- };
1836
+ return {
1837
+ type: "or",
1838
+ conditions
1839
+ };
2115
1840
  }
2116
1841
  function and(...conditions) {
2117
- return {
2118
- type: "and",
2119
- conditions
2120
- };
1842
+ return {
1843
+ type: "and",
1844
+ conditions
1845
+ };
2121
1846
  }
2122
1847
  function cond(column, operator, value) {
2123
- return {
2124
- column,
2125
- operator,
2126
- value
2127
- };
2128
- }
2129
- class QueryBuilder {
2130
- constructor(collection) {
2131
- this.collection = collection;
2132
- }
2133
- params = {
2134
- where: {}
2135
- };
2136
- where(columnOrCondition, operator, value) {
2137
- if (typeof columnOrCondition === "object" && columnOrCondition !== null && "type" in columnOrCondition) {
2138
- this.params.logical = columnOrCondition;
2139
- return this;
2140
- }
2141
- if (!this.params.where) {
2142
- this.params.where = {};
2143
- }
2144
- const column = columnOrCondition;
2145
- const condition = [operator, value];
2146
- const existing = this.params.where[column];
2147
- if (existing === void 0) {
2148
- this.params.where[column] = condition;
2149
- } else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) {
2150
- this.params.where[column].push(condition);
2151
- } else {
2152
- let firstCondition;
2153
- if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === "string") {
2154
- firstCondition = existing;
2155
- } else {
2156
- firstCondition = ["==", existing];
2157
- }
2158
- this.params.where[column] = [firstCondition, condition];
2159
- }
2160
- return this;
2161
- }
2162
- /**
2163
- * Order the results by a specific column.
2164
- * @example
2165
- * client.collection('users').orderBy('createdAt', 'desc').find()
2166
- */
2167
- orderBy(column, ascending = "asc") {
2168
- this.params.orderBy = `${column}:${ascending}`;
2169
- return this;
2170
- }
2171
- /**
2172
- * Limit the number of results returned.
2173
- */
2174
- limit(count) {
2175
- this.params.limit = count;
2176
- return this;
2177
- }
2178
- /**
2179
- * Skip the first N results.
2180
- */
2181
- offset(count) {
2182
- this.params.offset = count;
2183
- return this;
2184
- }
2185
- /**
2186
- * Set a free-text search string if supported by the backend.
2187
- */
2188
- search(searchString) {
2189
- this.params.searchString = searchString;
2190
- return this;
2191
- }
2192
- /**
2193
- * Include related entities in the response.
2194
- * Relations will be populated with full entity data instead of just IDs.
2195
- *
2196
- * @param relations - Relation names to include, or "*" for all.
2197
- * @example
2198
- * // Include specific relations
2199
- * client.data.posts.include("tags", "author").find()
2200
- *
2201
- * // Include all relations
2202
- * client.data.posts.include("*").find()
2203
- */
2204
- include(...relations) {
2205
- this.params.include = relations;
2206
- return this;
2207
- }
2208
- /**
2209
- * Execute the find query and return the results.
2210
- */
2211
- async find() {
2212
- return this.collection.find(this.params);
2213
- }
2214
- /**
2215
- * Listen to realtime updates matching this query.
2216
- */
2217
- listen(onUpdate, onError) {
2218
- if (!this.collection.listen) {
2219
- throw new Error("Listen is only available when RebaseClient is configured with a websocketUrl.");
2220
- }
2221
- return this.collection.listen(this.params, onUpdate, onError);
2222
- }
2223
- }
1848
+ return {
1849
+ column,
1850
+ operator,
1851
+ value
1852
+ };
1853
+ }
1854
+ var QueryBuilder = class {
1855
+ collection;
1856
+ params = { where: {} };
1857
+ constructor(collection) {
1858
+ this.collection = collection;
1859
+ }
1860
+ where(columnOrCondition, operator, value) {
1861
+ if (typeof columnOrCondition === "object" && columnOrCondition !== null && "type" in columnOrCondition) {
1862
+ this.params.logical = columnOrCondition;
1863
+ return this;
1864
+ }
1865
+ if (!this.params.where) this.params.where = {};
1866
+ const column = columnOrCondition;
1867
+ const condition = [operator, value];
1868
+ const existing = this.params.where[column];
1869
+ if (existing === void 0) this.params.where[column] = condition;
1870
+ else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) this.params.where[column].push(condition);
1871
+ else {
1872
+ let firstCondition;
1873
+ if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === "string") firstCondition = existing;
1874
+ else firstCondition = ["==", existing];
1875
+ this.params.where[column] = [firstCondition, condition];
1876
+ }
1877
+ return this;
1878
+ }
1879
+ /**
1880
+ * Order the results by a specific column.
1881
+ * @example
1882
+ * client.collection('users').orderBy('createdAt', 'desc').find()
1883
+ */
1884
+ orderBy(column, ascending = "asc") {
1885
+ this.params.orderBy = `${column}:${ascending}`;
1886
+ return this;
1887
+ }
1888
+ /**
1889
+ * Limit the number of results returned.
1890
+ */
1891
+ limit(count) {
1892
+ this.params.limit = count;
1893
+ return this;
1894
+ }
1895
+ /**
1896
+ * Skip the first N results.
1897
+ */
1898
+ offset(count) {
1899
+ this.params.offset = count;
1900
+ return this;
1901
+ }
1902
+ /**
1903
+ * Set a free-text search string if supported by the backend.
1904
+ */
1905
+ search(searchString) {
1906
+ this.params.searchString = searchString;
1907
+ return this;
1908
+ }
1909
+ /**
1910
+ * Include related entities in the response.
1911
+ * Relations will be populated with full entity data instead of just IDs.
1912
+ *
1913
+ * @param relations - Relation names to include, or "*" for all.
1914
+ * @example
1915
+ * // Include specific relations
1916
+ * client.data.posts.include("tags", "author").find()
1917
+ *
1918
+ * // Include all relations
1919
+ * client.data.posts.include("*").find()
1920
+ */
1921
+ include(...relations) {
1922
+ this.params.include = relations;
1923
+ return this;
1924
+ }
1925
+ /**
1926
+ * Execute the find query and return the results.
1927
+ */
1928
+ async find() {
1929
+ return this.collection.find(this.params);
1930
+ }
1931
+ /**
1932
+ * Listen to realtime updates matching this query.
1933
+ */
1934
+ listen(onUpdate, onError) {
1935
+ if (!this.collection.listen) throw new Error("Listen is only available when RebaseClient is configured with a websocketUrl.");
1936
+ return this.collection.listen(this.params, onUpdate, onError);
1937
+ }
1938
+ };
1939
+ //#endregion
1940
+ //#region src/data/buildRebaseData.ts
1941
+ /**
1942
+ * Convert where-clause filter object to the internal DataDriver FilterValues format.
1943
+ *
1944
+ * Supports multiple value formats:
1945
+ * - PostgREST string: { status: "eq.published", age: "gte.18" }
1946
+ * - Equality shorthand: { company_profile_id: null, status: "active", age: 18 }
1947
+ * - Tuple syntax: { age: [">=", 18], role: ["in", ["admin", "editor"]] }
1948
+ *
1949
+ * Internal: { status: ["==", "published"], age: [">=", 18] }
1950
+ */
2224
1951
  function convertWhereToFilter(where) {
2225
- if (!where) return void 0;
2226
- const operatorMap = {
2227
- "eq": "==",
2228
- "neq": "!=",
2229
- "gt": ">",
2230
- "gte": ">=",
2231
- "lt": "<",
2232
- "lte": "<=",
2233
- "in": "in",
2234
- "nin": "not-in",
2235
- "not-in": "not-in",
2236
- "cs": "array-contains",
2237
- "csa": "array-contains-any",
2238
- "==": "==",
2239
- "!=": "!=",
2240
- ">": ">",
2241
- ">=": ">=",
2242
- "<": "<",
2243
- "<=": "<=",
2244
- "array-contains": "array-contains",
2245
- "array-contains-any": "array-contains-any"
2246
- };
2247
- const filter = {};
2248
- for (const [field, rawValue] of Object.entries(where)) {
2249
- if (rawValue === null) {
2250
- filter[field] = ["==", null];
2251
- continue;
2252
- }
2253
- if (typeof rawValue === "boolean") {
2254
- filter[field] = ["==", rawValue];
2255
- continue;
2256
- }
2257
- if (typeof rawValue === "number") {
2258
- filter[field] = ["==", rawValue];
2259
- continue;
2260
- }
2261
- if (Array.isArray(rawValue)) {
2262
- const conditions = Array.isArray(rawValue[0]) ? rawValue : [rawValue];
2263
- const mappedConditions = conditions.map(([rawOp, val]) => {
2264
- const mappedOp = operatorMap[rawOp] ?? "==";
2265
- return [mappedOp, val];
2266
- });
2267
- filter[field] = Array.isArray(rawValue[0]) ? mappedConditions : mappedConditions[0];
2268
- continue;
2269
- }
2270
- if (typeof rawValue === "string") {
2271
- const dotIndex = rawValue.indexOf(".");
2272
- if (dotIndex === -1) {
2273
- filter[field] = ["==", rawValue];
2274
- continue;
2275
- }
2276
- const op = rawValue.substring(0, dotIndex);
2277
- let value = rawValue.substring(dotIndex + 1);
2278
- if (typeof value === "string" && value.startsWith("(") && value.endsWith(")")) {
2279
- value = value.slice(1, -1).split(",").map((v) => v.trim());
2280
- }
2281
- if (value === "null") {
2282
- value = null;
2283
- } else if (value === "true") {
2284
- value = true;
2285
- } else if (value === "false") {
2286
- value = false;
2287
- } else if (typeof value === "string" && !isNaN(Number(value)) && value.trim() !== "") {
2288
- value = Number(value);
2289
- }
2290
- const mappedOp = operatorMap[op];
2291
- if (mappedOp) {
2292
- filter[field] = [mappedOp, value];
2293
- }
2294
- }
2295
- }
2296
- return Object.keys(filter).length > 0 ? filter : void 0;
2297
- }
1952
+ if (!where) return void 0;
1953
+ const operatorMap = {
1954
+ "eq": "==",
1955
+ "neq": "!=",
1956
+ "gt": ">",
1957
+ "gte": ">=",
1958
+ "lt": "<",
1959
+ "lte": "<=",
1960
+ "in": "in",
1961
+ "nin": "not-in",
1962
+ "not-in": "not-in",
1963
+ "cs": "array-contains",
1964
+ "csa": "array-contains-any",
1965
+ "==": "==",
1966
+ "!=": "!=",
1967
+ ">": ">",
1968
+ ">=": ">=",
1969
+ "<": "<",
1970
+ "<=": "<=",
1971
+ "array-contains": "array-contains",
1972
+ "array-contains-any": "array-contains-any"
1973
+ };
1974
+ const filter = {};
1975
+ for (const [field, rawValue] of Object.entries(where)) {
1976
+ if (rawValue === null) {
1977
+ filter[field] = ["==", null];
1978
+ continue;
1979
+ }
1980
+ if (typeof rawValue === "boolean") {
1981
+ filter[field] = ["==", rawValue];
1982
+ continue;
1983
+ }
1984
+ if (typeof rawValue === "number") {
1985
+ filter[field] = ["==", rawValue];
1986
+ continue;
1987
+ }
1988
+ if (Array.isArray(rawValue)) {
1989
+ const mappedConditions = (Array.isArray(rawValue[0]) ? rawValue : [rawValue]).map(([rawOp, val]) => {
1990
+ return [operatorMap[rawOp] ?? "==", val];
1991
+ });
1992
+ filter[field] = Array.isArray(rawValue[0]) ? mappedConditions : mappedConditions[0];
1993
+ continue;
1994
+ }
1995
+ if (typeof rawValue === "string") {
1996
+ const dotIndex = rawValue.indexOf(".");
1997
+ if (dotIndex === -1) {
1998
+ filter[field] = ["==", rawValue];
1999
+ continue;
2000
+ }
2001
+ const op = rawValue.substring(0, dotIndex);
2002
+ let value = rawValue.substring(dotIndex + 1);
2003
+ if (typeof value === "string" && value.startsWith("(") && value.endsWith(")")) value = value.slice(1, -1).split(",").map((v) => v.trim());
2004
+ if (value === "null") value = null;
2005
+ else if (value === "true") value = true;
2006
+ else if (value === "false") value = false;
2007
+ else if (typeof value === "string" && !isNaN(Number(value)) && value.trim() !== "") value = Number(value);
2008
+ const mappedOp = operatorMap[op];
2009
+ if (mappedOp) filter[field] = [mappedOp, value];
2010
+ }
2011
+ }
2012
+ return Object.keys(filter).length > 0 ? filter : void 0;
2013
+ }
2014
+ /**
2015
+ * Parse an orderBy string like "created_at:desc" into [field, direction].
2016
+ */
2298
2017
  function parseOrderBy(orderBy) {
2299
- if (!orderBy) return void 0;
2300
- const parts = orderBy.split(":");
2301
- const field = parts[0];
2302
- const direction = parts[1] || "asc";
2303
- return [field, direction];
2018
+ if (!orderBy) return void 0;
2019
+ const parts = orderBy.split(":");
2020
+ return [parts[0], parts[1] || "asc"];
2304
2021
  }
2305
2022
  function createDriverAccessor(driver, slug) {
2306
- const accessor = {
2307
- async find(params) {
2308
- const orderParsed = parseOrderBy(params?.orderBy);
2309
- const entities = await driver.fetchCollection({
2310
- path: slug,
2311
- limit: params?.limit,
2312
- offset: params?.offset,
2313
- filter: convertWhereToFilter(params?.where),
2314
- orderBy: orderParsed?.[0],
2315
- order: orderParsed?.[1],
2316
- searchString: params?.searchString
2317
- });
2318
- const limit = params?.limit ?? 20;
2319
- const offset = params?.offset ?? 0;
2320
- return {
2321
- data: entities,
2322
- meta: {
2323
- total: entities.length,
2324
- limit,
2325
- offset,
2326
- hasMore: entities.length >= limit
2327
- }
2328
- };
2329
- },
2330
- async findById(id) {
2331
- return driver.fetchEntity({
2332
- path: slug,
2333
- entityId: id
2334
- });
2335
- },
2336
- async create(data, id) {
2337
- return driver.saveEntity({
2338
- path: slug,
2339
- values: data,
2340
- entityId: id,
2341
- status: "new"
2342
- });
2343
- },
2344
- async update(id, data) {
2345
- return driver.saveEntity({
2346
- path: slug,
2347
- values: data,
2348
- entityId: id,
2349
- status: "existing"
2350
- });
2351
- },
2352
- async delete(id) {
2353
- return driver.deleteEntity({
2354
- entity: {
2355
- id,
2356
- path: slug,
2357
- values: {}
2358
- }
2359
- });
2360
- },
2361
- deleteAll: driver.deleteAll ? async () => {
2362
- return driver.deleteAll(slug);
2363
- } : void 0,
2364
- count: driver.countEntities ? async (params) => {
2365
- return driver.countEntities({
2366
- path: slug,
2367
- filter: convertWhereToFilter(params?.where)
2368
- });
2369
- } : void 0,
2370
- listen: driver.listenCollection ? (params, onUpdate, onError) => {
2371
- const orderParsed = parseOrderBy(params?.orderBy);
2372
- const limit = params?.limit ?? 20;
2373
- const offset = params?.offset ?? 0;
2374
- return driver.listenCollection({
2375
- path: slug,
2376
- limit: params?.limit,
2377
- offset: params?.offset,
2378
- filter: convertWhereToFilter(params?.where),
2379
- orderBy: orderParsed?.[0],
2380
- order: orderParsed?.[1],
2381
- searchString: params?.searchString,
2382
- onUpdate: (entities) => {
2383
- onUpdate({
2384
- data: entities,
2385
- meta: {
2386
- total: entities.length,
2387
- limit,
2388
- offset,
2389
- hasMore: entities.length >= limit
2390
- }
2391
- });
2392
- },
2393
- onError
2394
- });
2395
- } : void 0,
2396
- listenById: driver.listenEntity ? (id, onUpdate, onError) => {
2397
- return driver.listenEntity({
2398
- path: slug,
2399
- entityId: id,
2400
- onUpdate: (entity) => onUpdate(entity ?? void 0),
2401
- onError
2402
- });
2403
- } : void 0,
2404
- // Fluent Query Builder
2405
- where(columnOrCondition, operator, value) {
2406
- const builder = new QueryBuilder(accessor);
2407
- if (typeof columnOrCondition === "object") {
2408
- return builder.where(columnOrCondition);
2409
- }
2410
- return builder.where(columnOrCondition, operator, value);
2411
- },
2412
- orderBy(column, ascending) {
2413
- return new QueryBuilder(accessor).orderBy(column, ascending);
2414
- },
2415
- limit(count) {
2416
- return new QueryBuilder(accessor).limit(count);
2417
- },
2418
- offset(count) {
2419
- return new QueryBuilder(accessor).offset(count);
2420
- },
2421
- search(searchString) {
2422
- return new QueryBuilder(accessor).search(searchString);
2423
- },
2424
- include(...relations) {
2425
- return new QueryBuilder(accessor).include(...relations);
2426
- }
2427
- };
2428
- return accessor;
2429
- }
2023
+ const accessor = {
2024
+ async find(params) {
2025
+ const orderParsed = parseOrderBy(params?.orderBy);
2026
+ const entities = await driver.fetchCollection({
2027
+ path: slug,
2028
+ limit: params?.limit,
2029
+ offset: params?.offset,
2030
+ filter: convertWhereToFilter(params?.where),
2031
+ orderBy: orderParsed?.[0],
2032
+ order: orderParsed?.[1],
2033
+ searchString: params?.searchString
2034
+ });
2035
+ const limit = params?.limit ?? 20;
2036
+ const offset = params?.offset ?? 0;
2037
+ return {
2038
+ data: entities,
2039
+ meta: {
2040
+ total: entities.length,
2041
+ limit,
2042
+ offset,
2043
+ hasMore: entities.length >= limit
2044
+ }
2045
+ };
2046
+ },
2047
+ async findById(id) {
2048
+ return driver.fetchEntity({
2049
+ path: slug,
2050
+ entityId: id
2051
+ });
2052
+ },
2053
+ async create(data, id) {
2054
+ return driver.saveEntity({
2055
+ path: slug,
2056
+ values: data,
2057
+ entityId: id,
2058
+ status: "new"
2059
+ });
2060
+ },
2061
+ async update(id, data) {
2062
+ return driver.saveEntity({
2063
+ path: slug,
2064
+ values: data,
2065
+ entityId: id,
2066
+ status: "existing"
2067
+ });
2068
+ },
2069
+ async delete(id) {
2070
+ return driver.deleteEntity({ entity: {
2071
+ id,
2072
+ path: slug,
2073
+ values: {}
2074
+ } });
2075
+ },
2076
+ deleteAll: driver.deleteAll ? async () => {
2077
+ return driver.deleteAll(slug);
2078
+ } : void 0,
2079
+ count: driver.countEntities ? async (params) => {
2080
+ return driver.countEntities({
2081
+ path: slug,
2082
+ filter: convertWhereToFilter(params?.where)
2083
+ });
2084
+ } : void 0,
2085
+ listen: driver.listenCollection ? (params, onUpdate, onError) => {
2086
+ const orderParsed = parseOrderBy(params?.orderBy);
2087
+ const limit = params?.limit ?? 20;
2088
+ const offset = params?.offset ?? 0;
2089
+ return driver.listenCollection({
2090
+ path: slug,
2091
+ limit: params?.limit,
2092
+ offset: params?.offset,
2093
+ filter: convertWhereToFilter(params?.where),
2094
+ orderBy: orderParsed?.[0],
2095
+ order: orderParsed?.[1],
2096
+ searchString: params?.searchString,
2097
+ onUpdate: (entities) => {
2098
+ onUpdate({
2099
+ data: entities,
2100
+ meta: {
2101
+ total: entities.length,
2102
+ limit,
2103
+ offset,
2104
+ hasMore: entities.length >= limit
2105
+ }
2106
+ });
2107
+ },
2108
+ onError
2109
+ });
2110
+ } : void 0,
2111
+ listenById: driver.listenEntity ? (id, onUpdate, onError) => {
2112
+ return driver.listenEntity({
2113
+ path: slug,
2114
+ entityId: id,
2115
+ onUpdate: (entity) => onUpdate(entity ?? void 0),
2116
+ onError
2117
+ });
2118
+ } : void 0,
2119
+ where(columnOrCondition, operator, value) {
2120
+ const builder = new QueryBuilder(accessor);
2121
+ if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
2122
+ return builder.where(columnOrCondition, operator, value);
2123
+ },
2124
+ orderBy(column, ascending) {
2125
+ return new QueryBuilder(accessor).orderBy(column, ascending);
2126
+ },
2127
+ limit(count) {
2128
+ return new QueryBuilder(accessor).limit(count);
2129
+ },
2130
+ offset(count) {
2131
+ return new QueryBuilder(accessor).offset(count);
2132
+ },
2133
+ search(searchString) {
2134
+ return new QueryBuilder(accessor).search(searchString);
2135
+ },
2136
+ include(...relations) {
2137
+ return new QueryBuilder(accessor).include(...relations);
2138
+ }
2139
+ };
2140
+ return accessor;
2141
+ }
2142
+ /**
2143
+ * Build a `RebaseData` object from a `DataDriver` using JavaScript Proxy.
2144
+ *
2145
+ * This is the key bridge: any property access like `data.products` returns
2146
+ * a `CollectionAccessor` backed by the underlying DataDriver, without
2147
+ * needing per-collection code generation.
2148
+ *
2149
+ * @example
2150
+ * const data = buildRebaseData(driver);
2151
+ * await data.products.create({ name: "Camera", price: 299 });
2152
+ * const { data: items } = await data.products.find({ where: { status: "eq.published" } });
2153
+ */
2430
2154
  function buildRebaseData(driver) {
2431
- const cache = /* @__PURE__ */ new Map();
2432
- function getAccessor(slug) {
2433
- let accessor = cache.get(slug);
2434
- if (!accessor) {
2435
- accessor = createDriverAccessor(driver, slug);
2436
- cache.set(slug, accessor);
2437
- }
2438
- return accessor;
2439
- }
2440
- const target = {
2441
- collection: getAccessor
2442
- };
2443
- return new Proxy(target, {
2444
- get(_target, prop) {
2445
- if (prop === "collection") return getAccessor;
2446
- if (typeof prop === "symbol") return void 0;
2447
- if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
2448
- const slug = toSnakeCase(prop);
2449
- return getAccessor(slug);
2450
- }
2451
- });
2452
- }
2453
- export {
2454
- COLLECTION_PATH_SEPARATOR,
2455
- CollectionRegistry,
2456
- DEFAULT_ONE_OF_TYPE,
2457
- DEFAULT_ONE_OF_VALUE,
2458
- QueryBuilder,
2459
- addInitialSlash,
2460
- and,
2461
- applyPropertyConditions,
2462
- buildAdditionalFieldDelegate,
2463
- buildCollection,
2464
- buildConditionContext,
2465
- buildEntityCallbacks,
2466
- buildEnum,
2467
- buildEnumValueConfig,
2468
- buildProperties,
2469
- buildPropertiesOrBuilder,
2470
- buildProperty,
2471
- buildPropertyCallbacks,
2472
- buildRebaseData,
2473
- canCreateEntity,
2474
- canDeleteEntity,
2475
- canEditEntity,
2476
- canReadCollection,
2477
- checkOperation,
2478
- cond,
2479
- createRelationRef,
2480
- createRelationRefWithData,
2481
- defaultUsersCollection,
2482
- enumToObjectEntries,
2483
- evaluateCondition,
2484
- findRelation,
2485
- fullPathToCollectionSegments,
2486
- getArrayResolvedProperties,
2487
- getCollectionBySlugWithin,
2488
- getCollectionPathsCombinations,
2489
- getColumnName,
2490
- getDefaultValueFor,
2491
- getDefaultValueFortype,
2492
- getDefaultValuesFor,
2493
- getEntityImagePreviewPropertyKey,
2494
- getEnumVarName,
2495
- getLabelOrConfigFrom,
2496
- getLastSegment,
2497
- getLocalChangesBackup,
2498
- getNavigationEntriesFromPath,
2499
- getParentReferencesFromPath,
2500
- getPrimaryKeys,
2501
- getReferenceFrom,
2502
- getRelationFrom,
2503
- getSubcollections,
2504
- getTableName,
2505
- getTableVarName,
2506
- isHidden,
2507
- isPropertyBuilder,
2508
- isReadOnly,
2509
- normalizeToEntityRelation,
2510
- or,
2511
- registerConditionOperations,
2512
- removeInitialAndTrailingSlashes,
2513
- removeInitialSlash,
2514
- removeTrailingSlash,
2515
- resolveArrayProperties,
2516
- resolveCollectionPathIds,
2517
- resolveCollectionRelations,
2518
- resolveDefaultSelectedView,
2519
- resolveEnumValues,
2520
- resolveProperties,
2521
- resolveProperty,
2522
- resolvePropertyEnum,
2523
- resolvePropertyRelation,
2524
- resolveRelationProperty,
2525
- resolveStorageFilenameString,
2526
- resolveStoragePathString,
2527
- sanitizeData,
2528
- sanitizeRelation,
2529
- segmentsToStrippedPath,
2530
- sortProperties,
2531
- stripCollectionPath,
2532
- traverseValueProperty,
2533
- traverseValuesProperties,
2534
- updateDateAutoValues
2535
- };
2536
- //# sourceMappingURL=index.es.js.map
2155
+ const cache = /* @__PURE__ */ new Map();
2156
+ function getAccessor(slug) {
2157
+ let accessor = cache.get(slug);
2158
+ if (!accessor) {
2159
+ accessor = createDriverAccessor(driver, slug);
2160
+ cache.set(slug, accessor);
2161
+ }
2162
+ return accessor;
2163
+ }
2164
+ return new Proxy({ collection: getAccessor }, { get(_target, prop) {
2165
+ if (prop === "collection") return getAccessor;
2166
+ if (typeof prop === "symbol") return void 0;
2167
+ if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
2168
+ return getAccessor(toSnakeCase(prop));
2169
+ } });
2170
+ }
2171
+ //#endregion
2172
+ export { COLLECTION_PATH_SEPARATOR, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, QueryBuilder, addInitialSlash, and, applyPropertyConditions, buildAdditionalFieldDelegate, buildCollection, buildConditionContext, buildEntityCallbacks, buildEnum, buildEnumValueConfig, buildProperties, buildPropertiesOrBuilder, buildProperty, buildPropertyCallbacks, buildRebaseData, canCreateEntity, canDeleteEntity, canEditEntity, canReadCollection, checkOperation, cond, createRelationRef, createRelationRefWithData, defaultUsersCollection, enumToObjectEntries, evaluateCondition, findRelation, fullPathToCollectionSegments, getArrayResolvedProperties, getCollectionBySlugWithin, getCollectionPathsCombinations, getColumnName, getDefaultValueFor, getDefaultValueFortype, getDefaultValuesFor, getEntityImagePreviewPropertyKey, getEnumVarName, getLabelOrConfigFrom, getLastSegment, getLocalChangesBackup, getNavigationEntriesFromPath, getParentReferencesFromPath, getPrimaryKeys, getReferenceFrom, getRelationFrom, getSubcollections, getTableName, getTableVarName, isHidden, isPropertyBuilder, isReadOnly, normalizeToEntityRelation, or, registerConditionOperations, removeInitialAndTrailingSlashes, removeInitialSlash, removeTrailingSlash, resolveArrayProperties, resolveCollectionPathIds, resolveCollectionRelations, resolveDefaultSelectedView, resolveEnumValues, resolveProperties, resolveProperty, resolvePropertyEnum, resolvePropertyRelation, resolveRelationProperty, resolveStorageFilenameString, resolveStoragePathString, sanitizeData, sanitizeRelation, segmentsToStrippedPath, sortProperties, stripCollectionPath, traverseValueProperty, traverseValuesProperties, updateDateAutoValues };
2173
+
2174
+ //# sourceMappingURL=index.es.js.map