@rebasepro/common 0.0.1-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +174 -0
  3. package/dist/collections/CollectionRegistry.d.ts +48 -0
  4. package/dist/collections/index.d.ts +1 -0
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.es.js +2380 -0
  7. package/dist/index.es.js.map +1 -0
  8. package/dist/index.umd.js +2379 -0
  9. package/dist/index.umd.js.map +1 -0
  10. package/dist/util/arrays.d.ts +1 -0
  11. package/dist/util/builders.d.ts +64 -0
  12. package/dist/util/callbacks.d.ts +6 -0
  13. package/dist/util/collections.d.ts +11 -0
  14. package/dist/util/common.d.ts +2 -0
  15. package/dist/util/conditions.d.ts +26 -0
  16. package/dist/util/dates.d.ts +1 -0
  17. package/dist/util/entities.d.ts +28 -0
  18. package/dist/util/entity_actions.d.ts +2 -0
  19. package/dist/util/enums.d.ts +3 -0
  20. package/dist/util/fields.d.ts +2 -0
  21. package/dist/util/flatten_object.d.ts +5 -0
  22. package/dist/util/hash.d.ts +1 -0
  23. package/dist/util/index.d.ts +26 -0
  24. package/dist/util/names.d.ts +22 -0
  25. package/dist/util/navigation_from_path.d.ts +29 -0
  26. package/dist/util/navigation_utils.d.ts +31 -0
  27. package/dist/util/objects.d.ts +26 -0
  28. package/dist/util/os.d.ts +2 -0
  29. package/dist/util/parent_references_from_path.d.ts +6 -0
  30. package/dist/util/paths.d.ts +14 -0
  31. package/dist/util/permissions.d.ts +5 -0
  32. package/dist/util/permissions.test.d.ts +1 -0
  33. package/dist/util/plurals.d.ts +16 -0
  34. package/dist/util/references.d.ts +2 -0
  35. package/dist/util/regexp.d.ts +7 -0
  36. package/dist/util/relations.d.ts +12 -0
  37. package/dist/util/resolutions.d.ts +74 -0
  38. package/dist/util/storage.d.ts +24 -0
  39. package/dist/util/strings.d.ts +7 -0
  40. package/package.json +118 -0
  41. package/src/collections/CollectionRegistry.ts +319 -0
  42. package/src/collections/index.ts +1 -0
  43. package/src/index.ts +2 -0
  44. package/src/util/arrays.ts +3 -0
  45. package/src/util/builders.ts +138 -0
  46. package/src/util/callbacks.ts +115 -0
  47. package/src/util/collections.ts +126 -0
  48. package/src/util/common.ts +2 -0
  49. package/src/util/conditions.ts +348 -0
  50. package/src/util/dates.ts +1 -0
  51. package/src/util/entities.ts +212 -0
  52. package/src/util/entity_actions.ts +28 -0
  53. package/src/util/enums.ts +26 -0
  54. package/src/util/fields.ts +28 -0
  55. package/src/util/flatten_object.ts +45 -0
  56. package/src/util/hash.ts +11 -0
  57. package/src/util/index.ts +26 -0
  58. package/src/util/names.ts +30 -0
  59. package/src/util/navigation_from_path.ts +121 -0
  60. package/src/util/navigation_utils.ts +222 -0
  61. package/src/util/objects.ts +376 -0
  62. package/src/util/os.ts +13 -0
  63. package/src/util/parent_references_from_path.ts +57 -0
  64. package/src/util/paths.ts +27 -0
  65. package/src/util/permissions.test.ts +716 -0
  66. package/src/util/permissions.ts +235 -0
  67. package/src/util/plurals.ts +188 -0
  68. package/src/util/references.ts +34 -0
  69. package/src/util/regexp.ts +32 -0
  70. package/src/util/relations.ts +211 -0
  71. package/src/util/resolutions.ts +383 -0
  72. package/src/util/storage.ts +144 -0
  73. package/src/util/strings.ts +84 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.es.js","sources":["../src/util/common.ts","../src/util/objects.ts","../src/util/entities.ts","../src/util/collections.ts","../src/util/strings.ts","../src/util/dates.ts","../src/util/enums.ts","../src/util/paths.ts","../src/util/regexp.ts","../src/util/fields.ts","../src/util/resolutions.ts","../src/util/navigation_utils.ts","../src/util/entity_actions.ts","../src/util/permissions.ts","../src/util/plurals.ts","../src/util/references.ts","../src/util/flatten_object.ts","../src/util/navigation_from_path.ts","../src/util/parent_references_from_path.ts","../src/util/builders.ts","../src/util/storage.ts","../src/util/arrays.ts","../src/util/callbacks.ts","../src/util/hash.ts","../src/util/names.ts","../src/util/relations.ts","../src/util/conditions.ts","../src/collections/CollectionRegistry.ts"],"sourcesContent":["export const DEFAULT_ONE_OF_TYPE = \"type\"\nexport const DEFAULT_ONE_OF_VALUE = \"value\"\n","import hash from \"object-hash\";\nimport { GeoPoint } from \"@rebasepro/types\";\n\n/** @private is the value an empty array? */\nexport const isEmptyArray = (value?: unknown) =>\n Array.isArray(value) && value.length === 0;\n\n/** @private is the given object a Function? */\nexport const isFunction = (obj: unknown): obj is Function =>\n typeof obj === \"function\";\n\n/** @private is the given object an integer? */\nexport const isInteger = (obj: unknown): boolean =>\n String(Math.floor(Number(obj))) === String(obj);\n\n/** @private is the given object a NaN? */\n// eslint-disable-next-line no-self-compare\nexport const isNaN = (obj: unknown): boolean => obj !== obj;\n\n/**\n * Deeply get a value from an object via its path.\n */\nexport function getIn(\n obj: Record<string, unknown> | unknown[] | unknown,\n key: string | string[],\n def?: unknown,\n p = 0\n) {\n const path = toPath(key);\n while (obj && p < path.length) {\n obj = (obj as Record<string, unknown>)[path[p++]];\n }\n\n // check if path is not in the end\n if (p !== path.length && !obj) {\n return def;\n }\n\n return obj === undefined ? def : obj;\n}\n\nexport function setIn<T>(obj: T, path: string, value: unknown): T {\n const res = clone(obj) as Record<string, unknown>;\n let resVal: Record<string, unknown> = res;\n let i = 0;\n const pathArray = toPath(path);\n\n for (; i < pathArray.length - 1; i++) {\n const currentPath: string = pathArray[i];\n const currentObj = getIn(obj as Record<string, unknown>, pathArray.slice(0, i + 1));\n\n if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) {\n resVal = resVal[currentPath] = clone(currentObj) as Record<string, unknown>;\n } else {\n const nextPath: string = pathArray[i + 1];\n resVal = resVal[currentPath] =\n (isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {}) as Record<string, unknown>;\n }\n }\n\n // Return original object if new value is the same as current\n if ((i === 0 ? obj as Record<string, unknown> : resVal)[pathArray[i]] === value) {\n return obj;\n }\n\n if (value === undefined) {\n delete resVal[pathArray[i]];\n } else {\n resVal[pathArray[i]] = value;\n }\n\n // If the path array has a single element, the loop did not run.\n // Deleting on `resVal` had no effect in this scenario, so we delete on the result instead.\n if (i === 0 && value === undefined) {\n delete res[pathArray[i]];\n }\n\n return res as T;\n}\n\nexport function clone<T>(value: T): T {\n if (Array.isArray(value)) {\n return [...value] as unknown as T;\n } else if (typeof value === \"object\" && value !== null) {\n return { ...value } as T;\n } else {\n return value; // This is for primitive types which do not need cloning.\n }\n}\n\nfunction toPath(value: string | string[]) {\n if (Array.isArray(value)) return value; // Already in path array form.\n // Replace brackets with dots, remove leading/trailing dots, then split by dot.\n return value.replace(/\\[(\\d+)]/g, \".$1\").replace(/^\\./, \"\").replace(/\\.$/, \"\").split(\".\");\n}\n\n\nexport const pick: <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => Partial<T> = <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => ({\n ...args.reduce<Record<string, unknown>>((res, key) => ({\n ...res,\n [key as string]: obj[key as string]\n }), {})\n}) as Partial<T>;\n\nexport function isObject(item: unknown): item is Record<string, unknown> {\n return !!item && typeof item === \"object\" && !Array.isArray(item);\n}\n\nexport function isPlainObject(obj: unknown): obj is Record<string, unknown> {\n // 1. Rule out non-objects, null, and arrays\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) {\n return false;\n }\n\n // 2. Get the object's direct prototype\n const proto = Object.getPrototypeOf(obj);\n\n // 3. A plain object's direct prototype is Object.prototype\n return proto === Object.prototype;\n}\n\nexport function mergeDeep<T extends Record<string, any>, U extends Record<string, any>>(\n target: T,\n source: U,\n ignoreUndefined: boolean = false\n): T & U {\n // If target is not a true object (e.g., null, array, primitive), return target itself.\n if (!isObject(target)) {\n return target as T & U;\n }\n\n // Create a shallow copy of the target to avoid modifying the original object.\n const output = { ...target };\n\n // If source is not a true object, there's nothing to merge from it.\n // Return the shallow copy of target.\n if (!isObject(source)) {\n return output as T & U;\n }\n\n // Iterate over keys in the source object.\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const outputValue = (output as any)[key]; // Current value in our merged object (originating from target)\n\n // Skip if source value is undefined and ignoreUndefined is true.\n // This handles both not adding new undefined properties and not overwriting existing properties with undefined.\n if (ignoreUndefined && sourceValue === undefined) {\n continue;\n }\n\n if ((sourceValue as unknown) instanceof Date) {\n // If source value is a Date, create a new Date instance.\n (output as Record<string, unknown>)[key] = new Date((sourceValue as unknown as Date).getTime());\n } else if (Array.isArray(sourceValue)) {\n if (Array.isArray(outputValue)) {\n const newArray = [];\n const maxLength = Math.max(outputValue.length, sourceValue.length);\n for (let i = 0; i < maxLength; i++) {\n const sourceItem = sourceValue[i];\n const targetItem = outputValue[i];\n\n if (i >= sourceValue.length) { // source is shorter\n newArray[i] = targetItem;\n } else if (i >= outputValue.length) { // target is shorter\n newArray[i] = sourceItem;\n } else if (sourceItem === null) {\n newArray[i] = targetItem;\n } else if (isPlainObject(sourceItem) && isPlainObject(targetItem)) {\n // Only recursively merge plain objects, preserve class instances\n newArray[i] = mergeDeep(targetItem, sourceItem, ignoreUndefined);\n } else {\n // For class instances and primitives, use source directly\n newArray[i] = sourceItem;\n }\n }\n (output as Record<string, unknown>)[key] = newArray;\n } else {\n // If output's value (from target) is not an array,\n // overwrite with a shallow copy of the source array.\n (output as Record<string, unknown>)[key] = [...sourceValue];\n }\n } else if (isPlainObject(sourceValue)) {\n // If source value is a plain object (not a class instance like EntityReference, GeoPoint, etc.):\n if (isPlainObject(outputValue)) {\n // If the corresponding value in output (from target) is also a plain object, recurse.\n // Ensure the ignoreUndefined flag is passed down.\n (output as Record<string, unknown>)[key] = mergeDeep(outputValue as Record<string, unknown>, sourceValue, ignoreUndefined);\n } else {\n // If output's value (from target) is not a plain object (e.g., null, primitive, class instance, or key didn't exist in original target),\n // overwrite with the source object.\n (output as Record<string, unknown>)[key] = sourceValue;\n }\n } else if (isObject(sourceValue)) {\n // If source value is a class instance (not a plain object), use it directly to preserve prototype\n (output as Record<string, unknown>)[key] = sourceValue;\n } else {\n // If source value is a primitive, null, or undefined (and not ignored).\n (output as Record<string, unknown>)[key] = sourceValue;\n }\n }\n }\n\n return output as T & U;\n}\n\nexport function getValueInPath(o: object | undefined, path: string): unknown {\n if (!o) return undefined;\n if (typeof o === \"object\") {\n if (path in o) {\n return (o as Record<string, unknown>)[path];\n }\n if (path.includes(\".\") || path.includes(\"[\")) {\n let pathSegments = path.split(/[.[]/);\n if (path.includes(\"[\")) {\n pathSegments = pathSegments.map(segment => segment.replace(\"]\", \"\"));\n }\n const firstSegment = pathSegments[0];\n const isArrayAndIndexExists = Array.isArray((o as Record<string, unknown>)[firstSegment]) && !isNaN(parseInt(pathSegments[1]));\n const nextObject = isArrayAndIndexExists\n ? ((o as Record<string, unknown>)[firstSegment] as unknown[])[parseInt(pathSegments[1])]\n : (o as Record<string, unknown>)[firstSegment];\n\n const nextPath = pathSegments.slice(isArrayAndIndexExists ? 2 : 1).join(\".\");\n if (nextPath === \"\")\n return nextObject;\n return getValueInPath(nextObject as object | undefined, nextPath);\n }\n }\n return undefined;\n}\n\nexport function removeInPath(o: object, path: string): object | undefined {\n let currentObject = { ...o };\n const parts = path.split(\".\");\n const last = parts.pop();\n for (const part of parts) {\n currentObject = (currentObject as Record<string, unknown>)[part] as Record<string, unknown>;\n }\n if (last)\n delete (currentObject as Record<string, unknown>)[last];\n return currentObject;\n}\n\nexport function removeFunctions(o: unknown): unknown {\n if (o === undefined) return undefined;\n if (o === null) return null;\n if (typeof o === \"object\") {\n // Handle arrays first - map over them recursively\n if (Array.isArray(o)) {\n return o.map(v => removeFunctions(v));\n }\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(o)) {\n return o;\n }\n return Object.entries(o)\n .filter(([_, value]) => typeof value !== \"function\")\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return { [key]: value.map(v => removeFunctions(v)) };\n } else if (typeof value === \"object\") {\n return { [key]: removeFunctions(value) };\n } else return { [key]: value };\n })\n .reduce((a, b) => ({ ...a, ...b }), {});\n }\n return o;\n}\n\nexport function getHashValue<T>(v: T): string | null {\n if (!v) return null;\n if (typeof v === \"object\" && v !== null) {\n if (\"id\" in v)\n return String((v as Record<string, unknown>).id);\n else if (v instanceof Date)\n return v.toLocaleString();\n else if (v instanceof GeoPoint)\n return hash(v as unknown as Record<string, unknown>);\n }\n return hash(v as object, { ignoreUnknown: true });\n}\n\nexport function removeUndefined(value: unknown, removeEmptyStrings?: boolean): unknown {\n if (typeof value === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v: unknown) => removeUndefined(v, removeEmptyStrings));\n }\n if (typeof value === \"object\") {\n if (value === null)\n return value;\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(value)) {\n return value;\n }\n const res: Record<string, unknown> = {};\n Object.keys(value).forEach((key) => {\n if (!isEmptyObject(value as object)) {\n const childRes = removeUndefined((value as Record<string, unknown>)[key], removeEmptyStrings);\n const isString = typeof childRes === \"string\";\n const shouldKeepIfString = !removeEmptyStrings || (removeEmptyStrings && !isString) || (removeEmptyStrings && isString && childRes !== \"\");\n if (childRes !== undefined && !isEmptyObject(childRes as object) && shouldKeepIfString)\n res[key] = childRes;\n }\n });\n return res;\n }\n return value;\n}\n\nexport function removeNulls(value: unknown): unknown {\n if (typeof value === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v: unknown) => removeNulls(v));\n }\n if (typeof value === \"object\") {\n if (value === null)\n return value;\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(value)) {\n return value;\n }\n const res: Record<string, unknown> = {};\n const obj = value as Record<string, unknown>;\n Object.keys(obj).forEach((key) => {\n if (obj[key] !== null)\n res[key] = removeNulls(obj[key]);\n });\n return res;\n }\n return value;\n}\n\nexport function isEmptyObject(obj: object) {\n return obj &&\n Object.getPrototypeOf(obj) === Object.prototype &&\n Object.keys(obj).length === 0\n}\n\nexport function removePropsIfExisting(source: Record<string, unknown> | unknown[], comparison: Record<string, unknown> | unknown[]) {\n const isObject = (val: unknown): val is Record<string, unknown> => typeof val === \"object\" && val !== null;\n const isArray = (val: unknown): val is unknown[] => Array.isArray(val);\n\n if (!isObject(source) || !isObject(comparison)) {\n return source;\n }\n\n const res = isArray(source) ? [...source] : { ...source };\n\n if (isArray(res)) {\n for (let i = res.length - 1; i >= 0; i--) {\n if (res[i] === comparison[i]) {\n res.splice(i, 1);\n } else if (isObject(res[i]) && isObject(comparison[i])) {\n res[i] = removePropsIfExisting(res[i] as Record<string, unknown>, (comparison as unknown as unknown[])[i] as Record<string, unknown>);\n }\n }\n } else {\n Object.keys(comparison).forEach(key => {\n if (key in res) {\n if (isObject(res[key]) && isObject(comparison[key])) {\n res[key] = removePropsIfExisting(res[key], comparison[key]);\n } else if (res[key] === comparison[key]) {\n delete res[key];\n }\n }\n });\n }\n\n return res;\n}\n","import {\n DataType,\n Entity,\n EntityReference,\n EntityRelation,\n EntityStatus,\n EntityValues,\n Properties,\n Property,\n} from \"@rebasepro/types\";\nimport { DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE } from \"./common\";\nimport { mergeDeep } from \"./objects\";\n\nexport function isReadOnly(property: Property): boolean {\n if (property.readOnly)\n return true;\n if (property.type === \"date\") {\n if (property.autoValue)\n return true;\n }\n if (property.type === \"reference\") {\n return !property.path && !property.Field;\n }\n return false;\n}\n\nexport function isHidden(property: Property): boolean {\n return typeof property.disabled === \"object\" && Boolean(property.disabled.hidden);\n}\n\nexport function isPropertyBuilder(property?: Property) {\n return typeof property?.dynamicProps === \"function\";\n}\n\nexport function getDefaultValuesFor<M extends Record<string, any>>(properties: Properties): Partial<EntityValues<M>> {\n if (!properties) return {};\n return Object.entries(properties)\n .map(([key, property]) => {\n if (!property) return {};\n const value = getDefaultValueFor(property);\n return value === undefined ? {} : { [key]: value };\n })\n .reduce((a, b) => ({ ...a, ...b }), {}) as EntityValues<M>;\n}\n\nexport function getDefaultValueFor(property?: Property) {\n if (!property) return undefined;\n if (isPropertyBuilder(property)) return undefined;\n if (property.defaultValue || property.defaultValue === null) {\n return property.defaultValue;\n } else if (property.type === \"map\" && property.properties) {\n const defaultValuesFor = getDefaultValuesFor(property.properties as Properties);\n if (Object.keys(defaultValuesFor).length === 0) return undefined;\n return defaultValuesFor;\n } else {\n return getDefaultValueFortype(property.type);\n }\n}\n\nexport function getDefaultValueFortype(type: DataType) {\n if (type === \"string\") {\n return null;\n } else if (type === \"number\") {\n return null;\n } else if (type === \"boolean\") {\n return false;\n } else if (type === \"date\") {\n return null;\n } else if (type === \"array\") {\n return [];\n } else if (type === \"map\") {\n return {};\n } else {\n return null;\n }\n}\n\n/**\n * Update the automatic values in an entity before save\n * @group Datasource\n */\nexport function updateDateAutoValues<M extends Record<string, any>>({\n inputValues,\n properties,\n status,\n timestampNowValue\n}:\n {\n inputValues: Partial<EntityValues<M>>,\n properties: Properties,\n status: EntityStatus,\n timestampNowValue: unknown\n }): EntityValues<M> {\n return traverseValuesProperties(\n inputValues,\n properties,\n (inputValue, property) => {\n if (property.type === \"date\") {\n if (status === \"existing\" && property.autoValue === \"on_update\") {\n return timestampNowValue;\n } else if ((status === \"new\" || status === \"copy\") &&\n (property.autoValue === \"on_update\" || property.autoValue === \"on_create\")) {\n return timestampNowValue;\n } else {\n return inputValue;\n }\n } else {\n return inputValue;\n }\n }\n ) ?? {} as M;\n}\n\n/**\n * Add missing required fields, expected in the collection, to the values of an entity\n * @param values\n * @param properties\n * @group Datasource\n */\nexport function sanitizeData<M extends Record<string, any>>\n (\n values: EntityValues<M>,\n properties: Properties\n ) {\n const result = values as Record<string, unknown>;\n Object.entries(properties)\n .forEach(([key, property]) => {\n if (values && values[key] !== undefined) result[key] = values[key];\n else if ((property as Property).validation?.required) result[key] = null;\n });\n return result;\n}\n\nexport function getReferenceFrom<M extends Record<string, any>>(entity: Entity<M>): EntityReference {\n if (typeof entity.id !== \"string\")\n throw new Error(\"Only string IDs are supported in references\");\n return new EntityReference({\n id: entity.id,\n path: entity.path,\n datasource: entity.datasource,\n databaseId: entity.databaseId\n });\n}\n\nexport function getRelationFrom<M extends Record<string, any>>(entity: Entity<M>): EntityRelation {\n return new EntityRelation(entity.id, entity.path);\n}\n\nexport function traverseValuesProperties<M extends Record<string, any>>(\n inputValues: Partial<EntityValues<M>>,\n properties: Properties,\n operation: (value: unknown, property: Property) => unknown\n): EntityValues<M> | undefined {\n // Handle null/undefined inputValues - use empty object as base for mergeDeep\n const safeInputValues = inputValues ?? {};\n\n const updatedValues = Object.entries(properties)\n .map(([key, property]) => {\n const inputValue = safeInputValues && (safeInputValues)[key];\n const updatedValue = traverseValueProperty(inputValue, property as Property, operation);\n if (updatedValue === null) return null;\n if (updatedValue === undefined) return undefined;\n return ({ [key]: updatedValue });\n })\n .reduce((a, b) => ({ ...a, ...b }), {}) as EntityValues<M>;\n // Use mergeDeep to preserve class instances like EntityReference, GeoPoint\n const result = mergeDeep(safeInputValues, updatedValues);\n if (!result || Object.keys(result).length === 0) return undefined;\n return result;\n}\n\nexport function traverseValueProperty(inputValue: unknown,\n property: Property,\n operation: (value: unknown, property: Property) => unknown): unknown {\n\n let value;\n if (property.type === \"map\" && property.properties) {\n value = traverseValuesProperties(inputValue as Partial<Record<string, unknown>>, property.properties, operation);\n } else if (property.type === \"array\") {\n const of = property.of;\n if (of && Array.isArray(inputValue) && !Array.isArray(of)) {\n value = inputValue.map((e) => traverseValueProperty(e, of, operation));\n } else if (of && Array.isArray(inputValue) && Array.isArray(of)) {\n value = inputValue.map((e, i) => {\n if (i < of.length)\n return traverseValueProperty(e, of[i], operation);\n return null\n }).filter(Boolean);\n } else if (property.oneOf && Array.isArray(inputValue)) {\n const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;\n const valueField = property.oneOf?.valueField ?? DEFAULT_ONE_OF_VALUE;\n value = inputValue.map((e) => {\n if (e === null) return null;\n if (typeof e !== \"object\") return e;\n const rec = e as Record<string, unknown>;\n const type = rec[typeField] as string;\n const childProperty = property.oneOf?.properties[type];\n if (!type || !childProperty) return e;\n return {\n [typeField]: type,\n [valueField]: traverseValueProperty(rec[valueField], childProperty, operation)\n };\n });\n } else {\n value = inputValue;\n }\n } else {\n value = operation(inputValue, property);\n }\n\n return value;\n}\n","import {\n DefaultSelectedViewBuilder,\n DefaultSelectedViewParams,\n EntityCollection,\n Properties,\n Property,\n} from \"@rebasepro/types\";\nimport { isPropertyBuilder } from \"./entities\";\n\nexport function sortProperties<M extends Record<string, any>>(properties: Properties, propertiesOrder?: string[]): Properties {\n try {\n const propertiesKeys = Object.keys(properties);\n // If no propertiesOrder, just use the original keys order\n if (!propertiesOrder || propertiesOrder.length === 0) {\n return propertiesKeys\n .map((key) => {\n const property = properties[key] as Property;\n if (!isPropertyBuilder(property) && property?.type === \"map\" && property.properties) {\n return ({\n [key]: {\n ...property,\n properties: sortProperties(property.properties, property.propertiesOrder)\n }\n });\n } else {\n return ({ [key]: property });\n }\n })\n .reduce((a: Properties, b: Properties) => ({ ...a, ...b }), {}) as Properties;\n }\n\n // Filter propertiesOrder to only include TOP-LEVEL property keys that exist\n // (ignore nested keys like \"data.mode\" - they are for column ordering, not property filtering)\n const validOrderKeys = (propertiesOrder as string[]).filter(key => {\n // Only include top-level keys (no dots) that exist in properties\n return !key.includes(\".\") && properties[key];\n });\n\n // Track which properties we've processed\n const processedKeys = new Set<string>(validOrderKeys);\n\n // Build result starting with ordered properties\n const orderedResult = validOrderKeys\n .map((key) => {\n const property = properties[key] as Property;\n if (!isPropertyBuilder(property) && property?.type === \"map\" && property.properties) {\n return ({\n [key]: {\n ...property,\n properties: sortProperties(property.properties, property.propertiesOrder)\n }\n });\n } else {\n return ({ [key]: property });\n }\n })\n .reduce((a: any, b: any) => ({ ...a, ...b }), {}) as Properties;\n\n // Append any properties that were NOT in propertiesOrder (so they don't disappear!)\n const missingProperties = propertiesKeys\n .filter(key => !processedKeys.has(key))\n .map((key) => {\n const property = properties[key] as Property;\n if (!isPropertyBuilder(property) && property?.type === \"map\" && property.properties) {\n return ({\n [key]: {\n ...property,\n properties: sortProperties(property.properties, property.propertiesOrder)\n }\n });\n } else {\n return ({ [key]: property });\n }\n })\n .reduce((a: any, b: any) => ({ ...a, ...b }), {}) as Properties;\n\n return { ...orderedResult, ...missingProperties };\n } catch (e) {\n console.error(\"Error sorting properties\", e);\n return properties;\n }\n}\n\nexport function resolveDefaultSelectedView(\n defaultSelectedView: string | DefaultSelectedViewBuilder | undefined,\n params: DefaultSelectedViewParams\n) {\n if (!defaultSelectedView) {\n return undefined;\n } else if (typeof defaultSelectedView === \"string\") {\n return defaultSelectedView;\n } else {\n return defaultSelectedView(params);\n }\n}\n\n\n\nexport function getLocalChangesBackup(collection: EntityCollection) {\n if (!collection.localChangesBackup) {\n return \"manual_apply\";\n }\n\n return collection.localChangesBackup;\n}\n\n/**\n * Returns the primary keys for an entity collection by inspecting the properties\n * and finding any properties with `isId`.\n * Fallbacks to `[\"id\"]` if no properties are marked as `isId: true`.\n * @param collection\n */\nexport function getPrimaryKeys<M extends Record<string, any>>(collection: EntityCollection<M>): Extract<keyof M, string>[] {\n const properties = collection.properties;\n if (!properties) {\n return [\"id\"] as Extract<keyof M, string>[];\n }\n const ids = Object.entries(properties)\n .filter(([key, prop]) => typeof prop === \"object\" && prop !== null && \"isId\" in prop && Boolean(prop.isId))\n .map(([key]) => key);\n\n if (ids.length > 0) {\n return ids as Extract<keyof M, string>[];\n }\n return [\"id\"] as Extract<keyof M, string>[];\n}\n","const kebabCaseRegex = /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g;\n\nexport const toKebabCase = (str: string) => {\n const regExpMatchArray = str.match(kebabCaseRegex);\n if (!regExpMatchArray) return \"\";\n return regExpMatchArray\n .map(x => x.toLowerCase())\n .join(\"-\");\n};\n\nconst snakeCaseRegex = /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g;\n\nexport const toSnakeCase = (str: string) => {\n const regExpMatchArray = str.match(snakeCaseRegex);\n if (!regExpMatchArray) return \"\";\n return regExpMatchArray\n .map(x => x.toLowerCase())\n .join(\"_\");\n};\n\nexport function randomString(strLength = 5) {\n return Math.random().toString(36).slice(2, 2 + strLength);\n}\n\nexport function randomColor() {\n return Math.floor(Math.random() * 16777215).toString(16);\n}\n\nexport function slugify(text?: string, separator = \"_\", lowercase = true) {\n if (!text) return \"\";\n const from = \"ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;-\"\n const to = `aaaaaeeeeeiiiiooooouuuunc${separator}${separator}${separator}${separator}${separator}${separator}${separator}`;\n\n for (let i = 0, l = from.length; i < l; i++) {\n text = text.replace(new RegExp(from.charAt(i), \"g\"), to.charAt(i));\n }\n\n text = text\n .toString() // Cast to string\n .replace(/\\s+/g, separator) // Replace spaces with separator\n .replace(/&/g, separator) // Replace & with separator\n .replace(/[^\\w\\\\-]+/g, \"\") // Remove all non-word chars\n .replace(new RegExp(\"\\\\\" + separator + \"\\\\\" + separator + \"+\", \"g\"),\n separator) // Replace multiple separators with single one\n .trim() // Remove whitespace from both sides of a string\n .replace(/^\\s+|\\s+$/g, \"\");\n\n return lowercase\n ? text.toLowerCase() // Convert the string to lowercase letters\n : text;\n}\n\nexport function unslugify(slug?: string): string {\n if (!slug) return \"\";\n if (slug.includes(\"-\") || slug.includes(\"_\") || !slug.includes(\" \")) {\n const result = slug.replace(/[-_]/g, \" \");\n return result.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substring(1);\n }).trim();\n } else {\n return slug.trim();\n }\n}\n\nexport function prettifyIdentifier(input: string) {\n if (!input) return \"\";\n\n let text = input;\n\n // 1. Handle camelCase and Acronyms\n // Group 1 ($1 $2): Lowercase followed by Uppercase (e.g., imageURL -> image URL)\n // Group 2 ($3 $4): Uppercase followed by Uppercase+lowercase (e.g., XMLParser -> XML Parser)\n text = text.replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, \"$1$3 $2$4\");\n\n // 2. Replace hyphens/underscores with spaces\n text = text.replace(/[_-]+/g, \" \");\n\n // 3. Capitalize first letter of each word (Title Case)\n const s = text\n .trim()\n .replace(/\\b\\w/g, (char) => char.toUpperCase());\n console.log(\"Prettified identifier:\", { input,s });\n return s;\n}\n","export const defaultDateFormat = \"MMMM dd, yyyy, HH:mm:ss\";\n","import { EnumValueConfig, EnumValues } from \"@rebasepro/types\";\n\nexport function enumToObjectEntries(enumValues: EnumValues): EnumValueConfig[] {\n if (Array.isArray(enumValues)) {\n return enumValues;\n } else {\n return Object.entries(enumValues).map(([id, value]) => {\n if (typeof value === \"string\") {\n return {\n id,\n label: value\n }\n } else {\n return {\n ...value,\n id\n }\n }\n });\n }\n}\n\nexport function getLabelOrConfigFrom(enumValues: EnumValueConfig[], key?: string | number): EnumValueConfig | undefined {\n if (key === null || key === undefined) return undefined;\n return enumValues.find((entry) => String(entry.id) === String(key));\n}\n","export const COLLECTION_PATH_SEPARATOR = \"::\";\n\n/**\n * Remove the entity ids from a given path\n * `products/B44RG6APH/locales` => `products::locales`\n * @param path\n */\nexport function stripCollectionPath(path: string): string {\n return segmentsToStrippedPath(fullPathToCollectionSegments(path));\n}\n\nexport function segmentsToStrippedPath(paths: string[]) {\n if (paths.length === 1)\n return paths[0];\n return paths.reduce((a, b) => `${a}${COLLECTION_PATH_SEPARATOR}${b}`);\n}\n\n/**\n * Extract the collection path routes\n * `products/B44RG6APH/locales` => [`products`, `locales`]\n * @param path\n */\nexport function fullPathToCollectionSegments(path: string): string[] {\n return path\n .split(\"/\")\n .filter((e, i) => i % 2 === 0);\n}\n","export function serializeRegExp(input: RegExp): string {\n if (!input) return \"\";\n // const fragments = input.toString().match(/\\/(.*?)\\/([a-z]*)?$/i);\n // if (fragments) {\n // if (fragments[2])\n // return input.toString();\n // return fragments[1];\n // }\n return input.toString();\n}\n\n/**\n * Get a RegExp out of a serialized string\n * @param input\n */\nexport function hydrateRegExp(input?: string): RegExp | undefined {\n if (!input) return undefined;\n const fragments = input.match(/\\/(.*?)\\/([a-z]*)?$/i);\n if (fragments) {\n return new RegExp(fragments[1], fragments[2] || \"\");\n } else {\n return new RegExp(input, \"\");\n }\n}\n\nexport function isValidRegExp(input: string): boolean {\n const fullRegexp = input.match(/\\/((?![*+?])(?:[^\\r\\n[/\\\\]|\\\\.|\\[(?:[^\\r\\n\\]\\\\]|\\\\.)*])+)\\/((?:g(?:im?|mi?)?|i(?:gm?|mg?)?|m(?:gi?|ig?)?)?)/);\n if (fullRegexp)\n return true;\n const simpleRegexp = input.match(/((?![*+?])(?:[^\\r\\n[/\\\\]|\\\\.|\\[(?:[^\\r\\n\\]\\\\]|\\\\.)*])+)/);\n return !!simpleRegexp;\n}\n","import { DefaultFieldConfig } from \"@rebasepro/types\";\n\nexport function isDefaultFieldConfigId(id: string): id is DefaultFieldConfig {\n return [\"text_field\",\n \"multiline\",\n \"markdown\",\n \"url\",\n \"email\",\n \"switch\",\n \"select\",\n \"multi_select\",\n \"number_input\",\n \"number_select\",\n \"multi_number_select\",\n \"file_upload\",\n \"multi_file_upload\",\n \"reference_as_string\",\n \"reference\",\n \"multi_references\",\n \"relation\",\n \"date_time\",\n \"group\",\n \"key_value\",\n \"repeat\",\n \"custom_array\",\n \"block\"\n ].includes(id);\n}\n","import {\n ArrayProperty,\n AuthController,\n CustomizationController,\n EntityAction,\n EntityCollection,\n EntityCustomView,\n EnumValueConfig,\n EnumValues,\n NumberProperty,\n Properties,\n Property,\n PropertyConfig,\n Relation,\n RelationProperty,\n StringProperty\n} from \"@rebasepro/types\";\nimport { isDefaultFieldConfigId } from \"./fields\";\nimport { isPropertyBuilder } from \"./entities\";\nimport { getIn, mergeDeep } from \"./objects\";\nimport { enumToObjectEntries } from \"./enums\";\nimport { DEFAULT_ONE_OF_TYPE } from \"./common\";\n\n/**\n * Resolve property builders, enums and arrays.\n */\n\nexport type ResolvePropertyProps<M extends Record<string, any> = any> = {\n property: Property\n propertyKey?: string,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthController;\n}\n\nexport function resolveProperty<M extends Record<string, any> = any>(props: ResolvePropertyProps<M>): Property | null {\n\n const {\n property,\n ignoreMissingFields = false,\n ...rest\n } = props;\n\n let resultProperty: Property;\n\n if (isPropertyBuilder(property)) {\n const path = rest.path;\n if (!path)\n throw Error(\"Trying to resolve a property builder without specifying the entity path\");\n\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicProps = property.dynamicProps?.({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n resultProperty = mergeDeep(property, dynamicProps ?? {});\n } else {\n resultProperty = property as Property;\n }\n\n // Apply dynamic properties if they exist\n if (resultProperty.dynamicProps) {\n const path = rest.path;\n if (!path)\n throw Error(\"Trying to resolve dynamicProps without specifying the entity path\");\n\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicPropsResult = resultProperty.dynamicProps({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n\n if (dynamicPropsResult) {\n resultProperty = mergeDeep(resultProperty, dynamicPropsResult);\n }\n }\n\n let resolvedProperty: Property | null;\n\n if (resultProperty?.type === \"map\" && resultProperty.properties) {\n const properties = resolveProperties({\n ignoreMissingFields,\n ...rest,\n properties: resultProperty.properties,\n });\n resolvedProperty = {\n ...resultProperty,\n properties\n } as Property;\n } else if (resultProperty?.type === \"array\") {\n resolvedProperty = resultProperty;\n } else if ((resultProperty?.type === \"string\" || resultProperty?.type === \"number\") && resultProperty.enum) {\n resolvedProperty = resolvePropertyEnum(resultProperty);\n } else {\n resolvedProperty = resultProperty;\n }\n\n if (resolvedProperty?.propertyConfig && !isDefaultFieldConfigId(resolvedProperty.propertyConfig)) {\n const cmsFields = rest.propertyConfigs;\n if (!cmsFields && !ignoreMissingFields) {\n 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`);\n }\n const customField: PropertyConfig | undefined = cmsFields?.[resolvedProperty.propertyConfig];\n if (!customField) {\n 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`)\n return resolvedProperty;\n }\n if (customField.property) {\n const { propertyConfig: _unused, ...restConfigProperty } = customField.property;\n const customFieldProperty = resolveProperty({\n property: { name: \"\", ...restConfigProperty } as Property,\n ignoreMissingFields,\n ...rest\n });\n if (customFieldProperty) {\n resolvedProperty = mergeDeep(customFieldProperty, resolvedProperty);\n }\n }\n\n }\n\n return resolvedProperty;\n}\n\nexport function resolveRelationProperty(property: RelationProperty, relations: Relation[]) {\n // find the relation by name\n const relation = relations.find((rel) => rel.relationName === property.relationName);\n if (!relation) {\n throw Error(`Relation ${property.relationName} not found`);\n }\n return {\n ...property,\n relation: relation\n } as RelationProperty;\n\n}\n\n/**\n * Resolve enum aliases for a string or number property\n * @param property\n */\nexport function resolvePropertyEnum(property: StringProperty | NumberProperty): StringProperty | NumberProperty {\n if (typeof property.enum === \"object\") {\n return {\n ...property,\n enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [],\n };\n }\n return property as StringProperty | NumberProperty;\n}\n\n/**\n * Resolve enums and arrays for properties\n * @param properties\n * @param value\n */\nexport function resolveProperties<M extends Record<string, any>>({\n propertyKey,\n properties,\n ignoreMissingFields,\n ...props\n}: {\n propertyKey?: string,\n properties: Properties,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthController;\n}): Properties {\n return Object.entries<Property>(properties as Record<string, Property>)\n .map(([key, property]) => {\n const childResolvedProperty = resolveProperty({\n propertyKey: propertyKey ? `${propertyKey}.${key}` : undefined,\n property: property,\n ignoreMissingFields,\n ...props\n });\n if (!childResolvedProperty) return {};\n return {\n [key]: childResolvedProperty\n };\n })\n .filter((a) => a !== null)\n .reduce((a, b) => ({ ...a, ...b }), {}) as Properties;\n}\n\nexport function resolveArrayProperties<M>({\n propertyKey,\n property,\n ignoreMissingFields = false,\n ...props\n}: {\n propertyKey?: string,\n property: ArrayProperty,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthController;\n}): Property[] {\n const propertyValue = propertyKey ? getIn(props.values, propertyKey) : undefined;\n\n if (property.of) {\n if (Array.isArray(property.of)) {\n return property.of.map((p, index) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: p as Property,\n ignoreMissingFields,\n ...props,\n index,\n });\n }) as Property[];\n } else {\n const of = property.of;\n const resolvedProperties = getArrayResolvedProperties({\n propertyValue,\n propertyKey,\n property,\n ignoreMissingFields,\n ...props\n });\n const {\n values,\n previousValues,\n ...rest\n } = props;\n const ofProperty = resolveProperty({ // we don't want to pass the values of the parent entity\n property: of,\n ignoreMissingFields,\n ...rest\n });\n if (!ofProperty && !ignoreMissingFields)\n throw Error(\"When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property\")\n return resolvedProperties;\n }\n } else if (property.oneOf) {\n const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;\n const resolvedProperties: Property[] = Array.isArray(propertyValue)\n ? propertyValue.map((v, index) => {\n const type = v && v[typeField];\n const childProperty = property.oneOf?.properties[type];\n if (!type || !childProperty) return null;\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: childProperty,\n ignoreMissingFields,\n ...props\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n return resolvedProperties;\n } else if (!property.Field) {\n throw Error(`The array property (${propertyKey}) needs to declare an 'of' or a 'oneOf' property, or provide a custom \\`Field\\` component`);\n } else {\n return [];\n }\n\n}\n\nexport function getArrayResolvedProperties({\n propertyKey,\n propertyValue,\n property,\n ...props\n}: {\n propertyValue: unknown,\n propertyKey?: string,\n property: ArrayProperty,\n ignoreMissingFields: boolean,\n values?: object;\n previousValues?: object;\n path?: string;\n entityId?: string | number;\n index?: number;\n propertyConfigs?: Record<string, PropertyConfig>;\n authController: AuthController;\n}) {\n\n const of = property.of;\n if (!of)\n throw Error(\n `Trying to resolve an array property (${propertyKey}) without providing an 'of' property`\n )\n return Array.isArray(propertyValue)\n ? propertyValue.map((v: unknown, index: number) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: Array.isArray(of) ? of[index] : of,\n ...props,\n index\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n}\n\nexport function resolveEnumValues(input: EnumValues): EnumValueConfig[] | undefined {\n if (typeof input === \"object\") {\n return Object.entries(input).map(([id, value]) =>\n (typeof value === \"string\"\n ? {\n id,\n label: value\n }\n : value));\n } else if (Array.isArray(input)) {\n return input as EnumValueConfig[];\n } else {\n return undefined;\n }\n}\n\nexport function resolveEntityView(entityView: string | EntityCustomView<any>, contextEntityViews?: EntityCustomView<any>[]): EntityCustomView<any> | undefined {\n if (typeof entityView === \"string\") {\n return contextEntityViews?.find((entry) => entry.key === entityView);\n } else {\n return entityView;\n }\n}\n\nexport function resolveEntityAction<M extends Record<string, any>>(\n entityAction: string | EntityAction<M>,\n contextEntityActions?: EntityAction<M>[]\n): EntityAction<M> | undefined {\n if (typeof entityAction === \"string\") {\n return contextEntityActions?.find((entry) => entry.key === entityAction);\n } else {\n return entityAction;\n }\n}\n\nexport function resolvedSelectedEntityView<M extends Record<string, any>>(\n customViews: (string | EntityCustomView<M>)[] | undefined,\n customizationController: CustomizationController,\n selectedTab?: string,\n canEdit?: boolean,\n) {\n const resolvedEntityViews = customViews ? customViews\n .map(e => resolveEntityView(e, customizationController.entityViews))\n .filter((e): e is EntityCustomView<M> => Boolean(e))\n // .filter((e) => canEdit || !e.includeActions)\n : [];\n\n const selectedEntityView = resolvedEntityViews.find(e => e.key === selectedTab);\n const selectedSecondaryForm = customViews\n && resolvedEntityViews.filter(e => e.includeActions).find(e => e.key === selectedTab);\n return {\n resolvedEntityViews,\n selectedEntityView,\n selectedSecondaryForm\n };\n}\n\nexport function getSubcollections<M extends Record<string, any> = any>(collection: EntityCollection<M>) {\n const subcollections: EntityCollection<any>[] = [];\n subcollections.push(...(collection.subcollections?.() ?? []));\n subcollections.push(...((collection.relations ?? [])\n .filter((rel) => rel.cardinality === \"many\")\n .map(relation => {\n const targetCollection = relation.target();\n const overrides = relation.overrides;\n return overrides ? mergeDeep(targetCollection, overrides) : targetCollection;\n }) ?? []));\n return subcollections;\n}\n","import { EntityCollection, CMSUrlController, SideEntityController } from \"@rebasepro/types\";\nimport { getSubcollections } from \"./resolutions\";\n\nexport function removeInitialAndTrailingSlashes(s: string): string {\n return removeInitialSlash(removeTrailingSlash(s));\n}\n\nexport function removeInitialSlash(s: string) {\n if (s.startsWith(\"/\"))\n return s.slice(1);\n else return s;\n}\n\nexport function removeTrailingSlash(s: string) {\n if (s.endsWith(\"/\"))\n return s.slice(0, -1);\n else return s;\n}\n\nexport function addInitialSlash(s: string) {\n if (s.startsWith(\"/\"))\n return s;\n else return `/${s}`;\n}\n\nexport function getLastSegment(path: string) {\n const cleanPath = removeInitialAndTrailingSlashes(path);\n if (cleanPath.includes(\"/\")) {\n const segments = cleanPath.split(\"/\");\n return segments[segments.length - 1];\n }\n return cleanPath;\n}\n\nexport function resolveCollectionPathIds(path: string, allCollections: EntityCollection[]): string {\n let remainingPath = removeInitialAndTrailingSlashes(path);\n if (!remainingPath) {\n return \"\";\n }\n\n let currentCollections: EntityCollection[] | undefined = allCollections;\n const resolvedPathParts: string[] = [];\n\n while (remainingPath.length > 0) {\n if (!currentCollections || currentCollections.length === 0) {\n // We have remaining path segments but no more collections to match against\n console.warn(`resolveCollectionPathIds: Path structure implies subcollections, but none found before segment starting with \"${remainingPath}\" in original path \"${path}\". Appending remaining original path.`);\n resolvedPathParts.push(remainingPath);\n remainingPath = \"\"; // Stop processing\n break;\n }\n\n let foundMatch = false;\n // Sort potential matches by length descending to prioritize longer matches (e.g., \"a/b\" over \"a\")\n const potentialMatches: { col: EntityCollection; match: string; }[] = currentCollections\n .flatMap(col => [{\n col,\n match: col.slug\n }])\n .filter(p => p.match && remainingPath.startsWith(p.match))\n .sort((a, b) => b.match.length - a.match.length);\n\n if (potentialMatches.length > 0) {\n const {\n col: foundCollection,\n match: matchString\n } = potentialMatches[0];\n\n resolvedPathParts.push(foundCollection.dbPath); // Use the defined path\n remainingPath = removeInitialSlash(remainingPath.substring(matchString.length));\n\n // Check if we are at the end of the path\n if (remainingPath.length === 0) {\n foundMatch = true;\n break; // Path ends with a collection segment\n }\n\n // The next segment must be an entity ID\n const idSeparatorIndex = remainingPath.indexOf(\"/\");\n let entityId: string | number;\n if (idSeparatorIndex > -1) {\n entityId = remainingPath.substring(0, idSeparatorIndex);\n remainingPath = remainingPath.substring(idSeparatorIndex + 1);\n } else {\n // This should not happen if the original path is valid (odd segments)\n // but handle it defensively: assume the rest is the ID\n entityId = remainingPath;\n remainingPath = \"\";\n 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.`);\n // Even if it ends here, we still need to push the ID\n }\n\n resolvedPathParts.push(entityId); // Append entity ID\n currentCollections = getSubcollections(foundCollection); // Move to subcollections\n foundMatch = true;\n\n if (!currentCollections && remainingPath.length > 0) {\n // Warn if the path continues but no subcollections were defined\n 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.`);\n resolvedPathParts.push(remainingPath); // Append the rest\n remainingPath = \"\"; // Stop processing\n break;\n }\n\n }\n\n if (!foundMatch) {\n // Collection definition not found for the start of the remaining path\n console.warn(`resolveCollectionPathIds: Collection definition not found for segment starting with \"${remainingPath}\" in original path \"${path}\". Appending remaining original path.`);\n resolvedPathParts.push(remainingPath); // Append the rest\n remainingPath = \"\"; // Stop processing\n break;\n }\n }\n\n return resolvedPathParts.join(\"/\");\n}\n\n/**\n * Find the corresponding view at any depth for a given path.\n * Note that path or segments of the paths can be collection aliases.\n * @param slugOrPath\n * @param collections\n */\nexport function getCollectionBySlugWithin(slugOrPath: string, collections: EntityCollection[]): EntityCollection | undefined {\n\n const subpaths = removeInitialAndTrailingSlashes(slugOrPath).split(\"/\");\n if (subpaths.length % 2 === 0) {\n throw Error(`getCollectionBySlug: Collection paths must have an odd number of segments: ${slugOrPath}`);\n }\n\n const subpathCombinations = getCollectionPathsCombinations(subpaths);\n let result: EntityCollection | undefined;\n for (let i = 0; i < subpathCombinations.length; i++) {\n const subpathCombination = subpathCombinations[i];\n const navigationEntry = collections && collections\n .sort((a, b) => (a.slug ?? \"\").localeCompare(b.slug ?? \"\"))\n .find((entry) => entry.slug === subpathCombination);\n\n if (navigationEntry) {\n\n if (subpathCombination === slugOrPath) {\n result = navigationEntry;\n } else if (navigationEntry.subcollections) {\n const newPath = slugOrPath.replace(subpathCombination, \"\").split(\"/\").slice(2).join(\"/\");\n if (newPath.length > 0)\n result = getCollectionBySlugWithin(newPath, getSubcollections(navigationEntry));\n }\n }\n if (result) break;\n }\n return result;\n}\n\n/**\n * Get the subcollection combinations from a path:\n * \"sites/es/locales\" => [\"sites/es/locales\", \"sites\"]\n * @param subpaths\n */\nexport function getCollectionPathsCombinations(subpaths: string[]): string[] {\n const entries = subpaths.length > 0 && subpaths.length % 2 === 0 ? subpaths.splice(0, subpaths.length - 1) : subpaths;\n\n const length = entries.length;\n const result: string[] = [];\n for (let i = length; i > 0; i = i - 2) {\n result.push(entries.slice(0, i).join(\"/\"));\n }\n return result;\n\n}\n\nexport function navigateToEntity({\n openEntityMode,\n collection,\n entityId,\n copy,\n path,\n selectedTab,\n sideEntityController,\n onClose,\n navigation\n}:\n\n {\n openEntityMode: \"side_panel\" | \"full_screen\";\n collection?: EntityCollection;\n entityId?: string | number;\n selectedTab?: string;\n copy?: boolean;\n path: string;\n sideEntityController: SideEntityController;\n onClose?: () => void;\n navigation: CMSUrlController\n }) {\n\n if (openEntityMode === \"side_panel\") {\n\n sideEntityController.open({\n entityId,\n path: path,\n copy,\n selectedTab,\n collection,\n updateUrl: true,\n onClose\n });\n\n } else {\n let to = navigation.buildUrlCollectionPath(entityId ? `${path ?? path}/${entityId}` : path ?? path);\n if (entityId && selectedTab) {\n to += `/${selectedTab}`;\n }\n if (!entityId) {\n to += \"#new\";\n }\n if (copy) {\n to += \"#copy\";\n }\n navigation.navigate(to);\n }\n\n}\n","import { EntityAction } from \"@rebasepro/types\";\n\nconst reservedKeys = [\"edit\", \"copy\", \"delete\"];\n\nexport function mergeEntityActions(currentActions: EntityAction[], newActions: EntityAction[]): EntityAction[] {\n // given the current actions, replace the ones with the same key\n // and append the new ones\n const updatedActions: EntityAction[] = [];\n currentActions.forEach(action => {\n const newAction = newActions.find(a => a.key === action.key);\n if (newAction) {\n const mergedAction = {\n ...action,\n ...newAction\n }\n updatedActions.push(mergedAction);\n } else {\n updatedActions.push(action);\n }\n });\n newActions.forEach(action => {\n if (!currentActions.find(a => a.key === action.key) && (!action.key || !reservedKeys.includes(action.key))) {\n updatedActions.push(action);\n }\n });\n return updatedActions;\n\n}\n","import { AuthController, Entity, EntityCollection, SecurityRule, User } from \"@rebasepro/types\";\n\nfunction evaluateAST(sqlString: string, auth: AuthController, entity: Entity<any> | null): boolean {\n // This is a client-side SQL evaluator used *only* for optimistic UI updates.\n // It parses basic AND / OR statements to evaluate RLS without backend roundtrips.\n if (!entity) return true;\n\n // 1. Clean outer parentheses\n let cleanedSQL = sqlString.trim();\n while (cleanedSQL.startsWith('(') && cleanedSQL.endsWith(')')) {\n let openCount = 0;\n let isEnclosing = true;\n for (let i = 0; i < cleanedSQL.length - 1; i++) {\n if (cleanedSQL[i] === '(') openCount++;\n else if (cleanedSQL[i] === ')') openCount--;\n if (openCount === 0) {\n isEnclosing = false;\n break;\n }\n }\n if (isEnclosing) {\n cleanedSQL = cleanedSQL.substring(1, cleanedSQL.length - 1).trim();\n } else {\n break;\n }\n }\n\n // 2. Split top-level OR / AND\n const splitByTopLevel = (str: string, delimiter: string) => {\n const parts: string[] = [];\n let current = \"\";\n let openCount = 0;\n let i = 0;\n while (i < str.length) {\n if (str[i] === '(') openCount++;\n else if (str[i] === ')') openCount--;\n \n if (openCount === 0 && str.substring(i).toUpperCase().startsWith(delimiter)) {\n parts.push(current);\n current = \"\";\n i += delimiter.length;\n } else {\n current += str[i];\n i++;\n }\n }\n parts.push(current);\n return parts;\n };\n\n const orParts = splitByTopLevel(cleanedSQL, \" OR \");\n if (orParts.length > 1) {\n return orParts.some(part => evaluateAST(part, auth, entity));\n }\n\n const andParts = splitByTopLevel(cleanedSQL, \" AND \");\n if (andParts.length > 1) {\n return andParts.every(part => evaluateAST(part, auth, entity));\n }\n\n const upperSQL = cleanedSQL.toUpperCase();\n\n // 3. Fallback for unparseable complex queries\n if (upperSQL.includes(\" IN \") || upperSQL.includes(\" EXISTS \")) {\n return true;\n }\n\n // 4. Role array checks\n // Pattern: `string_to_array(auth.roles(), ',') && ARRAY['admin', 'editor']`\n const roleIntersectMatch = cleanedSQL.match(/string_to_array\\s*\\(\\s*auth\\.roles\\(\\)\\s*,\\s*','\\s*\\)\\s*&&\\s*ARRAY\\[(.*?)\\]/i);\n if (roleIntersectMatch && roleIntersectMatch[1]) {\n const requiredRoles = roleIntersectMatch[1].split(',').map(r => r.trim().replace(/'/g, ''));\n const userRoles = auth.user?.roles || [];\n return requiredRoles.some(r => userRoles.includes(r));\n }\n\n // Pattern: `string_to_array(auth.roles(), ',') @> ARRAY['admin']`\n const roleContainMatch = cleanedSQL.match(/string_to_array\\s*\\(\\s*auth\\.roles\\(\\)\\s*,\\s*','\\s*\\)\\s*@>\\s*ARRAY\\[(.*?)\\]/i);\n if (roleContainMatch && roleContainMatch[1]) {\n const requiredRoles = roleContainMatch[1].split(',').map(r => r.trim().replace(/'/g, ''));\n const userRoles = auth.user?.roles || [];\n return requiredRoles.every(r => userRoles.includes(r));\n }\n\n // 5. Existing ID patterns\n const pattern1 = new RegExp(`^\\\\{?([a-zA-Z0-9_]+)\\\\}?\\\\s*=\\\\s*(?:current_setting\\\\s*\\\\(\\\\s*'app\\\\.user_id'\\\\s*\\\\)|auth\\\\.uid\\\\(\\\\))`);\n const pattern2 = new RegExp(`^(?:current_setting\\\\s*\\\\(\\\\s*'app\\\\.user_id'\\\\s*\\\\)|auth\\\\.uid\\\\(\\\\))\\\\s*=\\\\s*\\\\{?([a-zA-Z0-9_]+)\\\\}?`);\n\n const match1 = cleanedSQL.match(pattern1);\n if (match1 && match1[1]) {\n return entity.values[match1[1]] === auth.user?.uid;\n }\n\n const match2 = cleanedSQL.match(pattern2);\n if (match2 && match2[1]) {\n return entity.values[match2[1]] === auth.user?.uid;\n }\n\n // 6. Simple equality\n // Pattern: `field = 'value'` or `{field} != 'value'`\n const simpleEqualityMatch = cleanedSQL.match(/^\\{?([\\w_]+)\\}?\\s*(=|!=)\\s*'([^']+)'$/i);\n if (simpleEqualityMatch) {\n const field = simpleEqualityMatch[1];\n const operator = simpleEqualityMatch[2];\n const value = simpleEqualityMatch[3];\n const entityValue = entity.values[field];\n if (operator === \"=\") return entityValue === value;\n if (operator === \"!=\") return entityValue !== value;\n }\n\n return true; // Optimistic fallback for anything else\n}\n\nfunction evaluateRule(rule: SecurityRule, auth: AuthController, entity: Entity<any> | null): boolean {\n\n if (rule.access === \"public\") return true;\n\n if (rule.ownerField) {\n if (!entity) {\n // null entity: optimistic — we can't evaluate ownership without data\n // Fall through to SQL checks below (if any). If none, will return true.\n } else {\n // Entity present: strictly check ownership. Fail immediately if mismatch.\n if (entity.values[rule.ownerField] !== auth.user?.uid) return false;\n }\n }\n\n // In PostgreSQL RLS, USING and WITH CHECK have distinct semantics:\n // USING applies to existing rows (SELECT/UPDATE/DELETE read phase)\n // WITH CHECK applies to new/modified values (INSERT/UPDATE write phase)\n // Both must pass. We evaluate both independently.\n if (rule.using && !evaluateAST(rule.using, auth, entity)) return false;\n if (rule.withCheck && !evaluateAST(rule.withCheck, auth, entity)) return false;\n\n return true;\n}\n\nfunction checkOperation(\n collection: EntityCollection<any>,\n authController: AuthController<any>,\n entity: Entity<any> | null,\n targetOperation: \"select\" | \"insert\" | \"update\" | \"delete\"\n): boolean {\n if (!collection.securityRules || collection.securityRules.length === 0) {\n // According to our plan: Postgres RLS implicitly denies if enabled without rules.\n // But for Rebase we default to true if securityRules is undefined,\n // so as not to break everything without rules. Let's assume true for now.\n return true;\n }\n\n const applicableRules = collection.securityRules.filter(r =>\n r.operation === targetOperation ||\n r.operation === \"all\" ||\n r.operations?.includes(targetOperation) ||\n r.operations?.includes(\"all\")\n );\n\n if (applicableRules.length === 0) return false;\n\n // In Postgres, policies ONLY apply if the user matching the targeted roles.\n const userRoleIds = authController.user?.roles ?? [];\n const userRoles = [...userRoleIds, \"public\"];\n const roleApplicableRules = applicableRules.filter(rule => {\n if (!rule.roles || rule.roles.length === 0) return true; // APPLIES TO PUBLIC\n return rule.roles.some((r: string) => userRoles.includes(r));\n });\n\n // If no rules apply to this user's roles, the operation is implicitly denied.\n if (roleApplicableRules.length === 0) return false;\n\n let grantedByPermissive = false;\n let deniedByRestrictive = false;\n\n for (const rule of roleApplicableRules) {\n const mode = rule.mode || \"permissive\";\n const passed = evaluateRule(rule, authController, entity);\n\n if (mode === \"restrictive\" && !passed) {\n deniedByRestrictive = true;\n break; // Immediate deny\n }\n\n if (mode === \"permissive\" && passed) {\n grantedByPermissive = true;\n }\n }\n\n if (deniedByRestrictive) return false;\n\n const hasPermissive = roleApplicableRules.some(r => (r.mode || \"permissive\") === \"permissive\");\n if (hasPermissive) {\n return grantedByPermissive;\n } else {\n return false;\n }\n}\n\nexport function canReadCollection<M extends Record<string, any>, USER extends User>\n (\n collection: EntityCollection<M>,\n authController: AuthController<USER>\n ): boolean {\n return checkOperation(collection, authController, null, \"select\");\n}\n\nexport function canEditEntity<M extends Record<string, any>, USER extends User>\n (\n collection: EntityCollection<M>,\n authController: AuthController<USER>,\n path: string,\n entity: Entity<M> | null\n ): boolean {\n return checkOperation(collection, authController, entity, \"update\");\n}\n\nexport function canCreateEntity<M extends Record<string, any>, USER extends User>\n (\n collection: EntityCollection<M>,\n authController: AuthController<USER>,\n path: string,\n entity: Entity<M> | null\n ): boolean {\n if (collection.collectionGroup) return false;\n return checkOperation(collection, authController, entity, \"insert\");\n}\n\nexport function canDeleteEntity<M extends Record<string, any>, USER extends User>\n (\n collection: EntityCollection<M>,\n authController: AuthController<USER>,\n path: string,\n entity: Entity<M> | null\n ): boolean {\n return checkOperation(collection, authController, entity, \"delete\");\n}\n","/**\n * Returns the plural of an English word.\n *\n * @param {string} word\n * @param {number} [amount]\n * @returns {string}\n */\nexport function plural(word: string, amount?: number): string {\n if (amount !== undefined && amount === 1) {\n return word\n }\n const plurals: { [key: string]: string } = {\n \"(quiz)$\": \"$1zes\",\n \"^(ox)$\": \"$1en\",\n \"([m|l])ouse$\": \"$1ice\",\n \"(matr|vert|ind)ix|ex$\": \"$1ices\",\n \"(x|ch|ss|sh)$\": \"$1es\",\n \"([^aeiouy]|qu)y$\": \"$1ies\",\n \"(hive)$\": \"$1s\",\n \"(?:([^f])fe|([lr])f)$\": \"$1$2ves\",\n \"(shea|lea|loa|thie)f$\": \"$1ves\",\n sis$: \"ses\",\n \"([ti])um$\": \"$1a\",\n \"(tomat|potat|ech|her|vet)o$\": \"$1oes\",\n \"(bu)s$\": \"$1ses\",\n \"(alias)$\": \"$1es\",\n \"(octop)us$\": \"$1i\",\n \"(ax|test)is$\": \"$1es\",\n \"(us)$\": \"$1es\",\n \"([^s]+)$\": \"$1s\"\n }\n const irregular: { [key: string]: string } = {\n move: \"moves\",\n foot: \"feet\",\n goose: \"geese\",\n sex: \"sexes\",\n child: \"children\",\n man: \"men\",\n tooth: \"teeth\",\n person: \"people\"\n }\n const uncountable: string[] = [\n \"sheep\",\n \"fish\",\n \"deer\",\n \"moose\",\n \"series\",\n \"species\",\n \"money\",\n \"rice\",\n \"information\",\n \"equipment\",\n \"bison\",\n \"cod\",\n \"offspring\",\n \"pike\",\n \"salmon\",\n \"shrimp\",\n \"swine\",\n \"trout\",\n \"aircraft\",\n \"hovercraft\",\n \"spacecraft\",\n \"sugar\",\n \"tuna\",\n \"you\",\n \"wood\"\n ]\n // save some time in the case that singular and plural are the same\n if (uncountable.indexOf(word.toLowerCase()) >= 0) {\n return word;\n }\n // check for irregular forms\n for (const w in irregular) {\n const pattern = new RegExp(`${w}$`, \"i\")\n const replace = irregular[w]\n if (pattern.test(word)) {\n return word.replace(pattern, replace);\n }\n }\n // check for matches using regular expressions\n for (const reg in plurals) {\n const pattern = new RegExp(reg, \"i\")\n if (pattern.test(word)) {\n return word.replace(pattern, plurals[reg])\n }\n }\n return word;\n}\n\n/**\n * Returns the singular of an English word.\n *\n * @param {string} word\n * @param {number} [amount]\n * @returns {string}\n */\nexport function singular(word: string, amount?: number): string {\n if (amount !== undefined && amount !== 1) {\n return word;\n }\n const singulars: { [key: string]: string } = {\n \"(quiz)zes$\": \"$1\",\n \"(matr)ices$\": \"$1ix\",\n \"(vert|ind)ices$\": \"$1ex\",\n \"^(ox)en$\": \"$1\",\n \"(alias)es$\": \"$1\",\n \"(octop|vir)i$\": \"$1us\",\n \"(cris|ax|test)es$\": \"$1is\",\n \"(shoe)s$\": \"$1\",\n \"(o)es$\": \"$1\",\n \"(bus)es$\": \"$1\",\n \"([m|l])ice$\": \"$1ouse\",\n \"(x|ch|ss|sh)es$\": \"$1\",\n \"(m)ovies$\": \"$1ovie\",\n \"(s)eries$\": \"$1eries\",\n \"([^aeiouy]|qu)ies$\": \"$1y\",\n \"([lr])ves$\": \"$1f\",\n \"(tive)s$\": \"$1\",\n \"(hive)s$\": \"$1\",\n \"(li|wi|kni)ves$\": \"$1fe\",\n \"(shea|loa|lea|thie)ves$\": \"$1f\",\n \"(^analy)ses$\": \"$1sis\",\n \"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$\": \"$1$2sis\",\n \"([ti])a$\": \"$1um\",\n \"(n)ews$\": \"$1ews\",\n \"(h|bl)ouses$\": \"$1ouse\",\n \"(corpse)s$\": \"$1\",\n \"(us)es$\": \"$1\",\n s$: \"\"\n }\n const irregular: { [key: string]: string } = {\n move: \"moves\",\n foot: \"feet\",\n goose: \"geese\",\n sex: \"sexes\",\n child: \"children\",\n man: \"men\",\n tooth: \"teeth\",\n person: \"people\"\n }\n const uncountable: string[] = [\n \"sheep\",\n \"fish\",\n \"deer\",\n \"moose\",\n \"series\",\n \"species\",\n \"money\",\n \"rice\",\n \"information\",\n \"equipment\",\n \"bison\",\n \"cod\",\n \"offspring\",\n \"pike\",\n \"salmon\",\n \"shrimp\",\n \"swine\",\n \"trout\",\n \"aircraft\",\n \"hovercraft\",\n \"spacecraft\",\n \"sugar\",\n \"tuna\",\n \"you\",\n \"wood\"\n ]\n // save some time in the case that singular and plural are the same\n if (uncountable.indexOf(word.toLowerCase()) >= 0) {\n return word;\n }\n // check for irregular forms\n for (const w in irregular) {\n const pattern = new RegExp(`${irregular[w]}$`, \"i\");\n if (pattern.test(word)) {\n return word.replace(pattern, w);\n }\n }\n // check for matches using regular expressions\n for (const reg in singulars) {\n const pattern = new RegExp(reg, \"i\");\n if (pattern.test(word)) {\n return word.replace(pattern, singulars[reg]);\n }\n }\n return word;\n}\n","import { EntityCollection } from \"@rebasepro/types\";\n\nexport function getEntityImagePreviewPropertyKey<M extends object>(collection: EntityCollection<M>): string | undefined {\n\n // find first storage property of type image\n for (const key in collection.properties) {\n const property = collection.properties[key];\n if (property.type === \"string\" && property.storage?.acceptedFiles?.includes(\"image/*\")) {\n return key;\n }\n }\n // alternatively, look for the first array of images\n for (const key in collection.properties) {\n const property = collection.properties[key];\n if (property.type === \"array\" && !Array.isArray(property.of) && property.of?.type === \"string\" && property.of.storage?.acceptedFiles?.includes(\"image/*\")) {\n return key;\n }\n }\n // also check for URL properties with image preview type\n for (const key in collection.properties) {\n const property = collection.properties[key];\n if (property.type === \"string\" && property.url === \"image\") {\n return key;\n }\n }\n // and arrays of URL properties with image preview type\n for (const key in collection.properties) {\n const property = collection.properties[key];\n if (property.type === \"array\" && property.of?.type === \"string\" && property.of.url === \"image\") {\n return key;\n }\n }\n return undefined;\n}\n","export function flattenObject(obj: Record<string, unknown>, parentKey = \"\") {\n if (!obj) return obj;\n return Object.keys(obj).reduce((flatObj, key) => {\n const newKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (typeof obj[key] === \"object\" && obj[key] !== null) {\n if (Array.isArray(obj[key])) {\n obj[key].forEach((item: unknown, index: number) => {\n Object.assign(flatObj, flattenObject(item as Record<string, unknown>, `${newKey}[${index}]`));\n });\n } else {\n Object.assign(flatObj, flattenObject(obj[key] as Record<string, unknown>, newKey));\n }\n } else {\n flatObj[newKey] = obj[key];\n }\n\n return flatObj;\n }, {} as { [key: string]: unknown });\n}\n\n\n// map from nested property key like \"a.b.c\" to the maximum array count found in a list of objects for that array\nexport type ArrayValuesCount = Record<string, number>;\n\nexport function getArrayValuesCount(array: Record<string, unknown>[]): ArrayValuesCount {\n return array.reduce((acc: ArrayValuesCount, obj: Record<string, unknown>) => {\n Object.entries(obj).forEach(([key, value]) => {\n // proceed only if value is an array\n if (Array.isArray(value)) {\n acc[key] = Math.max(acc[key] || 0, value.length);\n }\n\n // handle nested object\n if (typeof value === \"object\" && value !== null) {\n const nested = getArrayValuesCount([value as Record<string, unknown>]);\n Object.entries(nested).forEach(([nestedKey, nestedCount]) => {\n const compoundKey = `${key}.${nestedKey}`;\n acc[compoundKey] = Math.max(acc[compoundKey] || 0, nestedCount);\n });\n }\n });\n return acc;\n }, {});\n}\n","import { EntityCollection, EntityCustomView } from \"@rebasepro/types\";\nimport { getCollectionPathsCombinations, removeInitialAndTrailingSlashes } from \"./navigation_utils\";\nimport { getSubcollections } from \"./resolutions\";\n\nexport type NavigationViewInternal<M extends Record<string, any> = any> =\n | NavigationViewEntityInternal<M>\n | NavigationViewCollectionInternal<M>\n | NavigationViewEntityCustomInternal<M>;\n\nexport interface NavigationViewEntityInternal<M extends Record<string, any>> {\n type: \"entity\";\n entityId: string | number;\n slug: string;\n path: string;\n parentCollection: EntityCollection<M>;\n}\n\nexport interface NavigationViewCollectionInternal<M extends Record<string, any>> {\n type: \"collection\";\n id: string;\n slug: string;\n path: string;\n collection: EntityCollection<M>;\n}\n\nexport interface NavigationViewEntityCustomInternal<M extends Record<string, any>> {\n type: \"custom_view\";\n slug: string;\n path: string;\n entityId: string | number;\n view: EntityCustomView<M>;\n}\n\nexport function getNavigationEntriesFromPath(props: {\n path: string,\n collections: EntityCollection[] | undefined,\n currentFullPath?: string,\n contextEntityViews?: EntityCustomView[]\n}): NavigationViewInternal[] {\n\n const {\n path,\n collections = [],\n currentFullPath,\n } = props;\n\n const subpaths = removeInitialAndTrailingSlashes(path).split(\"/\");\n const subpathCombinations = getCollectionPathsCombinations(subpaths);\n\n const result: NavigationViewInternal[] = [];\n for (let i = 0; i < subpathCombinations.length; i++) {\n const subpathCombination = subpathCombinations[i];\n\n const collection = collections && collections.find((entry) => entry.slug === subpathCombination);\n\n if (collection) {\n const collectionPath = currentFullPath && currentFullPath.length > 0\n ? (currentFullPath + \"/\" + collection.slug)\n : collection.slug;\n result.push({\n type: \"collection\",\n id: collection.slug,\n slug: collectionPath,\n path: collectionPath,\n collection\n });\n const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, \"\"));\n const nextSegments = restOfThePath.length > 0 ? restOfThePath.split(\"/\") : [];\n if (nextSegments.length > 0) {\n const entityId = nextSegments[0];\n const path = collectionPath + \"/\" + entityId;\n result.push({\n type: \"entity\",\n entityId,\n slug: collectionPath,\n path,\n parentCollection: collection\n });\n if (nextSegments.length > 1) {\n const newPath = nextSegments.slice(1).join(\"/\");\n if (!collection) {\n throw Error(\"collection not found resolving path: \" + collection);\n }\n const entityViews = collection.entityViews;\n const customView = entityViews && entityViews\n .map((entry) => resolveEntityView(entry, props.contextEntityViews))\n .filter(Boolean)\n .find((entry) => entry!.key === newPath);\n const subcollections = getSubcollections(collection);\n if (customView) {\n result.push({\n type: \"custom_view\",\n slug: collectionPath,\n entityId: entityId,\n path: path + \"/\" + customView.key,\n view: customView\n });\n } else if (subcollections) {\n result.push(...getNavigationEntriesFromPath({\n path: newPath,\n collections: subcollections,\n currentFullPath: path,\n contextEntityViews: props.contextEntityViews\n }));\n }\n }\n }\n break;\n }\n\n }\n return result;\n}\n\nfunction resolveEntityView(entityView: string | EntityCustomView, contextEntityViews?: EntityCustomView[]): EntityCustomView | undefined {\n if (typeof entityView === \"string\") {\n return contextEntityViews?.find((entry) => entry.key === entityView);\n } else {\n return entityView;\n }\n}\n","import { EntityCollection, EntityReference } from \"@rebasepro/types\";\nimport { getCollectionPathsCombinations, removeInitialAndTrailingSlashes } from \"./navigation_utils\";\nimport { getSubcollections } from \"./resolutions\";\n\nexport function getParentReferencesFromPath(props: {\n path: string,\n collections: EntityCollection[] | undefined,\n currentFullPath?: string,\n}): EntityReference[] {\n\n const {\n path,\n collections = [],\n currentFullPath,\n } = props;\n\n const subpaths = removeInitialAndTrailingSlashes(path).split(\"/\");\n const subpathCombinations = getCollectionPathsCombinations(subpaths);\n\n const result: EntityReference[] = [];\n for (let i = 0; i < subpathCombinations.length; i++) {\n const subpathCombination = subpathCombinations[i];\n\n const collection: EntityCollection | undefined = collections && collections.find((entry) => entry.slug === subpathCombination);\n\n // If we find a collection, we add the reference and continue\n if (collection) {\n const collectionPath = currentFullPath && currentFullPath.length > 0\n ? (currentFullPath + \"/\" + collection.slug) // Use the current full path if provided\n : collection.slug;\n\n const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, \"\"));\n const nextSegments = restOfThePath.length > 0 ? restOfThePath.split(\"/\") : [];\n if (nextSegments.length > 0) {\n const entityId = nextSegments[0];\n const path = collectionPath + \"/\" + entityId;\n result.push(new EntityReference({ id: entityId, path: collectionPath }));\n if (nextSegments.length > 1) {\n const newPath = nextSegments.slice(1).join(\"/\");\n if (!collection) {\n throw Error(\"collection not found resolving path: \" + collection);\n }\n if (collection.subcollections) {\n result.push(...getParentReferencesFromPath({\n path: newPath,\n collections: getSubcollections(collection),\n currentFullPath: path\n }));\n }\n }\n }\n break;\n }\n\n }\n return result;\n}\n","import {\n AdditionalFieldDelegate,\n ArrayProperty,\n BooleanProperty,\n DateProperty,\n EntityCallbacks,\n EntityCollection,\n EnumValueConfig,\n EnumValues,\n GeopointProperty,\n MapProperty,\n NumberProperty, Properties,\n Property,\n PropertyConfig,\n ReferenceProperty,\n StringProperty,\n User\n} from \"@rebasepro/types\";\n\n/**\n * Identity function we use to defeat the type system of Typescript and build\n * collection views with all its properties\n * @param collection\n * @group Builder\n */\nexport function buildCollection<\n M extends Record<string, any> = any,\n USER extends User = User>\n (\n collection: EntityCollection<M, USER>\n ): EntityCollection<M, USER> {\n return collection;\n}\n\n/**\n * Identity function we use to defeat the type system of Typescript and preserve\n * the property keys.\n * @param property\n * @group Builder\n */\nexport function buildProperty<T, P extends Property = Property>(\n property: P\n):\n P extends StringProperty ? StringProperty :\n P extends NumberProperty ? NumberProperty :\n P extends BooleanProperty ? BooleanProperty :\n P extends DateProperty ? DateProperty :\n P extends GeopointProperty ? GeopointProperty :\n P extends ReferenceProperty ? ReferenceProperty :\n P extends ArrayProperty ? ArrayProperty :\n P extends MapProperty ? MapProperty : never {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return property as any;\n}\n\n/**\n * Identity function we use to defeat the type system of Typescript and preserve\n * the properties keys.\n * @param properties\n * @group Builder\n */\nexport function buildProperties<M extends Record<string, any>>(\n properties: Properties\n): Properties {\n return properties;\n}\n\n/**\n * Identity function we use to defeat the type system of Typescript and preserve\n * the properties keys.\n * @param propertiesOrBuilder\n * @group Builder\n */\nexport function buildPropertiesOrBuilder<M extends Record<string, any>>(\n propertiesOrBuilder: Properties\n): Properties {\n return propertiesOrBuilder;\n}\n\n/**\n * Identity function we use to defeat the type system of Typescript and preserve\n * the properties keys.\n * @param enumValues\n * @group Builder\n */\nexport function buildEnum(\n enumValues: EnumValues\n): EnumValues {\n return enumValues;\n}\n\n/**\n * Identity function we use to defeat the type system of Typescript and preserve\n * the properties keys.\n * @param enumValueConfig\n * @group Builder\n */\nexport function buildEnumValueConfig(\n enumValueConfig: EnumValueConfig\n): EnumValueConfig {\n return enumValueConfig;\n}\n\n/**\n * Identity function we use to defeat the type system of Typescript and preserve\n * the properties keys.\n * @param callbacks\n * @group Builder\n */\nexport function buildEntityCallbacks<M extends Record<string, any> = any>(\n callbacks: EntityCallbacks<M>\n): EntityCallbacks<M> {\n return callbacks;\n}\n\n/**\n * Identity function we use to defeat the type system of Typescript and build\n * additional field delegates views with all its properties\n * @param additionalFieldDelegate\n * @group Builder\n */\nexport function buildAdditionalFieldDelegate<M extends Record<string, any>, USER extends User = User>(\n additionalFieldDelegate: AdditionalFieldDelegate<M, USER>\n): AdditionalFieldDelegate<M, USER> {\n return additionalFieldDelegate;\n}\n\n/**\n * Identity function we use to defeat the type system of Typescript and build\n * additional field delegates views with all its properties\n * @param propertyConfig\n * @group Builder\n */\nexport function buildFieldConfig(\n propertyConfig: PropertyConfig\n): PropertyConfig {\n return propertyConfig;\n}\n","import { ArrayProperty, EntityValues, StorageConfig, StringProperty, UploadedFileContext } from \"@rebasepro/types\";\nimport { randomString } from \"./strings\";\n\ninterface ResolveFilenameStringParams<M extends object> {\n input: string | ((context: UploadedFileContext) => (Promise<string> | string));\n storage: StorageConfig;\n values: EntityValues<M>;\n entityId?: string | number;\n path?: string;\n property: StringProperty | ArrayProperty,\n file: File;\n propertyKey: string;\n}\n\nexport async function resolveStorageFilenameString<M extends object>(\n {\n input,\n storage,\n values,\n entityId,\n path,\n property,\n file,\n propertyKey\n }: ResolveFilenameStringParams<M>): Promise<string> {\n let result;\n\n if (typeof input === \"function\") {\n result = await input({\n path,\n entityId,\n values,\n property,\n file,\n storage,\n propertyKey\n });\n if (!result)\n console.warn(\"Storage callback returned empty result. Using default name value\")\n } else {\n result = replacePlaceholders({\n file,\n input,\n entityId,\n propertyKey,\n path\n });\n }\n\n if (!result)\n result = randomString() + \"_\" + file.name;\n\n return result;\n}\n\ninterface ResolveStoragePathStringParams<M extends object> {\n input: string | ((context: UploadedFileContext) => string);\n storage: StorageConfig;\n values: EntityValues<M>;\n entityId?: string | number;\n path?: string;\n property: StringProperty | ArrayProperty;\n file: File;\n propertyKey: string;\n}\n\nexport function resolveStoragePathString<M extends object>(\n {\n input,\n storage,\n values,\n entityId,\n path,\n property,\n file,\n propertyKey\n }: ResolveStoragePathStringParams<M>): string {\n let result;\n if (typeof input === \"function\") {\n result = input({\n path,\n entityId,\n values,\n property,\n file,\n storage,\n propertyKey\n });\n if (!result)\n console.warn(\"Storage callback returned empty result. Using default name value\")\n } else {\n result = replacePlaceholders({\n file,\n input,\n entityId,\n propertyKey,\n path\n });\n }\n\n if (!result)\n result = randomString() + \"_\" + file.name;\n\n return result;\n}\n\ninterface Placeholders {\n file: File;\n input: string;\n entityId?: string | number;\n propertyKey: string;\n path?: string;\n}\n\nfunction replacePlaceholders({\n file,\n input,\n entityId,\n propertyKey,\n path\n}: Placeholders) {\n const ext = file.name.split(\".\").pop();\n let result = input\n .replace(\"{propertyKey}\", propertyKey)\n .replace(\"{rand}\", randomString())\n .replace(\"{file}\", file.name)\n .replace(\"{file.type}\", file.type);\n if (entityId) {\n result = result.replace(\"{entityId}\", String(entityId));\n }\n if (path) {\n result = result.replace(\"{path}\", path);\n }\n if (ext) {\n result = result.replace(\"{file.ext}\", ext);\n const name = file.name.replace(`.${ext}`, \"\");\n result = result.replace(\"{file.name}\", name)\n }\n\n if (!result)\n result = randomString() + \"_\" + file.name;\n\n return result;\n}\n","export function toArray<T>(input?: T | T[]): T[] {\n return Array.isArray(input) ? input : (input ? [input] : []);\n}\n","import { EntityCallbacks, Properties } from \"@rebasepro/types\";\nimport { mergeDeep } from \"./objects\";\n\n/**\n * Helper function to recursively check if there are any callbacks in the properties.\n */\nfunction hasPropertyCallbacks(properties: Properties, callbackName: \"afterRead\" | \"beforeSave\"): boolean {\n if (!properties) return false;\n for (const property of Object.values(properties)) {\n if (property.callbacks?.[callbackName]) return true;\n if (property.type === \"map\" && property.properties) {\n if (hasPropertyCallbacks(property.properties, callbackName)) return true;\n } else if (property.type === \"array\" && property.of) {\n const ofs = Array.isArray(property.of) ? property.of : [property.of];\n for (const of of ofs) {\n if (of.callbacks?.[callbackName]) return true;\n if (of.type === \"map\" && of.properties && hasPropertyCallbacks(of.properties, callbackName)) return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Recursively process properties to apply field-level hooks.\n */\nasync function processProperties(\n properties: Properties,\n values: Record<string, unknown>,\n previousValues: Record<string, unknown>,\n propsContext: unknown,\n callbackName: \"afterRead\" | \"beforeSave\"\n): Promise<Record<string, unknown>> {\n if (!values || typeof values !== \"object\") return values;\n\n let result = { ...values };\n\n for (const [key, property] of Object.entries(properties)) {\n if (result[key] === undefined) continue;\n\n let currentValue = result[key];\n let previousValue = previousValues?.[key];\n\n // 1. Array Property\n if (property.type === \"array\" && Array.isArray(currentValue)) {\n // We only support traversing single-type arrays for hooks currently to avoid complex union matching\n if (property.of && !Array.isArray(property.of)) {\n currentValue = await Promise.all(currentValue.map(async (item, index) => {\n const prevItem = Array.isArray(previousValue) ? previousValue[index] : undefined;\n // Mock a properties object to process a single item\n const singlePropData = { \"_tmp\": property.of } as Properties;\n const res = await processProperties(singlePropData, { \"_tmp\": item }, { \"_tmp\": prevItem }, propsContext, callbackName);\n return res[\"_tmp\"];\n }));\n }\n }\n // 2. Map Property\n else if (property.type === \"map\" && property.properties && typeof currentValue === \"object\") {\n currentValue = await processProperties(property.properties, currentValue as Record<string, unknown>, (previousValue ?? {}) as Record<string, unknown>, propsContext, callbackName);\n }\n\n // 3. Property's own callback\n if (property.callbacks?.[callbackName]) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const cbRes = await Promise.resolve(property.callbacks[callbackName]({\n ...(propsContext as Record<string, unknown>),\n value: currentValue,\n previousValue\n } as any));\n if (cbRes !== undefined) {\n currentValue = cbRes;\n }\n }\n\n result[key] = currentValue;\n }\n return result;\n}\n\n/**\n * Helper function to extract field-level PropertyCallbacks from a properties schema\n * and wrap them into an EntityCallbacks object recursively.\n */\nexport const buildPropertyCallbacks = (properties: Properties): EntityCallbacks | undefined => {\n if (!properties) return undefined;\n\n const propertyCallbacks: EntityCallbacks = {};\n\n if (hasPropertyCallbacks(properties, \"afterRead\")) {\n propertyCallbacks.afterRead = async (props) => {\n const processedValues = await processProperties(\n properties,\n props.entity.values as Record<string, unknown>,\n props.entity.values as Record<string, unknown>,\n props as unknown,\n \"afterRead\"\n );\n return { ...props.entity, values: processedValues };\n };\n }\n\n if (hasPropertyCallbacks(properties, \"beforeSave\")) {\n propertyCallbacks.beforeSave = async (props) => {\n return await processProperties(\n properties,\n props.values as Record<string, unknown>,\n (props.previousValues ?? {}) as Record<string, unknown>,\n props as unknown,\n \"beforeSave\"\n );\n };\n }\n\n return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : undefined;\n};\n","export function hashString(str: string): number {\n let hash = 0;\n let i;\n let chr;\n for (i = 0; i < str.length; i++) {\n chr = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n return Math.abs(hash);\n}\n","import { toSnakeCase } from \"./strings\";\n\n/**\n * Generates a foreign key column name from a given string, typically a collection slug or name.\n * It converts the name to snake_case, attempts to singularize it by removing a trailing 's'\n * (a common convention for collection names), and appends '_id'.\n *\n * @param name The base name to convert to a foreign key.\n * @returns A foreign key name in the format 'singular_name_id'.\n *\n * @example\n * // returns \"user_id\"\n * generateForeignKeyName(\"users\")\n *\n * @example\n * // returns \"post_id\"\n * generateForeignKeyName(\"posts\")\n *\n * @example\n * // returns \"product_id\"\n * generateForeignKeyName(\"Product\")\n *\n */\nexport function generateForeignKeyName(name: string): string {\n const snakeCaseName = toSnakeCase(name);\n // A simple heuristic to singularize a plural name, which is a common convention.\n const singularName = snakeCaseName.endsWith(\"s\") ? snakeCaseName.slice(0, -1) : snakeCaseName;\n return `${singularName}_id`;\n}\n\n","import { EntityCollection, Property, Relation } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"./strings\";\nimport { generateForeignKeyName } from \"./names\";\n\nexport function sanitizeRelation(relation: Partial<Relation>, sourceCollection: EntityCollection): Relation {\n if (!relation.target) {\n throw new Error(\"Relation is missing a `target` collection.\");\n }\n const targetCollection = relation.target();\n\n const newRelation: Partial<Relation> = { ...relation };\n\n // 1. Default relationName from target collection slug or dbPath\n if (!newRelation.relationName) {\n newRelation.relationName = toSnakeCase(targetCollection.slug ?? targetCollection.dbPath);\n }\n\n // 2. Infer or default direction if absent\n if (!newRelation.direction) {\n if (newRelation.foreignKeyOnTarget) newRelation.direction = \"inverse\";\n else if (newRelation.through) newRelation.direction = \"owning\";\n else if (newRelation.cardinality === \"many\") newRelation.direction = \"inverse\"; // Default has-many to be inverse\n else newRelation.direction = \"owning\"; // Default all others to owning\n }\n\n // Do not default keys if a custom joinPath is provided; it's an advanced override.\n if (!newRelation.joinPath) {\n const sourceName = toSnakeCase(sourceCollection.slug ?? sourceCollection.name);\n\n // 3. Default keys based on the relation type (cardinality and direction)\n if (newRelation.cardinality === \"one\" && newRelation.direction === \"owning\") {\n // Belongs-to / many-to-one\n if (!newRelation.localKey) {\n newRelation.localKey = generateForeignKeyName(newRelation.relationName);\n }\n } else if (newRelation.cardinality === \"one\" && newRelation.direction === \"inverse\") {\n // Inverse one-to-one: the foreign key is on the target table pointing back to this collection\n if (!newRelation.foreignKeyOnTarget) {\n // First, try to find the corresponding owning relation's localKey on the target collection\n let foundForeignKey = false;\n\n try {\n // Look for an owning relation on the target that points back to this collection\n const targetRelations = targetCollection.relations || [];\n for (const targetRel of targetRelations) {\n if (targetRel.direction === \"owning\" &&\n targetRel.cardinality === \"one\" &&\n targetRel.localKey) {\n try {\n const targetRelTarget = targetRel.target();\n if (targetRelTarget.slug === sourceCollection.slug ||\n targetRelTarget.dbPath === sourceCollection.dbPath) {\n // Found the corresponding owning relation, use its localKey\n newRelation.foreignKeyOnTarget = targetRel.localKey;\n foundForeignKey = true;\n break;\n }\n } catch (e) {\n // Continue looking if we can't resolve this target\n continue;\n }\n }\n }\n } catch (e) {\n // If we can't inspect the target collection, fall back to naming convention\n }\n\n // If we couldn't find an explicit foreign key, fall back to naming convention\n if (!foundForeignKey) {\n const keyPrefix = newRelation.inverseRelationName\n ? toSnakeCase(newRelation.inverseRelationName)\n : sourceName;\n newRelation.foreignKeyOnTarget = generateForeignKeyName(keyPrefix);\n }\n }\n } else if (newRelation.cardinality === \"many\" && newRelation.direction === \"inverse\") {\n // This could be either one-to-many or many-to-many inverse relation\n // We need to check if there's a corresponding owning many-to-many relation\n\n let isManyToManyInverse = false;\n\n // Try to determine if this is a many-to-many inverse relation\n if (newRelation.inverseRelationName && !newRelation.foreignKeyOnTarget) {\n try {\n // Look for a corresponding owning many-to-many relation on the target collection\n const targetRelations = targetCollection.relations || [];\n for (const targetRel of targetRelations) {\n if (targetRel.cardinality === \"many\" &&\n targetRel.direction === \"owning\" &&\n targetRel.through &&\n (targetRel.relationName === newRelation.inverseRelationName)) {\n // Found a corresponding owning many-to-many relation\n isManyToManyInverse = true;\n break;\n }\n }\n } catch (e) {\n // If we can't inspect the target collection, assume one-to-many\n }\n }\n\n // Only add foreignKeyOnTarget for one-to-many inverse relations\n if (!isManyToManyInverse && !newRelation.foreignKeyOnTarget) {\n newRelation.foreignKeyOnTarget = generateForeignKeyName(sourceName);\n }\n } else if (newRelation.cardinality === \"many\" && newRelation.direction === \"owning\") {\n\n // Many-to-many via junction table\n const sourceTableName = getTableName(sourceCollection);\n const targetTableName = getTableName(targetCollection);\n\n newRelation.through = {\n table: newRelation.through?.table ?? [sourceTableName, targetTableName].sort().join(\"_\"),\n sourceColumn: newRelation.through?.sourceColumn ?? generateForeignKeyName(sourceName),\n targetColumn: newRelation.through?.targetColumn ?? generateForeignKeyName(newRelation.relationName),\n };\n }\n }\n\n // 4. Basic validation to catch configuration errors early\n if (newRelation.cardinality === \"one\" && newRelation.direction === \"owning\" && !newRelation.localKey && !newRelation.joinPath) {\n 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}'`);\n }\n if (newRelation.cardinality === \"one\" && newRelation.direction === \"inverse\" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath) {\n 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}'`);\n }\n if (newRelation.cardinality === \"many\" && newRelation.direction === \"inverse\" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath) {\n 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}'`);\n }\n\n return newRelation as Relation;\n}\n\nexport function resolveCollectionRelations(\n collection: EntityCollection,\n): Record<string, Relation> {\n const relations: Record<string, Relation> = {};\n\n // 1. Process explicit relations from the new `relations` field\n if (collection.relations) {\n collection.relations.forEach((relation) => {\n const normalizedRelation = sanitizeRelation(relation, collection);\n const relationKey = normalizedRelation.relationName;\n if (relationKey) {\n relations[relationKey] = normalizedRelation;\n }\n });\n }\n\n // 2. Process properties of type \"relation\"\n if (collection.properties) {\n Object.entries(collection.properties).forEach(([propKey, prop]) => {\n const relation = resolvePropertyRelation({\n propertyKey: propKey,\n property: prop as Property,\n sourceCollection: collection\n });\n if (relation) {\n // Use property name as relation key if not already defined\n if (!relations[propKey]) {\n // FIX: Set relationName to propKey if not defined, before normalizing\n if (!relation.relationName) {\n relation.relationName = propKey;\n }\n relations[propKey] = sanitizeRelation(relation, collection); // Already normalized in collection.relations\n }\n }\n });\n }\n\n return relations;\n}\n\nexport function resolvePropertyRelation({\n propertyKey,\n property,\n sourceCollection\n}: {\n propertyKey: string;\n property: Property;\n sourceCollection: EntityCollection;\n}): Relation | undefined {\n if (property.type !== \"relation\") return undefined;\n\n const relation = sourceCollection.relations?.find((rel) => rel.relationName === property.relationName)\n if (!relation) {\n console.warn(`Unrecognized relation format for property '${propertyKey}' in collection '${sourceCollection.slug || sourceCollection.dbPath}'`);\n return undefined;\n }\n\n return relation as Relation;\n\n}\n\nexport function getTableName(collection: EntityCollection): string {\n return collection.dbPath ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);\n}\n\nexport function getTableVarName(tableName: string): string {\n return tableName.replace(/_([a-z])/g, (_, char) => char.toUpperCase());\n}\n\nexport function getEnumVarName(tableName: string, propName: string): string {\n const tableVar = getTableVarName(tableName);\n const propVar = propName.charAt(0).toUpperCase() + propName.slice(1);\n return `${tableVar}${propVar}`;\n}\n\nexport function getColumnName(fullColumn: string): string {\n return fullColumn.includes(\".\") ? fullColumn.split(\".\").pop()! : fullColumn;\n}\n","import jsonLogic from \"json-logic-js\";\nimport {\n ArrayProperty,\n AuthController,\n ConditionContext,\n EnumValueConfig,\n JsonLogicRule,\n NumberProperty,\n PropertyConditions,\n Property,\n ReferenceProperty,\n StringProperty\n} from \"@rebasepro/types\";\n\n/**\n * Access a nested property from an object via dot notation.\n */\nfunction getIn(obj: Record<string, unknown> | unknown, path: string): unknown {\n if (!obj || !path) return undefined;\n return path.split('.').reduce((acc: unknown, part: string) => acc && (acc as Record<string, unknown>)[part], obj);\n}\n\nlet operationsRegistered = false;\n\n/**\n * Register custom JSON Logic operations for Rebase.\n * Call this once at app initialization.\n */\nexport function registerConditionOperations(): void {\n if (operationsRegistered) return;\n\n // Check if user has a specific role by ID\n jsonLogic.add_operation(\"hasRole\", function (this: ConditionContext, roleId: string) {\n return this?.user?.roles?.includes(roleId) ?? false;\n });\n\n // Check if user has any of the specified roles\n jsonLogic.add_operation(\"hasAnyRole\", function (this: ConditionContext, roleIds: string[]) {\n if (!this?.user?.roles || !Array.isArray(roleIds)) return false;\n return roleIds.some(role => this.user.roles.includes(role));\n });\n\n // Check if a timestamp is today\n jsonLogic.add_operation(\"isToday\", (timestamp: number) => {\n if (!timestamp) return false;\n const date = new Date(timestamp);\n const today = new Date();\n return date.getFullYear() === today.getFullYear() &&\n date.getMonth() === today.getMonth() &&\n date.getDate() === today.getDate();\n });\n\n // Check if a timestamp is in the past\n jsonLogic.add_operation(\"isPast\", (timestamp: number) => {\n if (!timestamp) return false;\n return timestamp < Date.now();\n });\n\n // Check if a timestamp is in the future\n jsonLogic.add_operation(\"isFuture\", (timestamp: number) => {\n if (!timestamp) return false;\n return timestamp > Date.now();\n });\n\n operationsRegistered = true;\n}\n\n/**\n * Evaluate a JSON Logic rule against the given context.\n */\nexport function evaluateCondition(rule: JsonLogicRule, context: ConditionContext): unknown {\n // Ensure operations are registered\n registerConditionOperations();\n return jsonLogic.apply(rule, context);\n}\n\n/**\n * Convert a value to a format suitable for JSON Logic evaluation.\n * Specifically handles Date objects by converting them to Unix timestamps.\n */\nfunction serializeValueForConditions(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n // Handle Date objects\n if (value instanceof Date) {\n return value.getTime();\n }\n\n // Handle Firestore Timestamp-like objects (have toDate or toMillis)\n if (typeof (value as { toMillis?: () => number })?.toMillis === \"function\") {\n return (value as { toMillis: () => number }).toMillis();\n }\n if (typeof (value as { toDate?: () => Date })?.toDate === \"function\") {\n return (value as { toDate: () => Date }).toDate().getTime();\n }\n\n // Handle arrays recursively\n if (Array.isArray(value)) {\n return value.map(serializeValueForConditions);\n }\n\n // Handle plain objects recursively\n if (typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>)) {\n result[key] = serializeValueForConditions((value as Record<string, unknown>)[key]);\n }\n return result;\n }\n\n return value;\n}\n\n/**\n * Build a ConditionContext from the current property resolution context.\n */\nexport function buildConditionContext(params: {\n propertyKey?: string;\n values?: Record<string, unknown>;\n previousValues?: Record<string, unknown>;\n path: string;\n entityId?: string;\n index?: number;\n authController: AuthController;\n}): ConditionContext {\n const {\n propertyKey,\n values,\n previousValues,\n path,\n entityId,\n index,\n authController\n } = params;\n\n const user = authController.user;\n const serializedValues = serializeValueForConditions(values ?? {});\n const serializedPreviousValues = serializeValueForConditions(previousValues ?? values ?? {});\n\n return {\n values: serializedValues as Record<string, unknown>,\n previousValues: serializedPreviousValues as Record<string, unknown>,\n propertyValue: propertyKey ? getIn(serializedValues, propertyKey) : undefined,\n path,\n entityId,\n isNew: !entityId,\n index,\n user: {\n uid: user?.uid ?? \"\",\n email: user?.email ?? null,\n displayName: user?.displayName ?? null,\n photoURL: user?.photoURL ?? null,\n roles: user?.roles ?? []\n },\n now: Date.now()\n };\n}\n\n/**\n * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.\n */\nexport function applyPropertyConditions(\n property: Property,\n context: ConditionContext\n): Property {\n const { conditions } = property;\n if (!conditions) return property;\n\n let result = { ...property };\n\n // ═══════════════════════════════════════════════════════════════════════\n // FIELD STATE CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n // Evaluate disabled condition\n if (conditions.disabled) {\n const isDisabled = evaluateCondition(conditions.disabled, context);\n if (isDisabled) {\n result.disabled = {\n clearOnDisabled: conditions.clearOnDisabled ?? false,\n disabledMessage: conditions.disabledMessage,\n hidden: false\n };\n }\n }\n\n // Evaluate hidden condition\n if (conditions.hidden) {\n const isHidden = evaluateCondition(conditions.hidden, context);\n if (isHidden) {\n result.disabled = {\n ...(typeof result.disabled === \"object\" ? result.disabled : {}),\n hidden: true,\n clearOnDisabled: conditions.clearOnDisabled ?? false\n };\n }\n }\n\n // Evaluate readOnly condition\n if (conditions.readOnly) {\n const isReadOnly = evaluateCondition(conditions.readOnly, context);\n if (isReadOnly) {\n result.readOnly = true;\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // VALIDATION CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n // Evaluate required condition\n if (conditions.required !== undefined) {\n const isRequired = evaluateCondition(conditions.required, context) as boolean;\n result.validation = {\n ...result.validation,\n required: isRequired as boolean | undefined,\n requiredMessage: conditions.requiredMessage\n };\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // VALUE CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n // Apply default value for new entities\n if (context.isNew && conditions.defaultValue !== undefined) {\n result.defaultValue = evaluateCondition(conditions.defaultValue, context) as Property[\"defaultValue\"];\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // ENUM CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n if (\"enumValues\" in result && result.enumValues && (conditions.enumConditions || conditions.allowedEnumValues || conditions.excludedEnumValues)) {\n (result as Record<string, unknown>).enumValues = applyEnumConditions(\n result.enumValues as EnumValueConfig[],\n conditions,\n context\n );\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // REFERENCE CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n if (result.type === \"reference\") {\n if (conditions.referencePath) {\n (result as ReferenceProperty).path = evaluateCondition(conditions.referencePath, context) as string;\n }\n if (conditions.referenceFilter) {\n (result as ReferenceProperty).forceFilter = evaluateCondition(conditions.referenceFilter, context) as ReferenceProperty[\"forceFilter\"];\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // ARRAY CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n if (result.type === \"array\") {\n if (conditions.canAddElements !== undefined) {\n (result as ArrayProperty).canAddElements = evaluateCondition(conditions.canAddElements, context) as boolean;\n }\n if (conditions.sortable !== undefined) {\n (result as ArrayProperty).sortable = evaluateCondition(conditions.sortable, context) as boolean;\n }\n }\n\n return result;\n}\n\n/**\n * Convert an object with numeric keys back to an array.\n * Firestore stores arrays as {\"0\": \"a\", \"1\": \"b\"} to avoid nested arrays.\n */\nfunction objectToArray(obj: unknown): string[] {\n if (Array.isArray(obj)) return obj.map(String);\n if (obj && typeof obj === \"object\") {\n const keys = Object.keys(obj);\n if (keys.length > 0 && keys.every(k => !isNaN(Number(k)))) {\n return keys\n .sort((a, b) => Number(a) - Number(b))\n .map(k => (obj as Record<string, unknown>)[k])\n .filter((v): v is string => typeof v === \"string\" || typeof v === \"number\")\n .map(String);\n }\n }\n return [];\n}\n\n/**\n * Apply enum-specific conditions to filter and modify enum values.\n */\nfunction applyEnumConditions(\n enumValues: EnumValueConfig[],\n conditions: PropertyConditions,\n context: ConditionContext\n): EnumValueConfig[] {\n let result = [...enumValues];\n\n // Apply allowedEnumValues filter\n if (conditions.allowedEnumValues) {\n const allowed = evaluateCondition(conditions.allowedEnumValues, context);\n // Handle both array format and object-with-numeric-keys format (Firestore workaround)\n const allowedArray = objectToArray(allowed);\n if (allowedArray.length > 0) {\n result = result.filter(ev => allowedArray.includes(String(ev.id)));\n }\n }\n\n // Apply excludedEnumValues filter\n if (conditions.excludedEnumValues) {\n const excluded = evaluateCondition(conditions.excludedEnumValues, context);\n // Handle both array format and object-with-numeric-keys format\n const excludedArray = objectToArray(excluded);\n if (excludedArray.length > 0) {\n result = result.filter(ev => !excludedArray.includes(String(ev.id)));\n }\n }\n\n // Apply individual enum conditions\n if (conditions.enumConditions) {\n result = result\n .map(ev => {\n const evConditions = conditions.enumConditions?.[ev.id];\n if (!evConditions) return ev;\n\n // Check hidden condition first\n if (evConditions.hidden && evaluateCondition(evConditions.hidden, context)) {\n return null; // Will be filtered out\n }\n\n // Check disabled condition\n if (evConditions.disabled && evaluateCondition(evConditions.disabled, context)) {\n return {\n ...ev,\n disabled: true\n };\n }\n\n return ev;\n })\n .filter((ev): ev is EnumValueConfig => ev !== null);\n }\n\n return result;\n}\n","import {\n EntityCollection,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty\n} from \"@rebasepro/types\";\nimport { deepEqual } from \"fast-equals\";\n\nimport { enumToObjectEntries, getSubcollections, removeFunctions, resolveCollectionRelations } from \"../util\";\nimport cloneDeep from \"lodash/cloneDeep.js\";\n\nexport class CollectionRegistry {\n\n // Normalized runtime layer (used by Data Grid / UI)\n private collectionsByDbPath = new Map<string, EntityCollection>();\n private collectionsBySlug = new Map<string, EntityCollection>();\n private rootCollections: EntityCollection[] = [];\n\n // Raw configuration layer (used by Collection Editor AST generator)\n private rawCollectionsByDbPath = new Map<string, EntityCollection>();\n private rawCollectionsBySlug = new Map<string, EntityCollection>();\n private rawRootCollections: EntityCollection[] = [];\n\n // Snapshot of raw input for idempotency check — compared BEFORE normalization\n // to avoid the issue where normalization creates new objects that always fail equality.\n private lastRawInputSnapshot: ReturnType<typeof removeFunctions>[] | null = null;\n\n constructor(collections?: EntityCollection[]) {\n if (collections) {\n this.registerMultiple(collections);\n }\n }\n\n reset() {\n this.collectionsByDbPath.clear();\n this.collectionsBySlug.clear();\n this.rootCollections = [];\n\n this.rawCollectionsByDbPath.clear();\n this.rawCollectionsBySlug.clear();\n this.rawRootCollections = [];\n }\n\n /**\n * Registers a collection and its subcollections recursively.\n * Returns true if the collections have changed, false otherwise.\n *\n * Idempotent: compares the raw input (before normalization) against a stored\n * snapshot. Only re-normalizes and re-registers when the raw input actually changed.\n * @param collections\n */\n registerMultiple(collections: EntityCollection[]): boolean {\n // Compare raw input BEFORE normalization to detect actual changes.\n // This avoids the old issue where normalization creates new objects\n // that always fail deep-equal even when the source data is identical.\n const rawSnapshot = collections.map(c => removeFunctions(c));\n if (this.lastRawInputSnapshot && deepEqual(this.lastRawInputSnapshot, rawSnapshot)) {\n return false;\n }\n\n // Raw input has changed — normalize and register\n this.reset();\n\n const normalizedCollections = collections.map(c => this.normalizeCollection({ ...c }));\n normalizedCollections.forEach((c, index) => this.register(c, collections[index]));\n\n // Store the snapshot for future comparisons\n this.lastRawInputSnapshot = rawSnapshot;\n\n return true;\n }\n\n register(collection: EntityCollection, rawCollection?: EntityCollection) {\n const raw = rawCollection ? cloneDeep(rawCollection) : cloneDeep(collection);\n\n this.rootCollections.push(collection);\n this.rawRootCollections.push(raw);\n\n this._registerRecursively(collection, raw);\n }\n\n private _registerRecursively(collection: EntityCollection, rawCollection: EntityCollection) {\n if (this.collectionsByDbPath.has(collection.dbPath)) {\n return;\n }\n\n const normalizedCollection = this.normalizeCollection(collection);\n this.collectionsByDbPath.set(normalizedCollection.dbPath, normalizedCollection);\n this.rawCollectionsByDbPath.set(rawCollection.dbPath, rawCollection);\n\n if (normalizedCollection.slug) {\n this.collectionsBySlug.set(normalizedCollection.slug, normalizedCollection);\n }\n if (rawCollection.slug) {\n this.rawCollectionsBySlug.set(rawCollection.slug, rawCollection);\n }\n\n const subcollections = getSubcollections(collection);\n const rawSubcollections = getSubcollections(rawCollection);\n\n if (subcollections && rawSubcollections) {\n subcollections.forEach((subCollection, index) => {\n this._registerRecursively(this.normalizeCollection(subCollection), cloneDeep(rawSubcollections[index]));\n });\n }\n }\n\n public normalizeCollection(collection: EntityCollection): EntityCollection {\n const properties: Properties = this.normalizeProperties(collection.properties, collection.relations ?? []);\n\n collection.properties = properties;\n return collection;\n }\n\n private normalizeProperties(properties: Properties, relations: Relation[]): Properties {\n const newProperties: Properties = {};\n for (const key in properties) {\n newProperties[key] = this.normalizeProperty(properties[key], relations);\n }\n return newProperties;\n }\n\n private normalizeProperty(property: Property, relations: Relation[]): Property {\n const newProperty = { ...property };\n\n if (newProperty.type === \"map\" && newProperty.properties) {\n newProperty.properties = this.normalizeProperties(newProperty.properties, relations);\n } else if (newProperty.type === \"array\") {\n if (newProperty.of) {\n newProperty.of = this.normalizeProperty(newProperty.of, relations);\n } else if (newProperty.oneOf && newProperty.oneOf.properties) {\n newProperty.oneOf.properties = this.normalizeProperties(newProperty.oneOf.properties, relations);\n }\n } else if ((newProperty.type === \"string\" || newProperty.type === \"number\") && newProperty.enum) {\n const stringOrNumberProperty = newProperty as StringProperty | NumberProperty;\n if (typeof stringOrNumberProperty.enum === \"object\" && !Array.isArray(stringOrNumberProperty.enum)) {\n (stringOrNumberProperty as unknown as Record<string, unknown>).enum = enumToObjectEntries(stringOrNumberProperty.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [];\n }\n } else if (newProperty.type === \"relation\") {\n const relationProperty = newProperty as RelationProperty;\n const relation = relations.find(r => r.relationName === relationProperty.relationName);\n if (relation) {\n // we attach the resolved relation to the property\n (relationProperty as unknown as Record<string, unknown>).relation = relation;\n } else {\n console.warn(`Could not find relation for property with relationName: ${relationProperty.relationName}`);\n }\n }\n\n return newProperty;\n }\n\n get(path: string): EntityCollection | undefined {\n // First try slug lookup\n const bySlug = this.collectionsBySlug.get(path);\n if (bySlug) return bySlug;\n\n // Fallback to dbPath lookup\n return this.collectionsByDbPath.get(path);\n }\n\n /**\n * Gets the pristine, un-normalized collection exactly as it was provided.\n * Useful for the AST editor so it doesn't accidentally serialize injected metadata back to disk.\n */\n getRaw(path: string): EntityCollection | undefined {\n const bySlug = this.rawCollectionsBySlug.get(path);\n if (bySlug) return bySlug;\n return this.rawCollectionsByDbPath.get(path);\n }\n\n /**\n * Get collection by resolving multi-segment paths through relations\n * e.g., \"authors/70/posts\" resolves to the posts collection\n */\n getCollectionByPath(collectionPath: string): EntityCollection | undefined {\n // Handle simple single collection path\n if (!collectionPath.includes(\"/\")) {\n return this.get(collectionPath);\n }\n\n // Handle multi-segment paths by resolving through relations\n const pathSegments = collectionPath.split(\"/\").filter(p => p);\n\n if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {\n throw new Error(`Invalid relation path: ${collectionPath}. Expected format: collection/id/relation or collection/id/relation/id/relation`);\n }\n\n // Start with the root collection\n const rootCollectionPath = pathSegments[0];\n let currentCollection = this.get(rootCollectionPath);\n\n if (!currentCollection) {\n throw new Error(`Root collection not found: ${rootCollectionPath}`);\n }\n\n // Navigate through the path using relations\n for (let i = 2; i < pathSegments.length; i += 2) {\n const relationKey = pathSegments[i];\n\n // Get relations for current collection\n const resolvedRelations = resolveCollectionRelations(currentCollection);\n const relation = resolvedRelations[relationKey];\n\n if (!relation) {\n throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug || currentCollection.dbPath}'`);\n }\n\n // Move to the target collection\n currentCollection = relation.target();\n\n // If there are more segments, continue navigation\n if (i + 1 < pathSegments.length) {\n // Skip entity ID segment\n }\n }\n\n return currentCollection;\n }\n\n getCollections(): EntityCollection[] {\n return Array.from(this.collectionsByDbPath.values());\n }\n\n getRawCollections(): EntityCollection[] {\n return Array.from(this.rawCollectionsByDbPath.values());\n }\n\n /**\n * Resolves a multi-segment path like \"products/123/locales\" and returns\n * information about the collections and entity IDs along the path\n */\n resolvePathToCollections(path: string): {\n collections: EntityCollection[],\n entityIds: (string | number)[],\n finalCollection: EntityCollection\n } {\n const pathSegments = path.split(\"/\").filter(p => p);\n\n if (pathSegments.length === 0) {\n throw new Error(`Invalid path: ${path}`);\n }\n\n if (pathSegments.length % 2 !== 1) {\n throw new Error(`Invalid collection path: ${path}. It must have an odd number of segments.`);\n }\n\n const collections: EntityCollection[] = [];\n const entityIds: (string | number)[] = [];\n\n // Start with the first collection\n let currentCollection = this.get(pathSegments[0]);\n\n if (!currentCollection) {\n throw new Error(`Unknown collection path or slug: ${pathSegments[0]}`);\n }\n\n collections.push(currentCollection);\n\n // Process the rest of the path in pairs (entityId, subcollectionSlug)\n for (let i = 1; i < pathSegments.length; i += 2) {\n const entityId = pathSegments[i];\n entityIds.push(entityId);\n\n if (i + 1 < pathSegments.length) {\n const subcollectionSlug = pathSegments[i + 1];\n const subcollections: EntityCollection[] | undefined = currentCollection.subcollections?.();\n if (!subcollections) {\n throw new Error(`No subcollections found for ${currentCollection.slug || currentCollection.dbPath} in path: ${path}`);\n }\n\n const subcollection: EntityCollection | undefined = subcollections.find(c => c.slug === subcollectionSlug);\n if (!subcollection) {\n throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug || currentCollection.dbPath}`);\n }\n currentCollection = subcollection;\n collections.push(currentCollection);\n }\n }\n\n return {\n collections,\n entityIds,\n finalCollection: currentCollection\n };\n }\n\n}\n\nfunction areCollectionListsEqual(a: EntityCollection[], b: EntityCollection[]) {\n // console.log(\"Comparing collection lists\", a, b);\n // return true;\n if (a.length !== b.length) {\n return false;\n }\n const aCopy = [...a];\n const bCopy = [...b];\n const aSorted = aCopy.sort((x, y) => x.slug.localeCompare(y.slug));\n const bSorted = bCopy.sort((x, y) => x.slug.localeCompare(y.slug));\n return aSorted.every((value, index) => areCollectionsEqual(value, bSorted[index]));\n}\n\nfunction areCollectionsEqual(a: EntityCollection, b: EntityCollection) {\n const {\n subcollections: subcollectionsA,\n ...restA\n } = a;\n const {\n subcollections: subcollectionsB,\n ...restB\n } = b;\n if (!areCollectionListsEqual(subcollectionsA?.() ?? [], subcollectionsB?.() ?? [])) {\n return false;\n }\n return deepEqual(removeFunctions(restA), removeFunctions(restB));\n}\n"],"names":["DEFAULT_ONE_OF_TYPE","DEFAULT_ONE_OF_VALUE","isEmptyArray","value","Array","isArray","length","isFunction","obj","isInteger","String","Math","floor","Number","isNaN","getIn","key","def","p","path","toPath","undefined","setIn","res","clone","resVal","i","pathArray","currentPath","currentObj","slice","isObject","nextPath","replace","split","pick","args","reduce","item","isPlainObject","proto","Object","getPrototypeOf","prototype","mergeDeep","target","source","ignoreUndefined","output","hasOwnProperty","call","sourceValue","outputValue","Date","getTime","newArray","maxLength","max","sourceItem","targetItem","getValueInPath","o","includes","pathSegments","map","segment","firstSegment","isArrayAndIndexExists","parseInt","nextObject","join","removeInPath","currentObject","parts","last","pop","part","removeFunctions","v","entries","filter","_","a","b","getHashValue","id","toLocaleString","GeoPoint","hash","ignoreUnknown","removeUndefined","removeEmptyStrings","keys","forEach","isEmptyObject","childRes","isString","shouldKeepIfString","removeNulls","removePropsIfExisting","comparison","val","splice","isReadOnly","property","readOnly","type","autoValue","Field","isHidden","disabled","Boolean","hidden","isPropertyBuilder","dynamicProps","getDefaultValuesFor","properties","getDefaultValueFor","defaultValue","defaultValuesFor","getDefaultValueFortype","updateDateAutoValues","inputValues","status","timestampNowValue","traverseValuesProperties","inputValue","sanitizeData","values","result","validation","required","getReferenceFrom","entity","Error","EntityReference","datasource","databaseId","getRelationFrom","EntityRelation","operation","safeInputValues","updatedValues","updatedValue","traverseValueProperty","of","e","oneOf","typeField","valueField","rec","childProperty","sortProperties","propertiesOrder","propertiesKeys","validOrderKeys","processedKeys","Set","orderedResult","missingProperties","has","console","error","resolveDefaultSelectedView","defaultSelectedView","params","getLocalChangesBackup","collection","localChangesBackup","getPrimaryKeys","ids","prop","isId","kebabCaseRegex","toKebabCase","str","regExpMatchArray","match","x","toLowerCase","snakeCaseRegex","toSnakeCase","randomString","strLength","random","toString","randomColor","slugify","text","separator","lowercase","from","to","l","RegExp","charAt","trim","unslugify","slug","txt","toUpperCase","substring","prettifyIdentifier","input","s","char","log","defaultDateFormat","enumToObjectEntries","enumValues","label","getLabelOrConfigFrom","find","entry","COLLECTION_PATH_SEPARATOR","stripCollectionPath","segmentsToStrippedPath","fullPathToCollectionSegments","paths","serializeRegExp","hydrateRegExp","fragments","isValidRegExp","fullRegexp","simpleRegexp","isDefaultFieldConfigId","resolveProperty","props","ignoreMissingFields","rest","resultProperty","usedPropertyValue","propertyKey","propertyValue","previousValues","dynamicPropsResult","resolvedProperty","resolveProperties","enum","resolvePropertyEnum","propertyConfig","cmsFields","propertyConfigs","customField","warn","_unused","restConfigProperty","customFieldProperty","name","resolveRelationProperty","relations","relation","rel","relationName","childResolvedProperty","resolveArrayProperties","index","resolvedProperties","getArrayResolvedProperties","ofProperty","resolveEnumValues","resolveEntityView","entityView","contextEntityViews","resolveEntityAction","entityAction","contextEntityActions","resolvedSelectedEntityView","customViews","customizationController","selectedTab","canEdit","resolvedEntityViews","entityViews","selectedEntityView","selectedSecondaryForm","includeActions","getSubcollections","subcollections","push","cardinality","targetCollection","overrides","removeInitialAndTrailingSlashes","removeInitialSlash","removeTrailingSlash","startsWith","endsWith","addInitialSlash","getLastSegment","cleanPath","segments","resolveCollectionPathIds","allCollections","remainingPath","currentCollections","resolvedPathParts","foundMatch","potentialMatches","flatMap","col","sort","foundCollection","matchString","dbPath","idSeparatorIndex","indexOf","entityId","getCollectionBySlugWithin","slugOrPath","collections","subpaths","subpathCombinations","getCollectionPathsCombinations","subpathCombination","navigationEntry","localeCompare","newPath","navigateToEntity","openEntityMode","copy","sideEntityController","onClose","navigation","open","updateUrl","buildUrlCollectionPath","navigate","reservedKeys","mergeEntityActions","currentActions","newActions","updatedActions","action","newAction","mergedAction","evaluateAST","sqlString","auth","cleanedSQL","openCount","isEnclosing","splitByTopLevel","delimiter","current","orParts","some","andParts","every","upperSQL","roleIntersectMatch","requiredRoles","r","userRoles","user","roles","roleContainMatch","pattern1","pattern2","match1","uid","match2","simpleEqualityMatch","field","operator","entityValue","evaluateRule","rule","access","ownerField","using","withCheck","checkOperation","authController","targetOperation","securityRules","applicableRules","operations","userRoleIds","roleApplicableRules","grantedByPermissive","deniedByRestrictive","mode","passed","hasPermissive","canReadCollection","canEditEntity","canCreateEntity","collectionGroup","canDeleteEntity","plural","word","amount","plurals","sis$","irregular","move","foot","goose","sex","child","man","tooth","person","uncountable","w","pattern","test","reg","singular","singulars","s$","getEntityImagePreviewPropertyKey","storage","acceptedFiles","url","flattenObject","parentKey","flatObj","newKey","assign","getArrayValuesCount","array","acc","nested","nestedKey","nestedCount","compoundKey","getNavigationEntriesFromPath","currentFullPath","collectionPath","restOfThePath","nextSegments","parentCollection","customView","view","getParentReferencesFromPath","buildCollection","buildProperty","buildProperties","buildPropertiesOrBuilder","propertiesOrBuilder","buildEnum","buildEnumValueConfig","enumValueConfig","buildEntityCallbacks","callbacks","buildAdditionalFieldDelegate","additionalFieldDelegate","buildFieldConfig","resolveStorageFilenameString","file","replacePlaceholders","resolveStoragePathString","ext","toArray","hasPropertyCallbacks","callbackName","ofs","processProperties","propsContext","currentValue","previousValue","Promise","all","prevItem","singlePropData","cbRes","resolve","buildPropertyCallbacks","propertyCallbacks","afterRead","processedValues","beforeSave","hashString","chr","charCodeAt","abs","generateForeignKeyName","snakeCaseName","singularName","sanitizeRelation","sourceCollection","newRelation","direction","foreignKeyOnTarget","through","joinPath","sourceName","localKey","foundForeignKey","targetRelations","targetRel","targetRelTarget","keyPrefix","inverseRelationName","isManyToManyInverse","sourceTableName","getTableName","targetTableName","table","sourceColumn","targetColumn","resolveCollectionRelations","normalizedRelation","relationKey","propKey","resolvePropertyRelation","getTableVarName","tableName","getEnumVarName","propName","tableVar","propVar","getColumnName","fullColumn","operationsRegistered","registerConditionOperations","jsonLogic","add_operation","roleId","roleIds","role","timestamp","date","today","getFullYear","getMonth","getDate","now","evaluateCondition","context","apply","serializeValueForConditions","toMillis","toDate","buildConditionContext","serializedValues","serializedPreviousValues","isNew","email","displayName","photoURL","applyPropertyConditions","conditions","isDisabled","clearOnDisabled","disabledMessage","isRequired","requiredMessage","enumConditions","allowedEnumValues","excludedEnumValues","applyEnumConditions","referencePath","referenceFilter","forceFilter","canAddElements","sortable","objectToArray","k","allowed","allowedArray","ev","excluded","excludedArray","evConditions","CollectionRegistry","collectionsByDbPath","Map","collectionsBySlug","rootCollections","rawCollectionsByDbPath","rawCollectionsBySlug","rawRootCollections","lastRawInputSnapshot","constructor","registerMultiple","reset","clear","rawSnapshot","c","deepEqual","normalizedCollections","normalizeCollection","register","rawCollection","raw","cloneDeep","_registerRecursively","normalizedCollection","set","rawSubcollections","subCollection","normalizeProperties","newProperties","normalizeProperty","newProperty","stringOrNumberProperty","relationProperty","get","bySlug","getRaw","getCollectionByPath","rootCollectionPath","currentCollection","resolvedRelations","getCollections","getRawCollections","resolvePathToCollections","entityIds","subcollectionSlug","sub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