@rebasepro/common 0.2.5 → 0.4.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/util/common.ts","../src/util/entities.ts","../src/util/collections.ts","../src/util/enums.ts","../src/util/paths.ts","../src/util/relations.ts","../src/util/resolutions.ts","../src/util/permissions.ts","../src/util/references.ts","../src/util/navigation_utils.ts","../src/util/navigation_from_path.ts","../src/util/parent_references_from_path.ts","../src/util/builders.ts","../src/util/storage.ts","../src/util/callbacks.ts","../src/util/conditions.ts","../src/collections/CollectionRegistry.ts","../src/collections/default-collections.ts","../src/data/query_builder.ts","../src/data/buildRebaseData.ts"],"sourcesContent":["export const DEFAULT_ONE_OF_TYPE = \"type\"\nexport const DEFAULT_ONE_OF_VALUE = \"value\"\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 \"@rebasepro/utils\";\n\nexport function isReadOnly(property: Property): boolean {\n if (property.ui?.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 && !(\"Field\" in (property.ui || {}) && property.ui?.Field);\n }\n return false;\n}\n\nexport function isHidden(property: Property): boolean {\n return typeof property.ui?.disabled === \"object\" && Boolean(property.ui?.disabled.hidden);\n}\n\nexport function isPropertyBuilder(property?: Property) {\n return typeof property?.dynamicProps === \"function\";\n}\n\nexport function getDefaultValuesFor<M extends Record<string, unknown>>(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,\n...b }), {}) as EntityValues<M>;\n}\n\nexport function getDefaultValueFor(property?: Property): unknown {\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): unknown {\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 if (type === \"vector\") {\n return null;\n } else if (type === \"binary\") {\n return null;\n } else {\n return null;\n }\n}\n\n/**\n * Update the automatic values in an entity before save\n * @group Driver\n */\nexport function updateDateAutoValues<M extends Record<string, unknown>>({\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 Driver\n */\nexport function sanitizeData<M extends Record<string, unknown>>\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, unknown>>(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 driver: entity.driver,\n databaseId: entity.databaseId\n });\n}\n\nexport function getRelationFrom<M extends Record<string, unknown>>(entity: Entity<M>): EntityRelation {\n return new EntityRelation(entity.id, entity.path, entity);\n}\n\n/**\n * Normalize a value into a proper EntityRelation instance.\n * Handles EntityRelation class instances, and plain objects\n * with `__type === \"relation\"` or an `isEntityRelation()` method.\n *\n * Returns null if the value cannot be coerced.\n */\nexport function normalizeToEntityRelation(value: unknown): EntityRelation | null {\n if (value instanceof EntityRelation) return value;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\n const obj = value as Record<string, unknown>;\n const isRelationLike =\n obj.__type === \"relation\" ||\n obj.__type === \"reference\" ||\n (typeof obj.isEntityRelation === \"function\" && (obj.isEntityRelation as () => boolean)()) ||\n (typeof obj.isEntityReference === \"function\" && (obj.isEntityReference as () => boolean)());\n\n if (!isRelationLike) return null;\n\n return new EntityRelation(\n obj.id as string | number,\n obj.path as string,\n obj.data as Entity | undefined\n );\n}\n\nexport function traverseValuesProperties<M extends Record<string, unknown>>(\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,\n...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\n/**\n * Relation reference types used throughout the server layer.\n * These replace the 50+ manual `{ id, path, __type: \"relation\" }` constructions.\n */\nexport interface RelationRef {\n readonly id: string | number;\n readonly path: string;\n readonly __type: \"relation\";\n}\n\nexport interface RelationRefWithData extends RelationRef {\n readonly data: Entity;\n}\n\n/**\n * Create a lightweight relation stub for CMS views.\n * Replaces inline `{ id, path, __type: \"relation\" }` object literals.\n */\nexport function createRelationRef(id: string | number, path: string): RelationRef {\n return { id, path, __type: \"relation\" };\n}\n\n/**\n * Create a hydrated relation reference that includes the full entity data.\n * Used when entity data has been pre-fetched (e.g., via batch loading or JOINs).\n */\nexport function createRelationRefWithData(id: string | number, path: string, data: Entity): RelationRefWithData {\n return { id, path, __type: \"relation\", data };\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, unknown>>(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,\n...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: Properties, b: Properties) => ({ ...a,\n...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: Properties, b: Properties) => ({ ...a,\n...b }), {}) as Properties;\n\n return { ...orderedResult,\n...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\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, unknown>>(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","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","import { CollectionWithRelations, EntityCollection, getDataSourceCapabilities, Property, Relation, RelationProperty } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport { generateForeignKeyName } from \"@rebasepro/utils\";\n\nexport function sanitizeRelation(\n relation: Partial<Relation>,\n sourceCollection: EntityCollection,\n resolveCollection?: (slugOrTable: string) => EntityCollection | undefined\n): Relation {\n if (!relation.target) {\n throw new Error(\"Relation is missing a `target` collection.\");\n }\n\n const rawTarget = relation.target;\n let targetCollection: EntityCollection | undefined;\n\n if (typeof rawTarget === \"string\") {\n if (resolveCollection) {\n targetCollection = resolveCollection(rawTarget);\n }\n if (!targetCollection) {\n targetCollection = { slug: rawTarget, name: rawTarget } as EntityCollection;\n }\n } else if (typeof rawTarget === \"function\") {\n const evaluated = rawTarget();\n if (typeof evaluated === \"string\") {\n if (resolveCollection) {\n targetCollection = resolveCollection(evaluated);\n }\n if (!targetCollection) {\n targetCollection = { slug: evaluated, name: evaluated } as EntityCollection;\n }\n } else {\n targetCollection = evaluated;\n }\n } else if (rawTarget && typeof rawTarget === \"object\") {\n targetCollection = rawTarget as EntityCollection;\n }\n\n if (!targetCollection) {\n throw new Error(\"Relation is missing a valid `target` collection.\");\n }\n\n const newRelation: Partial<Relation> = { ...relation };\n\n newRelation.target = () => {\n if (typeof rawTarget === \"string\") {\n return (resolveCollection && resolveCollection(rawTarget)) || targetCollection!;\n } else if (typeof rawTarget === \"function\") {\n const evaluated = rawTarget();\n if (typeof evaluated === \"string\") {\n return (resolveCollection && resolveCollection(evaluated)) || targetCollection!;\n }\n return evaluated;\n }\n return targetCollection!;\n };\n\n // 1. Default relationName from target collection slug\n if (!newRelation.relationName) {\n newRelation.relationName = toSnakeCase(targetCollection.slug);\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 = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? (((targetCollection as CollectionWithRelations).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 // 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 // Note: we intentionally do NOT require `through` here because the raw (unsanitized)\n // relations won't have `through` populated yet — sanitizeRelation fills it in later.\n // `cardinality: \"many\" + direction: \"owning\"` is sufficient to identify owning M2M.\n\n // 1. Check the explicit relations[] array\n const targetRelations = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? (((targetCollection as CollectionWithRelations).relations) || []) : [];\n for (const targetRel of targetRelations) {\n if (targetRel.cardinality === \"many\" &&\n (targetRel.direction === \"owning\" || !targetRel.direction) &&\n (targetRel.relationName === newRelation.inverseRelationName)) {\n isManyToManyInverse = true;\n break;\n }\n }\n\n // 2. Also check the target's properties for inline relation definitions\n // (e.g. posts.properties.tags = { type: \"relation\", cardinality: \"many\", direction: \"owning\" })\n if (!isManyToManyInverse && targetCollection.properties) {\n for (const [propKey, prop] of Object.entries(targetCollection.properties)) {\n if ((prop as Property).type !== \"relation\") continue;\n const relProp = prop as RelationProperty;\n const relName = relProp.relationName || propKey;\n if (relName === newRelation.inverseRelationName &&\n relProp.cardinality === \"many\" &&\n (relProp.direction === \"owning\" || !relProp.direction)) {\n isManyToManyInverse = true;\n break;\n }\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 && !newRelation.inverseRelationName) {\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\n/** WeakMap cache — same collection instance always yields the same relation map. */\nconst _resolvedRelationsCache = new WeakMap<EntityCollection, Record<string, Relation>>();\n\nexport function resolveCollectionRelations(\n collection: EntityCollection\n): Record<string, Relation> {\n const cached = _resolvedRelationsCache.get(collection);\n if (cached) return cached;\n\n if (!getDataSourceCapabilities(collection.driver).supportsRelations) return {};\n const relCollection = collection as CollectionWithRelations;\n const relations: Record<string, Relation> = {};\n\n // Track which explicit relationName values have been registered so that\n // property-based entries in section 2 don't re-add the same underlying relation\n // under a different key (e.g. explicit \"company\" + property \"company_id\").\n const registeredRelationNames = new Set<string>();\n\n // 1. Process explicit relations from the `relations` field.\n // Each relation is stored once under its canonical relationName key.\n if (relCollection.relations) {\n relCollection.relations.forEach((relation: Relation) => {\n try {\n const normalizedRelation = sanitizeRelation(relation, collection);\n const relationKey = normalizedRelation.relationName;\n if (relationKey) {\n relations[relationKey] = normalizedRelation;\n registeredRelationNames.add(relationKey);\n }\n } catch (e) {\n // Ignore incomplete or invalid relations (e.g. missing target during registry setup)\n }\n });\n }\n\n // 2. Process properties of type \"relation\".\n // Only adds an entry if:\n // (a) the property key itself is not already in the map, AND\n // (b) the underlying relation (by relationName) hasn't already been registered.\n // This prevents duplicate entries when a property key differs from the\n // explicit relation's relationName (e.g. property \"company_id\" referencing\n // explicit relation \"company\").\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 // Skip if the property key is already registered\n if (relations[propKey]) return;\n\n // We previously skipped if the underlying relation was already registered under\n // its canonical relationName in section 1. But we need to keep the property mapping\n // for EntityFetchService to hydrate the relation back to the correct property key.\n // Deduplication for Drizzle schema generation is handled in generate-drizzle-schema-logic.ts.\n\n if (!relation.relationName) {\n relation.relationName = propKey;\n }\n const normalizedRelation = sanitizeRelation(relation, collection);\n relations[propKey] = normalizedRelation;\n registeredRelationNames.add(normalizedRelation.relationName ?? propKey);\n }\n });\n }\n\n _resolvedRelationsCache.set(collection, relations);\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 relProp = property as RelationProperty;\n\n // If the property has inline config (target set), build a Relation from it.\n // We only support the flat format where properties are directly on the RelationProperty.\n if (relProp.target) {\n return {\n relationName: relProp.relationName || propertyKey,\n target: relProp.target,\n cardinality: relProp.cardinality || \"one\",\n direction: relProp.direction || \"owning\",\n inverseRelationName: relProp.inverseRelationName,\n localKey: relProp.localKey,\n foreignKeyOnTarget: relProp.foreignKeyOnTarget,\n through: relProp.through,\n joinPath: relProp.joinPath,\n onUpdate: relProp.onUpdate,\n onDelete: relProp.onDelete,\n overrides: relProp.overrides,\n } as Relation;\n }\n\n console.warn(`Unrecognized or missing relation target for property '${propertyKey}' in collection '${sourceCollection.slug}'`);\n return undefined;\n}\n\nexport function getTableName(collection: EntityCollection): string {\n if (getDataSourceCapabilities(collection.driver).supportsRelations) {\n return (collection as CollectionWithRelations).table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);\n }\n return 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\n/**\n * Look up a relation by key with forgiving normalization.\n *\n * `resolveCollectionRelations` stores each relation under a single canonical\n * key (no aliases). This helper tries the given key as-is, then falls back to\n * slug form (underscores → hyphens) and snake_case form (hyphens → underscores)\n * so that callers that receive a key from external input (URL path segments,\n * user-provided config, etc.) can still find the right entry.\n */\nexport function findRelation(\n resolvedRelations: Record<string, Relation>,\n key: string\n): Relation | undefined {\n // Exact match first\n if (resolvedRelations[key]) return resolvedRelations[key];\n\n // Try slug form (e.g. \"company_id\" → \"company-id\")\n const slugKey = key.replace(/_/g, \"-\");\n if (slugKey !== key && resolvedRelations[slugKey]) return resolvedRelations[slugKey];\n\n // Try snake_case form (e.g. \"company-id\" → \"company_id\")\n const snakeKey = key.replace(/-/g, \"_\");\n if (snakeKey !== key && resolvedRelations[snakeKey]) return resolvedRelations[snakeKey];\n\n return undefined;\n}\n","import {\n ArrayProperty,\n AuthController,\n CollectionWithRelations,\n CollectionWithSubcollections,\n EntityCollection,\n EnumValueConfig,\n EnumValues,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty,\n getDataSourceCapabilities\n} from \"@rebasepro/types\";\n\ntype PropertyConfig = { property: unknown; [key: string]: unknown };\nimport { isPropertyBuilder } from \"./entities\";\nimport { enumToObjectEntries } from \"./enums\";\nimport { DEFAULT_ONE_OF_TYPE } from \"./common\";\nimport { isDefaultFieldConfigId } from \"@rebasepro/utils\";\nimport { getIn, mergeDeep } from \"@rebasepro/utils\";\nimport { resolveCollectionRelations } from \"./relations\";\n\n/**\n * Resolve property builders, enums and arrays.\n */\n\nexport type ResolvePropertyProps<M extends Record<string, unknown> = Record<string, unknown>> = {\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, unknown> = Record<string, unknown>>(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 // When path is not available (e.g. in preview contexts), skip dynamic\n // resolution and use the property as-is without dynamic modifications.\n resultProperty = property as Property;\n } else {\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 }\n } else {\n resultProperty = property as Property;\n }\n\n // Apply dynamic properties if they exist\n if (resultProperty?.dynamicProps && rest.path) {\n const path = rest.path;\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 restConfigProperty = { ...customField.property } as Record<string, unknown>;\n delete restConfigProperty.propertyConfig;\n const customFieldProperty = resolveProperty({\n property: { name: \"\",\n...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[], propertyKey?: string) {\n // If the property already has a resolved relation, return as-is\n if (property.relation) {\n return property;\n }\n\n // Determine the relation name: explicit > property key\n const name = property.relationName || propertyKey;\n\n // Find the relation by name (it may have been extracted from the property during normalization)\n const relation = name ? relations.find((rel) => rel.relationName === name) : undefined;\n if (!relation) {\n throw Error(`Relation ${name ?? \"(unnamed)\"} 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, unknown>>({\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,\n...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 (!(\"Field\" in (property.ui || {}) && property.ui?.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\n\nexport function getSubcollections<M extends Record<string, unknown> = Record<string, unknown>>(collection: EntityCollection<M>): EntityCollection<Record<string, unknown>>[] {\n if (collection.childCollections) {\n return collection.childCollections() ?? [];\n }\n\n if (getDataSourceCapabilities(collection.driver).supportsSubcollections && (collection as CollectionWithSubcollections).subcollections) {\n return (collection as CollectionWithSubcollections).subcollections!() ?? [];\n }\n\n if (getDataSourceCapabilities(collection.driver).supportsRelations) {\n const resolvedRelations = resolveCollectionRelations(collection);\n const manyRelations = Object.values(resolvedRelations).filter((r: Relation) => r.cardinality === \"many\");\n \n return manyRelations.map((r: Relation) => {\n const target = r.target();\n if (!target) return undefined;\n const relationKey = r.relationName || target.slug;\n\n // Try to find corresponding property to get custom name\n let customName: string | undefined;\n if (collection.properties) {\n const prop = Object.entries(collection.properties as Record<string, Property>).find(\n ([_, p]) => p.type === \"relation\" && p.relationName === relationKey\n );\n if (prop && prop[1].name) {\n customName = prop[1].name;\n }\n }\n\n const baseOverrides: Partial<EntityCollection> = { slug: relationKey };\n if (customName) {\n baseOverrides.name = customName;\n baseOverrides.singularName = customName;\n }\n\n const targetWithOverrides = { ...target, ...baseOverrides };\n return (r.overrides ? mergeDeep(targetWithOverrides, r.overrides) : targetWithOverrides) as EntityCollection<Record<string, unknown>>;\n }).filter((c: EntityCollection<Record<string, unknown>> | undefined): c is EntityCollection<Record<string, unknown>> => Boolean(c));\n }\n\n return [];\n}\n","import { AuthController, CollectionWithRelations, Entity, EntityCollection, getDataSourceCapabilities, SecurityRule, User } from \"@rebasepro/types\";\n\nfunction evaluateAST<USER extends User, M extends Record<string, unknown>>(sqlString: string, auth: AuthController<USER>, entity: Entity<M> | 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<USER extends User, M extends Record<string, unknown>>(rule: SecurityRule, auth: AuthController<USER>, entity: Entity<M> | 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\nexport function checkOperation<M extends Record<string, unknown>, USER extends User>(\n collection: EntityCollection<M>,\n authController: AuthController<USER>,\n entity: Entity<M> | null,\n targetOperation: \"select\" | \"insert\" | \"update\" | \"delete\"\n): boolean {\n const securityRules = getDataSourceCapabilities(collection.driver).supportsRLS ? (collection as CollectionWithRelations).securityRules : undefined;\n if (!securityRules || 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 = securityRules.filter((r: SecurityRule) =>\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: SecurityRule) => {\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: SecurityRule) => (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, unknown>, 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, unknown>, 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, unknown>, 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, \"insert\");\n}\n\nexport function canDeleteEntity<M extends Record<string, unknown>, 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","import { EntityCollection } from \"@rebasepro/types\";\n\nexport function getEntityImagePreviewPropertyKey<M extends Record<string, unknown>>(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.ui?.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 && !Array.isArray(property.of) && property.of.type === \"string\" && property.of.url === \"image\") {\n return key;\n }\n }\n // fallback: any storage property without explicit acceptedFiles (e.g. a generic \"picture\" field)\n for (const key in collection.properties) {\n const property = collection.properties[key];\n if (property.type === \"string\" && property.storage && !property.storage.acceptedFiles) {\n return key;\n }\n }\n // fallback: any array of storage properties without explicit acceptedFiles\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 && !property.of.storage.acceptedFiles) {\n return key;\n }\n }\n return undefined;\n}\n","import { EntityCollection } from \"@rebasepro/types\";\n\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.slug); // 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 (getSubcollections(navigationEntry).length > 0) {\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","import { EntityCollection } from \"@rebasepro/types\";\ntype EntityCustomView<M extends Record<string, unknown> = Record<string, unknown>> = { key: string; [key: string]: unknown };\nimport { getCollectionPathsCombinations, removeInitialAndTrailingSlashes } from \"./navigation_utils\";\nimport { getSubcollections } from \"./resolutions\";\n\nexport type NavigationViewInternal<M extends Record<string, unknown> = Record<string, unknown>> =\n | NavigationViewEntityInternal<M>\n | NavigationViewCollectionInternal<M>\n | NavigationViewEntityCustomInternal<M>;\n\nexport interface NavigationViewEntityInternal<M extends Record<string, unknown>> {\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, unknown>> {\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, unknown>> {\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((v): v is EntityCustomView => v != null)\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,\npath: 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 (getSubcollections(collection).length > 0) {\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 ReferenceProperty,\n StringProperty,\n User\n} from \"@rebasepro/types\";\n\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, unknown> = Record<string, unknown>,\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\n // SAFETY: Identity function — P is a subtype of the conditional return type by definition\n return property as unknown as ReturnType<typeof buildProperty<T, P>>;\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, unknown>>(\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, unknown>>(\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, unknown> = Record<string, unknown>>(\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, unknown>, USER extends User = User>(\n additionalFieldDelegate: AdditionalFieldDelegate<M, USER>\n): AdditionalFieldDelegate<M, USER> {\n return additionalFieldDelegate;\n}\n\n\n","import { ArrayProperty, EntityValues, StorageConfig, StringProperty, UploadedFileContext } from \"@rebasepro/types\";\nimport { randomString } from \"@rebasepro/utils\";\n\ninterface ResolveFilenameStringParams<M extends Record<string, unknown>> {\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 Record<string, unknown>>(\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 Record<string, unknown>> {\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 Record<string, unknown>>(\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","import { EntityCallbacks, Properties } from \"@rebasepro/types\";\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 const 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 const 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\n const cbRes = await Promise.resolve(property.callbacks[callbackName]({\n ...(propsContext as Record<string, unknown>),\n value: currentValue,\n previousValue\n } as never));\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,\nvalues: 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","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 ?? []).map((r: unknown) => typeof r === \"string\" ? r : (r as { id: string }).id)\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 const 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.ui = result.ui || {};\n result.ui.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.ui = result.ui || {};\n result.ui.disabled = {\n ...(typeof result.ui?.disabled === \"object\" ? result.ui.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.ui = result.ui || {};\n result.ui.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 (\"enum\" in result && result.enum && (conditions.enumConditions || conditions.allowedEnumValues || conditions.excludedEnumValues)) {\n (result as Record<string, unknown>).enum = applyEnumConditions(\n result.enum 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).fixedFilter = evaluateCondition(conditions.referenceFilter, context) as ReferenceProperty[\"fixedFilter\"];\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 ArrayProperty,\n CollectionWithRelations,\n CollectionWithSubcollections,\n EntityCollection,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty,\n getDataSourceCapabilities\n} from \"@rebasepro/types\";\nimport { deepEqual } from \"fast-equals\";\n\nimport { enumToObjectEntries, getSubcollections, getTableName, resolveCollectionRelations, findRelation, sanitizeRelation } from \"../util\";\nimport { removeFunctions, mergeDeep, deepClone } from \"@rebasepro/utils\";\n\nexport class CollectionRegistry {\n\n // Normalized runtime layer (used by Data Grid / UI)\n private collectionsByTableName = new Map<string, EntityCollection>();\n private collectionsBySlug = new Map<string, EntityCollection>();\n private rootCollections: EntityCollection[] = [];\n private cachedCollectionsList: EntityCollection[] | null = null;\n\n // Raw configuration layer (used by Collection Editor AST generator)\n private rawCollectionsByTableName = new Map<string, EntityCollection>();\n private rawCollectionsBySlug = new Map<string, EntityCollection>();\n private rawRootCollections: EntityCollection[] = [];\n private cachedRawCollectionsList: EntityCollection[] | null = null;\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.collectionsByTableName.clear();\n this.collectionsBySlug.clear();\n this.rootCollections = [];\n this.cachedCollectionsList = null;\n\n this.rawCollectionsByTableName.clear();\n this.rawCollectionsBySlug.clear();\n this.rawRootCollections = [];\n this.cachedRawCollectionsList = null;\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 this.reset();\n // Phase 0: Populate maps with raw collections first for string target resolution\n collections.forEach((c) => {\n if (c.slug) {\n this.collectionsBySlug.set(c.slug, c);\n }\n this.collectionsByTableName.set(getTableName(c), c);\n });\n\n const normalizedCollections = collections.map(c => this.normalizeCollection({ ...c }));\n\n // Phase 1: Register all top-level collections first (without recursion).\n // This ensures that injected entityViews (e.g. History tab) are preserved.\n // Without this, _registerRecursively could register a relation-target collection\n // (e.g. Tags from Posts.relations) using the raw module object (without injected views)\n // before the top-level Tags collection (with injected views) gets its turn.\n normalizedCollections.forEach((c, index) => {\n const raw = deepClone(collections[index]);\n this.rootCollections.push(c);\n this.rawRootCollections.push(raw);\n\n const normalized = this.normalizeCollection(c);\n this.collectionsByTableName.set(getTableName(normalized), normalized);\n this.rawCollectionsByTableName.set(getTableName(raw), raw);\n if (normalized.slug) {\n this.collectionsBySlug.set(normalized.slug, normalized);\n }\n if (raw.slug) {\n this.rawCollectionsBySlug.set(raw.slug, raw);\n }\n });\n\n // Phase 2: Now recurse into subcollections (relations, etc.)\n normalizedCollections.forEach((c) => {\n const subcollections = getSubcollections(c);\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n });\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 ? deepClone(rawCollection) : deepClone(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.collectionsByTableName.has(getTableName(collection))) {\n return;\n }\n\n const normalizedCollection = this.normalizeCollection(collection);\n this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);\n this.rawCollectionsByTableName.set(getTableName(rawCollection), 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 // Use the normalized collection for subcollection discovery so that\n // both inline-extracted and explicit relations are considered.\n const subcollections = getSubcollections(normalizedCollection);\n\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n }\n\n public normalizeCollection(collection: EntityCollection): EntityCollection {\n // Work on a shallow copy to avoid mutating the caller's reference.\n // This is critical for idempotency (the raw input must not be changed)\n // and for preventing mutation of module-level collection singletons.\n const result = { ...collection } as EntityCollection;\n\n // 1. Extract relations from properties that have inline config (target set)\n const extractedRelations = this.extractRelationsFromProperties(result.properties);\n\n // 2. Merge with manual relations[] (manual entries win on name conflict)\n const relResult = result as CollectionWithRelations;\n const manualRelations = getDataSourceCapabilities(result.driver).supportsRelations ? (relResult.relations ?? []) : [];\n const mergedRelationsRaw = [...extractedRelations];\n for (const manual of manualRelations) {\n const name = manual.relationName;\n if (!name) {\n mergedRelationsRaw.push(manual);\n } else {\n const existingIndex = mergedRelationsRaw.findIndex(r => r.relationName === name);\n if (existingIndex === -1) {\n mergedRelationsRaw.push(manual);\n } else {\n // Merge manual into existing, preserving custom fields like 'collection'\n mergedRelationsRaw[existingIndex] = {\n ...manual,\n ...mergedRelationsRaw[existingIndex]\n };\n }\n }\n }\n\n let mergedRelations = mergedRelationsRaw;\n\n // 2b. Sanitize each relation so derived fields (through, localKey,\n // foreignKeyOnTarget, etc.) are populated. Without this the\n // property.relation stamp is missing junction-table metadata and\n // the backend cannot fetch many-to-many data.\n if (getDataSourceCapabilities(result.driver).supportsRelations) {\n mergedRelations = mergedRelationsRaw.map(r => {\n try {\n return sanitizeRelation(r, result, (slug) => this.get(slug));\n } catch {\n // sanitizeRelation may throw for incomplete configs\n // (e.g. missing target). Keep the raw relation as-is.\n return r;\n }\n });\n\n // 3. Set the merged relations on the result copy\n relResult.relations = mergedRelations;\n }\n\n // 4. Normalize properties (which stamps relation on each property)\n const properties: Properties = this.normalizeProperties(result.properties, mergedRelations);\n result.properties = properties;\n\n // Populate childCollections from driver-specific fields\n if (!result.childCollections) {\n if (getDataSourceCapabilities(result.driver).supportsSubcollections && (result as CollectionWithSubcollections).subcollections) {\n result.childCollections = (result as CollectionWithSubcollections).subcollections;\n } else if (getDataSourceCapabilities(result.driver).supportsRelations && relResult.relations) {\n const manyRelations = relResult.relations.filter((r: Relation) => r.cardinality === \"many\");\n if (manyRelations.length > 0) {\n result.childCollections = () => manyRelations.map((r: Relation) => {\n const target = r.target();\n return r.overrides ? mergeDeep(target, r.overrides) : target;\n });\n }\n }\n }\n\n return result;\n }\n\n /**\n * Extract Relation[] from properties that have inline relation config (i.e. `target` is set).\n * This allows developers to define relations directly on properties without a separate\n * `relations[]` entry on the collection.\n */\n private extractRelationsFromProperties(properties: Properties): Relation[] {\n const relations: Relation[] = [];\n for (const [key, property] of Object.entries(properties as Record<string, Property>)) {\n if (property.type === \"relation\") {\n const relProp = property as RelationProperty;\n // Support both inline config (target directly on property)\n // and nested config (target inside property.relation)\n const target = relProp.target ?? relProp.relation?.target;\n if (target) {\n const relationName = relProp.relationName ?? relProp.relation?.relationName ?? key;\n relations.push({\n relationName,\n target,\n cardinality: relProp.cardinality ?? relProp.relation?.cardinality ?? \"one\",\n direction: relProp.direction ?? relProp.relation?.direction ?? \"owning\",\n inverseRelationName: relProp.inverseRelationName ?? relProp.relation?.inverseRelationName,\n localKey: relProp.localKey ?? relProp.relation?.localKey,\n foreignKeyOnTarget: relProp.foreignKeyOnTarget ?? relProp.relation?.foreignKeyOnTarget,\n through: relProp.through ?? relProp.relation?.through,\n joinPath: relProp.joinPath ?? relProp.relation?.joinPath,\n onUpdate: relProp.onUpdate ?? relProp.relation?.onUpdate,\n onDelete: relProp.onDelete ?? relProp.relation?.onDelete,\n overrides: relProp.overrides ?? relProp.relation?.overrides,\n });\n }\n } else if (property.type === \"map\" && property.properties) {\n // Recurse into map children to extract nested inline relations\n relations.push(...this.extractRelationsFromProperties(property.properties));\n }\n }\n return relations;\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(key, properties[key], relations);\n }\n return newProperties;\n }\n\n private normalizeProperty(key: string, 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 // Cast to get a properly typed mutable reference\n const arrayProp = newProperty as ArrayProperty;\n if (arrayProp.of) {\n if (Array.isArray(arrayProp.of)) {\n (arrayProp as { of: Property | Property[] }).of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, relations));\n } else {\n arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, relations);\n }\n } else if (arrayProp.oneOf && arrayProp.oneOf.properties) {\n arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.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.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 name = relationProperty.relationName || key;\n const relation = relations.find(r => r.relationName === name);\n if (relation) {\n // we attach the resolved relation to the property\n (relationProperty as RelationProperty & { relation?: Relation }).relation = relation;\n } else {\n console.warn(`Could not find relation for property '${key}' with relationName: ${name}`);\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: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.collectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n // Fallback to table name lookup\n return this.collectionsByTableName.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\n // Fallback: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.rawCollectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n return this.rawCollectionsByTableName.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 if (!getDataSourceCapabilities(currentCollection.driver).supportsRelations) {\n throw new Error(`Relation path navigation requires a collection that supports relations, but '${currentCollection.slug}' uses driver '${currentCollection.driver}'`);\n }\n const resolvedRelations = resolveCollectionRelations(currentCollection);\n const relation = findRelation(resolvedRelations, relationKey);\n\n if (!relation) {\n throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);\n }\n\n // Move to the target collection\n const target = relation.target();\n const targetRelationKey = relation.relationName || target.slug;\n const targetSlug = relation.overrides?.slug ?? targetRelationKey;\n currentCollection = this.get(targetSlug) || this.normalizeCollection(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 if (!this.cachedCollectionsList) {\n this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());\n }\n return this.cachedCollectionsList;\n }\n\n getRawCollections(): EntityCollection[] {\n if (!this.cachedRawCollectionsList) {\n this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());\n }\n return this.cachedRawCollectionsList;\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 = getSubcollections(currentCollection);\n if (!subcollections || subcollections.length === 0) {\n throw new Error(`No subcollections found for ${currentCollection.slug} 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}`);\n }\n currentCollection = this.get(subcollection.slug) || this.normalizeCollection(subcollection);\n collections.push(currentCollection);\n }\n }\n\n return {\n collections,\n entityIds,\n finalCollection: currentCollection\n };\n }\n\n}\n\n","import type { PostgresCollection } from \"@rebasepro/types\";\n\n/**\n * Default users collection.\n *\n * Prepended to the developer's collections array by the admin and server.\n * Slug-based dedup (Map keyed by slug, last-write-wins) lets developers\n * override by defining their own collection with `slug: \"users\"`.\n */\nexport const defaultUsersCollection: PostgresCollection = {\n name: \"Users\",\n singularName: \"User\",\n slug: \"users\",\n table: \"users\",\n schema: \"rebase\",\n icon: \"Users\",\n group: \"Settings\",\n openEntityMode: \"dialog\",\n disableDefaultActions: [\"copy\"],\n sort: [\"createdAt\", \"desc\"],\n properties: {\n id: {\n name: \"ID\",\n type: \"string\",\n isId: \"uuid\",\n ui: { readOnly: true }\n },\n email: {\n name: \"Email\",\n type: \"string\",\n validation: { required: true, unique: true }\n },\n displayName: {\n name: \"Name\",\n type: \"string\",\n columnName: \"display_name\",\n validation: { required: true }\n },\n photoURL: {\n name: \"Photo URL\",\n type: \"string\",\n columnName: \"photo_url\",\n url: \"image\"\n },\n roles: {\n name: \"Roles\",\n type: \"array\",\n columnType: \"text[]\",\n of: {\n name: \"Role\",\n type: \"string\",\n enum: {\n admin: \"Admin\",\n editor: \"Editor\",\n viewer: \"Viewer\"\n }\n }\n },\n passwordHash: {\n name: \"Password Hash\",\n type: \"string\",\n columnName: \"password_hash\",\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n emailVerified: {\n name: \"Email Verified\",\n type: \"boolean\",\n columnName: \"email_verified\",\n defaultValue: false,\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n emailVerificationToken: {\n name: \"Email Verification Token\",\n type: \"string\",\n columnName: \"email_verification_token\",\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n emailVerificationSentAt: {\n name: \"Email Verification Sent At\",\n type: \"date\",\n columnName: \"email_verification_sent_at\",\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n metadata: {\n name: \"Metadata\",\n type: \"map\",\n defaultValue: {},\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n createdAt: {\n name: \"Created At\",\n type: \"date\",\n columnName: \"created_at\",\n ui: { readOnly: true }\n },\n updatedAt: {\n name: \"Updated At\",\n type: \"date\",\n columnName: \"updated_at\",\n autoValue: \"on_update\",\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n }\n },\n listProperties: [\"displayName\", \"email\", \"roles\", \"createdAt\"],\n propertiesOrder: [\"id\", \"email\", \"displayName\", \"roles\", \"createdAt\"]\n};\n","import { FindParams, Entity, FindResponse, CollectionAccessor, QueryBuilderInterface, FilterOperator } from \"@rebasepro/types\";\n\n/**\n * Maps standard operators to Rebase backend's string-based operators\n */\nfunction mapOperator(op: FilterOperator): string {\n switch (op) {\n case \"==\": return \"eq\";\n case \"!=\": return \"neq\";\n case \">\": return \"gt\";\n case \">=\": return \"gte\";\n case \"<\": return \"lt\";\n case \"<=\": return \"lte\";\n case \"array-contains\": return \"cs\";\n case \"array-contains-any\": return \"csa\";\n case \"not-in\": return \"nin\";\n default: return op;\n }\n}\n\nexport class QueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> implements QueryBuilderInterface<M> {\n private params: FindParams = { where: {} };\n\n constructor(private collection: CollectionAccessor<M>) {}\n\n /**\n * Add a filter condition to your query.\n * @example\n * client.collection('users').where('age', '>=', 18).find()\n */\n where(column: keyof M & string, operator: FilterOperator, value: unknown): this {\n if (!this.params.where) {\n this.params.where = {};\n }\n\n const mappedOp = mapOperator(operator);\n let formattedValue = value;\n\n // Handle arrays for in, nin, cs, csa\n if (Array.isArray(value) && [\"in\", \"nin\", \"cs\", \"csa\"].includes(mappedOp)) {\n formattedValue = `(${value.join(\",\")})`;\n } else if (value === null) {\n formattedValue = \"null\";\n }\n\n this.params.where[column] = mappedOp === \"eq\" ? String(formattedValue) : `${mappedOp}.${formattedValue}`;\n return this;\n }\n\n /**\n * Order the results by a specific column.\n * @example\n * client.collection('users').orderBy('createdAt', 'desc').find()\n */\n orderBy(column: keyof M & string, ascending: \"asc\" | \"desc\" = \"asc\"): this {\n this.params.orderBy = `${column}:${ascending}`;\n return this;\n }\n\n /**\n * Limit the number of results returned.\n */\n limit(count: number): this {\n this.params.limit = count;\n return this;\n }\n\n /**\n * Skip the first N results.\n */\n offset(count: number): this {\n this.params.offset = count;\n return this;\n }\n\n /**\n * Set a free-text search string if supported by the backend.\n */\n search(searchString: string): this {\n this.params.searchString = searchString;\n return this;\n }\n\n /**\n * Include related entities in the response.\n * Relations will be populated with full entity data instead of just IDs.\n *\n * @param relations - Relation names to include, or \"*\" for all.\n * @example\n * // Include specific relations\n * client.data.posts.include(\"tags\", \"author\").find()\n *\n * // Include all relations\n * client.data.posts.include(\"*\").find()\n */\n include(...relations: string[]): this {\n this.params.include = relations;\n return this;\n }\n\n /**\n * Execute the find query and return the results.\n */\n async find(): Promise<FindResponse<M>> {\n return this.collection.find(this.params) as Promise<FindResponse<M>>;\n }\n\n /**\n * Listen to realtime updates matching this query.\n */\n listen(onUpdate: (data: FindResponse<M>) => void, onError?: (error: Error) => void): () => void {\n if (!this.collection.listen) {\n throw new Error(\"Listen is only available when RebaseClient is configured with a websocketUrl.\");\n }\n return this.collection.listen(this.params, onUpdate, onError);\n }\n}\n","import {\n DataDriver,\n RebaseData,\n CollectionAccessor,\n FindParams,\n FindResponse,\n Entity,\n EntityValues,\n FilterValues,\n WhereFilterOp,\n WhereFieldValue\n} from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport { QueryBuilder } from \"./query_builder\";\n\n/**\n * Convert where-clause filter object to the internal DataDriver FilterValues format.\n *\n * Supports multiple value formats:\n * - PostgREST string: { status: \"eq.published\", age: \"gte.18\" }\n * - Equality shorthand: { company_profile_id: null, status: \"active\", age: 18 }\n * - Tuple syntax: { age: [\">=\", 18], role: [\"in\", [\"admin\", \"editor\"]] }\n *\n * Internal: { status: [\"==\", \"published\"], age: [\">=\", 18] }\n */\nfunction convertWhereToFilter(where?: Record<string, WhereFieldValue>): FilterValues<string> | undefined {\n if (!where) return undefined;\n\n const operatorMap: Record<string, WhereFilterOp> = {\n \"eq\": \"==\",\n \"neq\": \"!=\",\n \"gt\": \">\",\n \"gte\": \">=\",\n \"lt\": \"<\",\n \"lte\": \"<=\",\n \"in\": \"in\",\n \"nin\": \"not-in\",\n \"not-in\": \"not-in\",\n \"cs\": \"array-contains\",\n \"csa\": \"array-contains-any\",\n \"==\": \"==\",\n\"!=\": \"!=\",\n \">\": \">\",\n\">=\": \">=\",\n \"<\": \"<\",\n\"<=\": \"<=\",\n \"array-contains\": \"array-contains\",\n \"array-contains-any\": \"array-contains-any\"\n };\n\n const filter: FilterValues<string> = {};\n\n for (const [field, rawValue] of Object.entries(where)) {\n // Handle null → equality\n if (rawValue === null) {\n filter[field] = [\"==\", null];\n continue;\n }\n\n // Handle boolean → equality\n if (typeof rawValue === \"boolean\") {\n filter[field] = [\"==\", rawValue];\n continue;\n }\n\n // Handle number → equality\n if (typeof rawValue === \"number\") {\n filter[field] = [\"==\", rawValue];\n continue;\n }\n\n // Handle tuple: [operator, value]\n if (Array.isArray(rawValue) && rawValue.length === 2) {\n const [rawOp, val] = rawValue;\n const mappedOp = operatorMap[rawOp] ?? \"==\";\n filter[field] = [mappedOp, val];\n continue;\n }\n\n // Handle PostgREST string format: \"op.value\"\n if (typeof rawValue === \"string\") {\n const dotIndex = rawValue.indexOf(\".\");\n if (dotIndex === -1) {\n // Plain string equality\n filter[field] = [\"==\", rawValue];\n continue;\n }\n\n const op = rawValue.substring(0, dotIndex);\n let value: unknown = rawValue.substring(dotIndex + 1);\n\n // Parse list values like \"(admin,editor)\"\n if (typeof value === \"string\" && value.startsWith(\"(\") && value.endsWith(\")\")) {\n value = value.slice(1, -1).split(\",\").map((v: string) => v.trim());\n }\n\n // Parse null string\n if (value === \"null\") {\n value = null;\n }\n // Parse boolean strings\n else if (value === \"true\") {\n value = true;\n } else if (value === \"false\") {\n value = false;\n }\n // Try to parse numbers\n else if (typeof value === \"string\" && !isNaN(Number(value)) && value.trim() !== \"\") {\n value = Number(value);\n }\n\n const mappedOp = operatorMap[op];\n if (mappedOp) {\n filter[field] = [mappedOp, value];\n }\n }\n }\n\n return Object.keys(filter).length > 0 ? filter : undefined;\n}\n\n/**\n * Parse an orderBy string like \"created_at:desc\" into [field, direction].\n */\nfunction parseOrderBy(orderBy?: string): [string, \"asc\" | \"desc\"] | undefined {\n if (!orderBy) return undefined;\n const parts = orderBy.split(\":\");\n const field = parts[0];\n const direction = (parts[1] as \"asc\" | \"desc\") || \"asc\";\n return [field, direction];\n}\n\nfunction createDriverAccessor<M extends Record<string, unknown> = Record<string, unknown>>(\n driver: DataDriver,\n slug: string\n): CollectionAccessor<M> {\n const accessor: CollectionAccessor<M> = {\n async find(params?: FindParams): Promise<FindResponse<M>> {\n const orderParsed = parseOrderBy(params?.orderBy);\n const entities = await driver.fetchCollection<M>({\n path: slug,\n limit: params?.limit,\n offset: params?.offset,\n filter: convertWhereToFilter(params?.where),\n orderBy: orderParsed?.[0],\n order: orderParsed?.[1],\n searchString: params?.searchString\n });\n const limit = params?.limit ?? 20;\n const offset = params?.offset ?? 0;\n return {\n data: entities,\n meta: {\n total: entities.length,\n limit,\n offset,\n hasMore: entities.length >= limit\n }\n };\n },\n\n async findById(id: string | number): Promise<Entity<M> | undefined> {\n return driver.fetchEntity<M>({ path: slug,\nentityId: id });\n },\n\n async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {\n return driver.saveEntity<M>({\n path: slug,\n values: data,\n entityId: id,\n status: \"new\"\n });\n },\n\n async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {\n return driver.saveEntity<M>({\n path: slug,\n values: data,\n entityId: id,\n status: \"existing\"\n });\n },\n\n async delete(id: string | number): Promise<void> {\n return driver.deleteEntity({\n entity: { id,\npath: slug,\nvalues: {} as Record<string, unknown> }\n });\n },\n\n deleteAll: driver.deleteAll\n ? async (): Promise<void> => {\n return driver.deleteAll!(slug);\n }\n : undefined,\n\n count: driver.countEntities\n ? async (params?: FindParams): Promise<number> => {\n return driver.countEntities!({\n path: slug,\n filter: convertWhereToFilter(params?.where)\n });\n }\n : undefined,\n\n listen: driver.listenCollection\n ? (params: FindParams | undefined, onUpdate: (response: FindResponse<M>) => void, onError?: (error: Error) => void) => {\n const orderParsed = parseOrderBy(params?.orderBy);\n const limit = params?.limit ?? 20;\n const offset = params?.offset ?? 0;\n return driver.listenCollection!<M>({\n path: slug,\n limit: params?.limit,\n offset: params?.offset,\n filter: convertWhereToFilter(params?.where),\n orderBy: orderParsed?.[0],\n order: orderParsed?.[1],\n searchString: params?.searchString,\n onUpdate: (entities) => {\n onUpdate({\n data: entities,\n meta: {\n total: entities.length,\n limit,\n offset,\n hasMore: entities.length >= limit\n }\n });\n },\n onError\n });\n } : undefined,\n\n listenById: driver.listenEntity\n ? (id: string | number, onUpdate: (entity: Entity<M> | undefined) => void, onError?: (error: Error) => void) => {\n return driver.listenEntity!<M>({\n path: slug,\n entityId: id,\n onUpdate: (entity) => onUpdate(entity ?? undefined),\n onError\n });\n } : undefined,\n\n // Fluent Query Builder\n where(column: keyof M & string, operator: WhereFilterOp, value: unknown) {\n return new QueryBuilder<M>(accessor).where(column, operator, value);\n },\n orderBy(column: keyof M & string, ascending?: \"asc\" | \"desc\") {\n return new QueryBuilder<M>(accessor).orderBy(column, ascending);\n },\n limit(count: number) {\n return new QueryBuilder<M>(accessor).limit(count);\n },\n offset(count: number) {\n return new QueryBuilder<M>(accessor).offset(count);\n },\n search(searchString: string) {\n return new QueryBuilder<M>(accessor).search(searchString);\n },\n include(...relations: string[]) {\n return new QueryBuilder<M>(accessor).include(...relations);\n }\n };\n\n return accessor;\n}\n\n/**\n * Build a `RebaseData` object from a `DataDriver` using JavaScript Proxy.\n *\n * This is the key bridge: any property access like `data.products` returns\n * a `CollectionAccessor` backed by the underlying DataDriver, without\n * needing per-collection code generation.\n *\n * @example\n * const data = buildRebaseData(driver);\n * await data.products.create({ name: \"Camera\", price: 299 });\n * const { data: items } = await data.products.find({ where: { status: \"eq.published\" } });\n */\nexport function buildRebaseData(driver: DataDriver): RebaseData {\n const cache = new Map<string, CollectionAccessor>();\n\n function getAccessor(slug: string): CollectionAccessor {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = createDriverAccessor(driver, slug);\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = {\n collection: getAccessor\n } as RebaseData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n // Ignore Symbol properties (e.g. Symbol.toPrimitive, Symbol.iterator)\n if (typeof prop === \"symbol\") return undefined;\n // Ignore internal JS properties\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n\n // Convert camelCase property names to snake_case slugs\n const slug = toSnakeCase(prop);\n return getAccessor(slug);\n }\n });\n}\n"],"names":["DEFAULT_ONE_OF_TYPE","DEFAULT_ONE_OF_VALUE","isReadOnly","property","ui","readOnly","type","autoValue","path","Field","isHidden","disabled","Boolean","hidden","isPropertyBuilder","dynamicProps","getDefaultValuesFor","properties","Object","entries","map","key","value","getDefaultValueFor","undefined","reduce","a","b","defaultValue","defaultValuesFor","keys","length","getDefaultValueFortype","updateDateAutoValues","inputValues","status","timestampNowValue","traverseValuesProperties","inputValue","sanitizeData","values","result","forEach","validation","required","getReferenceFrom","entity","id","Error","EntityReference","driver","databaseId","getRelationFrom","EntityRelation","normalizeToEntityRelation","Array","isArray","obj","isRelationLike","__type","isEntityRelation","isEntityReference","data","operation","safeInputValues","updatedValues","updatedValue","traverseValueProperty","mergeDeep","of","e","i","filter","oneOf","typeField","valueField","rec","childProperty","createRelationRef","createRelationRefWithData","sortProperties","propertiesOrder","propertiesKeys","validOrderKeys","includes","processedKeys","Set","orderedResult","missingProperties","has","console","error","resolveDefaultSelectedView","defaultSelectedView","params","getLocalChangesBackup","collection","localChangesBackup","getPrimaryKeys","ids","prop","isId","enumToObjectEntries","enumValues","label","getLabelOrConfigFrom","find","entry","String","COLLECTION_PATH_SEPARATOR","stripCollectionPath","segmentsToStrippedPath","fullPathToCollectionSegments","paths","split","sanitizeRelation","relation","sourceCollection","resolveCollection","target","rawTarget","targetCollection","slug","name","evaluated","newRelation","relationName","toSnakeCase","direction","foreignKeyOnTarget","through","cardinality","joinPath","sourceName","localKey","generateForeignKeyName","foundForeignKey","targetRelations","getDataSourceCapabilities","supportsRelations","relations","targetRel","targetRelTarget","keyPrefix","inverseRelationName","isManyToManyInverse","propKey","relProp","relName","sourceTableName","getTableName","targetTableName","table","sort","join","sourceColumn","targetColumn","_resolvedRelationsCache","WeakMap","resolveCollectionRelations","cached","get","relCollection","registeredRelationNames","normalizedRelation","relationKey","add","resolvePropertyRelation","propertyKey","set","onUpdate","onDelete","overrides","warn","getTableVarName","tableName","replace","_","char","toUpperCase","getEnumVarName","propName","tableVar","propVar","charAt","slice","getColumnName","fullColumn","pop","findRelation","resolvedRelations","slugKey","snakeKey","resolveProperty","props","ignoreMissingFields","rest","resultProperty","usedPropertyValue","getIn","propertyValue","previousValues","dynamicPropsResult","resolvedProperty","resolveProperties","enum","resolvePropertyEnum","propertyConfig","isDefaultFieldConfigId","cmsFields","propertyConfigs","customField","restConfigProperty","customFieldProperty","resolveRelationProperty","rel","childResolvedProperty","resolveArrayProperties","p","index","resolvedProperties","getArrayResolvedProperties","ofProperty","v","resolveEnumValues","input","getSubcollections","childCollections","supportsSubcollections","subcollections","manyRelations","r","customName","baseOverrides","singularName","targetWithOverrides","c","evaluateAST","sqlString","auth","cleanedSQL","trim","startsWith","endsWith","openCount","isEnclosing","substring","splitByTopLevel","str","delimiter","parts","current","push","orParts","some","part","andParts","every","upperSQL","roleIntersectMatch","match","requiredRoles","userRoles","user","roles","roleContainMatch","pattern1","RegExp","pattern2","match1","uid","match2","simpleEqualityMatch","field","operator","entityValue","evaluateRule","rule","access","ownerField","using","withCheck","checkOperation","authController","targetOperation","securityRules","supportsRLS","applicableRules","operations","userRoleIds","roleApplicableRules","grantedByPermissive","deniedByRestrictive","mode","passed","hasPermissive","canReadCollection","canEditEntity","canCreateEntity","canDeleteEntity","getEntityImagePreviewPropertyKey","storage","acceptedFiles","url","removeInitialAndTrailingSlashes","s","removeInitialSlash","removeTrailingSlash","addInitialSlash","getLastSegment","cleanPath","segments","resolveCollectionPathIds","allCollections","remainingPath","currentCollections","resolvedPathParts","foundMatch","potentialMatches","flatMap","col","foundCollection","matchString","idSeparatorIndex","indexOf","entityId","getCollectionBySlugWithin","slugOrPath","collections","subpaths","subpathCombinations","getCollectionPathsCombinations","subpathCombination","navigationEntry","localeCompare","newPath","splice","getNavigationEntriesFromPath","currentFullPath","collectionPath","restOfThePath","nextSegments","parentCollection","entityViews","customView","resolveEntityView","contextEntityViews","view","entityView","getParentReferencesFromPath","buildCollection","buildProperty","buildProperties","buildPropertiesOrBuilder","propertiesOrBuilder","buildEnum","buildEnumValueConfig","enumValueConfig","buildEntityCallbacks","callbacks","buildAdditionalFieldDelegate","additionalFieldDelegate","resolveStorageFilenameString","file","replacePlaceholders","randomString","resolveStoragePathString","ext","hasPropertyCallbacks","callbackName","ofs","processProperties","propsContext","currentValue","previousValue","Promise","all","item","prevItem","singlePropData","res","cbRes","resolve","buildPropertyCallbacks","propertyCallbacks","afterRead","processedValues","beforeSave","acc","operationsRegistered","registerConditionOperations","jsonLogic","add_operation","roleId","roleIds","role","timestamp","date","Date","today","getFullYear","getMonth","getDate","now","evaluateCondition","context","apply","serializeValueForConditions","getTime","toMillis","toDate","buildConditionContext","serializedValues","serializedPreviousValues","isNew","email","displayName","photoURL","applyPropertyConditions","conditions","isDisabled","clearOnDisabled","disabledMessage","isRequired","requiredMessage","enumConditions","allowedEnumValues","excludedEnumValues","applyEnumConditions","referencePath","referenceFilter","fixedFilter","canAddElements","sortable","objectToArray","k","isNaN","Number","allowed","allowedArray","ev","excluded","excludedArray","evConditions","CollectionRegistry","collectionsByTableName","Map","collectionsBySlug","rootCollections","cachedCollectionsList","rawCollectionsByTableName","rawCollectionsBySlug","rawRootCollections","cachedRawCollectionsList","lastRawInputSnapshot","constructor","registerMultiple","reset","clear","rawSnapshot","removeFunctions","deepEqual","normalizedCollections","normalizeCollection","raw","deepClone","normalized","subCollection","_registerRecursively","register","rawCollection","normalizedCollection","extractedRelations","extractRelationsFromProperties","relResult","manualRelations","mergedRelationsRaw","manual","existingIndex","findIndex","mergedRelations","normalizeProperties","newProperties","normalizeProperty","newProperty","arrayProp","stringOrNumberProperty","relationProperty","bySlug","byNormalized","getRaw","getCollectionByPath","pathSegments","rootCollectionPath","currentCollection","targetRelationKey","targetSlug","getCollections","from","getRawCollections","resolvePathToCollections","entityIds","subcollectionSlug","subcollection","finalCollection","defaultUsersCollection","schema","icon","group","openEntityMode","disableDefaultActions","unique","columnName","columnType","admin","editor","viewer","passwordHash","hideFromCollection","emailVerified","emailVerificationToken","emailVerificationSentAt","metadata","createdAt","updatedAt","listProperties","mapOperator","op","QueryBuilder","where","column","mappedOp","formattedValue","orderBy","ascending","limit","count","offset","search","searchString","include","listen","onError","convertWhereToFilter","operatorMap","rawValue","rawOp","val","dotIndex","parseOrderBy","createDriverAccessor","accessor","orderParsed","entities","fetchCollection","order","meta","total","hasMore","findById","fetchEntity","create","saveEntity","update","delete","deleteEntity","deleteAll","countEntities","listenCollection","listenById","listenEntity","buildRebaseData","cache","getAccessor","Proxy","_target"],"mappings":";;;;AAAO,MAAMA,sBAAsB;AAC5B,MAAMC,uBAAuB;ACY7B,SAASC,WAAWC,UAA6B;AACpD,MAAIA,SAASC,IAAIC,SACb,QAAO;AACX,MAAIF,SAASG,SAAS,QAAQ;AAC1B,QAAIH,SAASI,UACT,QAAO;AAAA,EACf;AACA,MAAIJ,SAASG,SAAS,aAAa;AAC/B,WAAO,CAACH,SAASK,QAAQ,EAAE,YAAYL,SAASC,MAAM,OAAOD,SAASC,IAAIK;AAAAA,EAC9E;AACA,SAAO;AACX;AAEO,SAASC,SAASP,UAA6B;AAClD,SAAO,OAAOA,SAASC,IAAIO,aAAa,YAAYC,QAAQT,SAASC,IAAIO,SAASE,MAAM;AAC5F;AAEO,SAASC,kBAAkBX,UAAqB;AACnD,SAAO,OAAOA,UAAUY,iBAAiB;AAC7C;AAEO,SAASC,oBAAuDC,YAAkD;AACrH,MAAI,CAACA,WAAY,QAAO,CAAA;AACxB,SAAOC,OAAOC,QAAQF,UAAU,EAC3BG,IAAI,CAAC,CAACC,KAAKlB,QAAQ,MAAM;AACtB,QAAI,CAACA,SAAU,QAAO,CAAA;AACtB,UAAMmB,QAAQC,mBAAmBpB,QAAQ;AACzC,WAAOmB,UAAUE,SAAY,KAAK;AAAA,MAAE,CAACH,GAAG,GAAGC;AAAAA,IAAAA;AAAAA,EAC/C,CAAC,EACAG,OAAO,CAACC,GAAGC,OAAO;AAAA,IAAE,GAAGD;AAAAA,IAChC,GAAGC;AAAAA,EAAAA,IAAM,CAAA,CAAE;AACX;AAEO,SAASJ,mBAAmBpB,UAA8B;AAC7D,MAAI,CAACA,SAAU,QAAOqB;AACtB,MAAIV,kBA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OAAOD,KAAK;AAAA,IACrD;AAAA,IACAE,OAAOC,cAAsB;AACzB,aAAO,IAAIX,aAAgBuB,QAAQ,EAAEb,OAAOC,YAAY;AAAA,IAC5D;AAAA,IACAC,WAAWhZ,WAAqB;AAC5B,aAAO,IAAIoY,aAAgBuB,QAAQ,EAAEX,QAAQ,GAAGhZ,SAAS;AAAA,IAC7D;AAAA,EAAA;AAGJ,SAAO2Z;AACX;AAcO,SAASoB,gBAAgBzgB,QAAgC;AAC5D,QAAM0gB,4BAAY9H,IAAAA;AAElB,WAAS+H,YAAYnc,MAAkC;AACnD,QAAI6a,WAAWqB,MAAM3Z,IAAIvC,IAAI;AAC7B,QAAI,CAAC6a,UAAU;AACXA,iBAAWD,qBAAqBpf,QAAQwE,IAAI;AAC5Ckc,YAAMnZ,IAAI/C,MAAM6a,QAAQ;AAAA,IAC5B;AACA,WAAOA;AAAAA,EACX;AAEA,QAAMhb,SAAS;AAAA,IACXvB,YAAY6d;AAAAA,EAAAA;AAGhB,SAAO,IAAIC,MAAMvc,QAAQ;AAAA,IACrB0C,IAAI8Z,SAAS3d,MAAuB;AAChC,UAAIA,SAAS,aAAc,QAAOyd;AAElC,UAAI,OAAOzd,SAAS,SAAU,QAAO5E;AAErC,UAAI4E,SAAS,UAAUA,SAAS,YAAYA,SAAS,WAAY,QAAO5E;AAGxE,YAAMkG,OAAOK,YAAY3B,IAAI;AAC7B,aAAOyd,YAAYnc,IAAI;AAAA,IAC3B;AAAA,EAAA,CACH;AACL;"}
1
+ {"version":3,"file":"index.es.js","sources":["../src/util/common.ts","../src/util/entities.ts","../src/util/collections.ts","../src/util/enums.ts","../src/util/paths.ts","../src/util/relations.ts","../src/util/resolutions.ts","../src/util/permissions.ts","../src/util/references.ts","../src/util/navigation_utils.ts","../src/util/navigation_from_path.ts","../src/util/parent_references_from_path.ts","../src/util/builders.ts","../src/util/storage.ts","../src/util/callbacks.ts","../src/util/conditions.ts","../src/collections/CollectionRegistry.ts","../src/collections/default-collections.ts","../src/data/query_builder.ts","../src/data/buildRebaseData.ts"],"sourcesContent":["export const DEFAULT_ONE_OF_TYPE = \"type\"\nexport const DEFAULT_ONE_OF_VALUE = \"value\"\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 \"@rebasepro/utils\";\n\nexport function isReadOnly(property: Property): boolean {\n if (property.ui?.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 && !(\"Field\" in (property.ui || {}) && property.ui?.Field);\n }\n return false;\n}\n\nexport function isHidden(property: Property): boolean {\n return typeof property.ui?.disabled === \"object\" && Boolean(property.ui?.disabled.hidden);\n}\n\nexport function isPropertyBuilder(property?: Property) {\n return typeof property?.dynamicProps === \"function\";\n}\n\nexport function getDefaultValuesFor<M extends Record<string, unknown>>(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,\n...b }), {}) as EntityValues<M>;\n}\n\nexport function getDefaultValueFor(property?: Property): unknown {\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): unknown {\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 if (type === \"vector\") {\n return null;\n } else if (type === \"binary\") {\n return null;\n } else {\n return null;\n }\n}\n\n/**\n * Update the automatic values in an entity before save\n * @group Driver\n */\nexport function updateDateAutoValues<M extends Record<string, unknown>>({\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 Driver\n */\nexport function sanitizeData<M extends Record<string, unknown>>\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, unknown>>(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 driver: entity.driver,\n databaseId: entity.databaseId\n });\n}\n\nexport function getRelationFrom<M extends Record<string, unknown>>(entity: Entity<M>): EntityRelation {\n return new EntityRelation(entity.id, entity.path, entity);\n}\n\n/**\n * Normalize a value into a proper EntityRelation instance.\n * Handles EntityRelation class instances, and plain objects\n * with `__type === \"relation\"` or an `isEntityRelation()` method.\n *\n * Returns null if the value cannot be coerced.\n */\nexport function normalizeToEntityRelation(value: unknown): EntityRelation | null {\n if (value instanceof EntityRelation) return value;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\n const obj = value as Record<string, unknown>;\n const isRelationLike =\n obj.__type === \"relation\" ||\n obj.__type === \"reference\" ||\n (typeof obj.isEntityRelation === \"function\" && (obj.isEntityRelation as () => boolean)()) ||\n (typeof obj.isEntityReference === \"function\" && (obj.isEntityReference as () => boolean)());\n\n if (!isRelationLike) return null;\n\n return new EntityRelation(\n obj.id as string | number,\n obj.path as string,\n obj.data as Entity | undefined\n );\n}\n\nexport function traverseValuesProperties<M extends Record<string, unknown>>(\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,\n...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\n/**\n * Relation reference types used throughout the server layer.\n * These replace the 50+ manual `{ id, path, __type: \"relation\" }` constructions.\n */\nexport interface RelationRef {\n readonly id: string | number;\n readonly path: string;\n readonly __type: \"relation\";\n}\n\nexport interface RelationRefWithData extends RelationRef {\n readonly data: Entity;\n}\n\n/**\n * Create a lightweight relation stub for CMS views.\n * Replaces inline `{ id, path, __type: \"relation\" }` object literals.\n */\nexport function createRelationRef(id: string | number, path: string): RelationRef {\n return { id, path, __type: \"relation\" };\n}\n\n/**\n * Create a hydrated relation reference that includes the full entity data.\n * Used when entity data has been pre-fetched (e.g., via batch loading or JOINs).\n */\nexport function createRelationRefWithData(id: string | number, path: string, data: Entity): RelationRefWithData {\n return { id, path, __type: \"relation\", data };\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, unknown>>(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,\n...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: Properties, b: Properties) => ({ ...a,\n...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: Properties, b: Properties) => ({ ...a,\n...b }), {}) as Properties;\n\n return { ...orderedResult,\n...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\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, unknown>>(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","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","import { CollectionWithRelations, EntityCollection, getDataSourceCapabilities, Property, Relation, RelationProperty } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport { generateForeignKeyName } from \"@rebasepro/utils\";\n\nexport function sanitizeRelation(\n relation: Partial<Relation>,\n sourceCollection: EntityCollection,\n resolveCollection?: (slugOrTable: string) => EntityCollection | undefined\n): Relation {\n if (!relation.target) {\n throw new Error(\"Relation is missing a `target` collection.\");\n }\n\n const rawTarget = relation.target;\n let targetCollection: EntityCollection | undefined;\n\n if (typeof rawTarget === \"string\") {\n if (resolveCollection) {\n targetCollection = resolveCollection(rawTarget);\n }\n if (!targetCollection) {\n targetCollection = { slug: rawTarget, name: rawTarget } as EntityCollection;\n }\n } else if (typeof rawTarget === \"function\") {\n const evaluated = rawTarget();\n if (typeof evaluated === \"string\") {\n if (resolveCollection) {\n targetCollection = resolveCollection(evaluated);\n }\n if (!targetCollection) {\n targetCollection = { slug: evaluated, name: evaluated } as EntityCollection;\n }\n } else {\n targetCollection = evaluated;\n }\n } else if (rawTarget && typeof rawTarget === \"object\") {\n targetCollection = rawTarget as EntityCollection;\n }\n\n if (!targetCollection) {\n throw new Error(\"Relation is missing a valid `target` collection.\");\n }\n\n const newRelation: Partial<Relation> = { ...relation };\n\n newRelation.target = () => {\n if (typeof rawTarget === \"string\") {\n return (resolveCollection && resolveCollection(rawTarget)) || targetCollection!;\n } else if (typeof rawTarget === \"function\") {\n const evaluated = rawTarget();\n if (typeof evaluated === \"string\") {\n return (resolveCollection && resolveCollection(evaluated)) || targetCollection!;\n }\n return evaluated;\n }\n return targetCollection!;\n };\n\n // 1. Default relationName from target collection slug\n if (!newRelation.relationName) {\n newRelation.relationName = toSnakeCase(targetCollection.slug);\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 = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? (((targetCollection as CollectionWithRelations).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 // 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 // Note: we intentionally do NOT require `through` here because the raw (unsanitized)\n // relations won't have `through` populated yet — sanitizeRelation fills it in later.\n // `cardinality: \"many\" + direction: \"owning\"` is sufficient to identify owning M2M.\n\n // 1. Check the explicit relations[] array\n const targetRelations = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? (((targetCollection as CollectionWithRelations).relations) || []) : [];\n for (const targetRel of targetRelations) {\n if (targetRel.cardinality === \"many\" &&\n (targetRel.direction === \"owning\" || !targetRel.direction) &&\n (targetRel.relationName === newRelation.inverseRelationName)) {\n isManyToManyInverse = true;\n break;\n }\n }\n\n // 2. Also check the target's properties for inline relation definitions\n // (e.g. posts.properties.tags = { type: \"relation\", cardinality: \"many\", direction: \"owning\" })\n if (!isManyToManyInverse && targetCollection.properties) {\n for (const [propKey, prop] of Object.entries(targetCollection.properties)) {\n if ((prop as Property).type !== \"relation\") continue;\n const relProp = prop as RelationProperty;\n const relName = relProp.relationName || propKey;\n if (relName === newRelation.inverseRelationName &&\n relProp.cardinality === \"many\" &&\n (relProp.direction === \"owning\" || !relProp.direction)) {\n isManyToManyInverse = true;\n break;\n }\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 && !newRelation.inverseRelationName) {\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\n/** WeakMap cache — same collection instance always yields the same relation map. */\nconst _resolvedRelationsCache = new WeakMap<EntityCollection, Record<string, Relation>>();\n\nexport function resolveCollectionRelations(\n collection: EntityCollection\n): Record<string, Relation> {\n const cached = _resolvedRelationsCache.get(collection);\n if (cached) return cached;\n\n if (!getDataSourceCapabilities(collection.driver).supportsRelations) return {};\n const relCollection = collection as CollectionWithRelations;\n const relations: Record<string, Relation> = {};\n\n // Track which explicit relationName values have been registered so that\n // property-based entries in section 2 don't re-add the same underlying relation\n // under a different key (e.g. explicit \"company\" + property \"company_id\").\n const registeredRelationNames = new Set<string>();\n\n // 1. Process explicit relations from the `relations` field.\n // Each relation is stored once under its canonical relationName key.\n if (relCollection.relations) {\n relCollection.relations.forEach((relation: Relation) => {\n try {\n const normalizedRelation = sanitizeRelation(relation, collection);\n const relationKey = normalizedRelation.relationName;\n if (relationKey) {\n relations[relationKey] = normalizedRelation;\n registeredRelationNames.add(relationKey);\n }\n } catch (e) {\n // Ignore incomplete or invalid relations (e.g. missing target during registry setup)\n }\n });\n }\n\n // 2. Process properties of type \"relation\".\n // Only adds an entry if:\n // (a) the property key itself is not already in the map, AND\n // (b) the underlying relation (by relationName) hasn't already been registered.\n // This prevents duplicate entries when a property key differs from the\n // explicit relation's relationName (e.g. property \"company_id\" referencing\n // explicit relation \"company\").\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 // Skip if the property key is already registered\n if (relations[propKey]) return;\n\n // We previously skipped if the underlying relation was already registered under\n // its canonical relationName in section 1. But we need to keep the property mapping\n // for EntityFetchService to hydrate the relation back to the correct property key.\n // Deduplication for Drizzle schema generation is handled in generate-drizzle-schema-logic.ts.\n\n if (!relation.relationName) {\n relation.relationName = propKey;\n }\n const normalizedRelation = sanitizeRelation(relation, collection);\n relations[propKey] = normalizedRelation;\n registeredRelationNames.add(normalizedRelation.relationName ?? propKey);\n }\n });\n }\n\n _resolvedRelationsCache.set(collection, relations);\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 relProp = property as RelationProperty;\n\n // If the property has inline config (target set), build a Relation from it.\n // We only support the flat format where properties are directly on the RelationProperty.\n if (relProp.target) {\n return {\n relationName: relProp.relationName || propertyKey,\n target: relProp.target,\n cardinality: relProp.cardinality || \"one\",\n direction: relProp.direction || \"owning\",\n inverseRelationName: relProp.inverseRelationName,\n localKey: relProp.localKey,\n foreignKeyOnTarget: relProp.foreignKeyOnTarget,\n through: relProp.through,\n joinPath: relProp.joinPath,\n onUpdate: relProp.onUpdate,\n onDelete: relProp.onDelete,\n overrides: relProp.overrides,\n } as Relation;\n }\n\n console.warn(`Unrecognized or missing relation target for property '${propertyKey}' in collection '${sourceCollection.slug}'`);\n return undefined;\n}\n\nexport function getTableName(collection: EntityCollection): string {\n if (getDataSourceCapabilities(collection.driver).supportsRelations) {\n return (collection as CollectionWithRelations).table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);\n }\n return 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\n/**\n * Look up a relation by key with forgiving normalization.\n *\n * `resolveCollectionRelations` stores each relation under a single canonical\n * key (no aliases). This helper tries the given key as-is, then falls back to\n * slug form (underscores → hyphens) and snake_case form (hyphens → underscores)\n * so that callers that receive a key from external input (URL path segments,\n * user-provided config, etc.) can still find the right entry.\n */\nexport function findRelation(\n resolvedRelations: Record<string, Relation>,\n key: string\n): Relation | undefined {\n // Exact match first\n if (resolvedRelations[key]) return resolvedRelations[key];\n\n // Try slug form (e.g. \"company_id\" → \"company-id\")\n const slugKey = key.replace(/_/g, \"-\");\n if (slugKey !== key && resolvedRelations[slugKey]) return resolvedRelations[slugKey];\n\n // Try snake_case form (e.g. \"company-id\" → \"company_id\")\n const snakeKey = key.replace(/-/g, \"_\");\n if (snakeKey !== key && resolvedRelations[snakeKey]) return resolvedRelations[snakeKey];\n\n return undefined;\n}\n","import {\n ArrayProperty,\n AuthController,\n CollectionWithRelations,\n CollectionWithSubcollections,\n EntityCollection,\n EnumValueConfig,\n EnumValues,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty,\n getDataSourceCapabilities\n} from \"@rebasepro/types\";\n\ntype PropertyConfig = { property: unknown; [key: string]: unknown };\nimport { isPropertyBuilder } from \"./entities\";\nimport { enumToObjectEntries } from \"./enums\";\nimport { DEFAULT_ONE_OF_TYPE } from \"./common\";\nimport { isDefaultFieldConfigId } from \"@rebasepro/utils\";\nimport { getIn, mergeDeep } from \"@rebasepro/utils\";\nimport { resolveCollectionRelations } from \"./relations\";\n\n/**\n * Resolve property builders, enums and arrays.\n */\n\nexport type ResolvePropertyProps<M extends Record<string, unknown> = Record<string, unknown>> = {\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, unknown> = Record<string, unknown>>(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 // When path is not available (e.g. in preview contexts), skip dynamic\n // resolution and use the property as-is without dynamic modifications.\n resultProperty = property as Property;\n } else {\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 }\n } else {\n resultProperty = property as Property;\n }\n\n // Apply dynamic properties if they exist\n if (resultProperty?.dynamicProps && rest.path) {\n const path = rest.path;\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 restConfigProperty = { ...customField.property } as Record<string, unknown>;\n delete restConfigProperty.propertyConfig;\n const customFieldProperty = resolveProperty({\n property: { name: \"\",\n...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[], propertyKey?: string) {\n // If the property already has a resolved relation, return as-is\n if (property.relation) {\n return property;\n }\n\n // Determine the relation name: explicit > property key\n const name = property.relationName || propertyKey;\n\n // Find the relation by name (it may have been extracted from the property during normalization)\n const relation = name ? relations.find((rel) => rel.relationName === name) : undefined;\n if (!relation) {\n throw Error(`Relation ${name ?? \"(unnamed)\"} 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, unknown>>({\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,\n...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 (!(\"Field\" in (property.ui || {}) && property.ui?.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\n\nexport function getSubcollections<M extends Record<string, unknown> = Record<string, unknown>>(collection: EntityCollection<M>): EntityCollection<Record<string, unknown>>[] {\n if (collection.childCollections) {\n return collection.childCollections() ?? [];\n }\n\n if (getDataSourceCapabilities(collection.driver).supportsSubcollections && (collection as CollectionWithSubcollections).subcollections) {\n return (collection as CollectionWithSubcollections).subcollections!() ?? [];\n }\n\n if (getDataSourceCapabilities(collection.driver).supportsRelations) {\n const resolvedRelations = resolveCollectionRelations(collection);\n const manyRelations = Object.values(resolvedRelations).filter((r: Relation) => r.cardinality === \"many\");\n \n return manyRelations.map((r: Relation) => {\n const target = r.target();\n if (!target) return undefined;\n const relationKey = r.relationName || target.slug;\n\n // Try to find corresponding property to get custom name\n let customName: string | undefined;\n if (collection.properties) {\n const prop = Object.entries(collection.properties as Record<string, Property>).find(\n ([_, p]) => p.type === \"relation\" && p.relationName === relationKey\n );\n if (prop && prop[1].name) {\n customName = prop[1].name;\n }\n }\n\n const baseOverrides: Partial<EntityCollection> = { slug: relationKey };\n if (customName) {\n baseOverrides.name = customName;\n baseOverrides.singularName = customName;\n }\n\n const targetWithOverrides = { ...target, ...baseOverrides };\n return (r.overrides ? mergeDeep(targetWithOverrides, r.overrides) : targetWithOverrides) as EntityCollection<Record<string, unknown>>;\n }).filter((c: EntityCollection<Record<string, unknown>> | undefined): c is EntityCollection<Record<string, unknown>> => Boolean(c));\n }\n\n return [];\n}\n","import { AuthController, CollectionWithRelations, Entity, EntityCollection, getDataSourceCapabilities, SecurityRule, User } from \"@rebasepro/types\";\n\nfunction evaluateAST<USER extends User, M extends Record<string, unknown>>(sqlString: string, auth: AuthController<USER>, entity: Entity<M> | 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<USER extends User, M extends Record<string, unknown>>(rule: SecurityRule, auth: AuthController<USER>, entity: Entity<M> | 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\nexport function checkOperation<M extends Record<string, unknown>, USER extends User>(\n collection: EntityCollection<M>,\n authController: AuthController<USER>,\n entity: Entity<M> | null,\n targetOperation: \"select\" | \"insert\" | \"update\" | \"delete\"\n): boolean {\n const securityRules = getDataSourceCapabilities(collection.driver).supportsRLS ? (collection as CollectionWithRelations).securityRules : undefined;\n if (!securityRules || 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 = securityRules.filter((r: SecurityRule) =>\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: SecurityRule) => {\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: SecurityRule) => (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, unknown>, 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, unknown>, 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, unknown>, 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, \"insert\");\n}\n\nexport function canDeleteEntity<M extends Record<string, unknown>, 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","import { EntityCollection } from \"@rebasepro/types\";\n\nexport function getEntityImagePreviewPropertyKey<M extends Record<string, unknown>>(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.ui?.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 && !Array.isArray(property.of) && property.of.type === \"string\" && property.of.url === \"image\") {\n return key;\n }\n }\n // fallback: any storage property without explicit acceptedFiles (e.g. a generic \"picture\" field)\n for (const key in collection.properties) {\n const property = collection.properties[key];\n if (property.type === \"string\" && property.storage && !property.storage.acceptedFiles) {\n return key;\n }\n }\n // fallback: any array of storage properties without explicit acceptedFiles\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 && !property.of.storage.acceptedFiles) {\n return key;\n }\n }\n return undefined;\n}\n","import { EntityCollection } from \"@rebasepro/types\";\n\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.slug); // 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 (getSubcollections(navigationEntry).length > 0) {\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","import { EntityCollection } from \"@rebasepro/types\";\ntype EntityCustomView<M extends Record<string, unknown> = Record<string, unknown>> = { key: string; [key: string]: unknown };\nimport { getCollectionPathsCombinations, removeInitialAndTrailingSlashes } from \"./navigation_utils\";\nimport { getSubcollections } from \"./resolutions\";\n\nexport type NavigationViewInternal<M extends Record<string, unknown> = Record<string, unknown>> =\n | NavigationViewEntityInternal<M>\n | NavigationViewCollectionInternal<M>\n | NavigationViewEntityCustomInternal<M>;\n\nexport interface NavigationViewEntityInternal<M extends Record<string, unknown>> {\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, unknown>> {\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, unknown>> {\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((v): v is EntityCustomView => v != null)\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,\npath: 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 (getSubcollections(collection).length > 0) {\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 ReferenceProperty,\n StringProperty,\n User\n} from \"@rebasepro/types\";\n\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, unknown> = Record<string, unknown>,\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\n // SAFETY: Identity function — P is a subtype of the conditional return type by definition\n return property as unknown as ReturnType<typeof buildProperty<T, P>>;\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, unknown>>(\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, unknown>>(\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, unknown> = Record<string, unknown>>(\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, unknown>, USER extends User = User>(\n additionalFieldDelegate: AdditionalFieldDelegate<M, USER>\n): AdditionalFieldDelegate<M, USER> {\n return additionalFieldDelegate;\n}\n\n\n","import { ArrayProperty, EntityValues, StorageConfig, StringProperty, UploadedFileContext } from \"@rebasepro/types\";\nimport { randomString } from \"@rebasepro/utils\";\n\ninterface ResolveFilenameStringParams<M extends Record<string, unknown>> {\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 Record<string, unknown>>(\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 Record<string, unknown>> {\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 Record<string, unknown>>(\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","import { EntityCallbacks, Properties } from \"@rebasepro/types\";\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 const 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 const 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\n const cbRes = await Promise.resolve(property.callbacks[callbackName]({\n ...(propsContext as Record<string, unknown>),\n value: currentValue,\n previousValue\n } as never));\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,\nvalues: 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","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 ?? []).map((r: unknown) => typeof r === \"string\" ? r : (r as { id: string }).id)\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 const 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.ui = result.ui || {};\n result.ui.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.ui = result.ui || {};\n result.ui.disabled = {\n ...(typeof result.ui?.disabled === \"object\" ? result.ui.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.ui = result.ui || {};\n result.ui.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 (\"enum\" in result && result.enum && (conditions.enumConditions || conditions.allowedEnumValues || conditions.excludedEnumValues)) {\n (result as Record<string, unknown>).enum = applyEnumConditions(\n result.enum 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).fixedFilter = evaluateCondition(conditions.referenceFilter, context) as ReferenceProperty[\"fixedFilter\"];\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 ArrayProperty,\n CollectionWithRelations,\n CollectionWithSubcollections,\n EntityCollection,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty,\n getDataSourceCapabilities\n} from \"@rebasepro/types\";\nimport { deepEqual } from \"fast-equals\";\n\nimport { enumToObjectEntries, getSubcollections, getTableName, resolveCollectionRelations, findRelation, sanitizeRelation } from \"../util\";\nimport { removeFunctions, mergeDeep, deepClone } from \"@rebasepro/utils\";\n\nexport class CollectionRegistry {\n\n // Normalized runtime layer (used by Data Grid / UI)\n private collectionsByTableName = new Map<string, EntityCollection>();\n private collectionsBySlug = new Map<string, EntityCollection>();\n private rootCollections: EntityCollection[] = [];\n private cachedCollectionsList: EntityCollection[] | null = null;\n\n // Raw configuration layer (used by Collection Editor AST generator)\n private rawCollectionsByTableName = new Map<string, EntityCollection>();\n private rawCollectionsBySlug = new Map<string, EntityCollection>();\n private rawRootCollections: EntityCollection[] = [];\n private cachedRawCollectionsList: EntityCollection[] | null = null;\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.collectionsByTableName.clear();\n this.collectionsBySlug.clear();\n this.rootCollections = [];\n this.cachedCollectionsList = null;\n\n this.rawCollectionsByTableName.clear();\n this.rawCollectionsBySlug.clear();\n this.rawRootCollections = [];\n this.cachedRawCollectionsList = null;\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 this.reset();\n // Phase 0: Populate maps with raw collections first for string target resolution\n collections.forEach((c) => {\n if (c.slug) {\n this.collectionsBySlug.set(c.slug, c);\n }\n this.collectionsByTableName.set(getTableName(c), c);\n });\n\n const normalizedCollections = collections.map(c => this.normalizeCollection({ ...c }));\n\n // Phase 1: Register all top-level collections first (without recursion).\n // This ensures that injected entityViews (e.g. History tab) are preserved.\n // Without this, _registerRecursively could register a relation-target collection\n // (e.g. Tags from Posts.relations) using the raw module object (without injected views)\n // before the top-level Tags collection (with injected views) gets its turn.\n normalizedCollections.forEach((c, index) => {\n const raw = deepClone(collections[index]);\n this.rootCollections.push(c);\n this.rawRootCollections.push(raw);\n\n const normalized = this.normalizeCollection(c);\n this.collectionsByTableName.set(getTableName(normalized), normalized);\n this.rawCollectionsByTableName.set(getTableName(raw), raw);\n if (normalized.slug) {\n this.collectionsBySlug.set(normalized.slug, normalized);\n }\n if (raw.slug) {\n this.rawCollectionsBySlug.set(raw.slug, raw);\n }\n });\n\n // Phase 2: Now recurse into subcollections (relations, etc.)\n normalizedCollections.forEach((c) => {\n const subcollections = getSubcollections(c);\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n });\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 ? deepClone(rawCollection) : deepClone(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.collectionsByTableName.has(getTableName(collection))) {\n return;\n }\n\n const normalizedCollection = this.normalizeCollection(collection);\n this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);\n this.rawCollectionsByTableName.set(getTableName(rawCollection), 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 // Use the normalized collection for subcollection discovery so that\n // both inline-extracted and explicit relations are considered.\n const subcollections = getSubcollections(normalizedCollection);\n\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n }\n\n public normalizeCollection(collection: EntityCollection): EntityCollection {\n // Work on a shallow copy to avoid mutating the caller's reference.\n // This is critical for idempotency (the raw input must not be changed)\n // and for preventing mutation of module-level collection singletons.\n const result = { ...collection } as EntityCollection;\n\n // 1. Extract relations from properties that have inline config (target set)\n const extractedRelations = this.extractRelationsFromProperties(result.properties);\n\n // 2. Merge with manual relations[] (manual entries win on name conflict)\n const relResult = result as CollectionWithRelations;\n const manualRelations = getDataSourceCapabilities(result.driver).supportsRelations ? (relResult.relations ?? []) : [];\n const mergedRelationsRaw = [...extractedRelations];\n for (const manual of manualRelations) {\n const name = manual.relationName;\n if (!name) {\n mergedRelationsRaw.push(manual);\n } else {\n const existingIndex = mergedRelationsRaw.findIndex(r => r.relationName === name);\n if (existingIndex === -1) {\n mergedRelationsRaw.push(manual);\n } else {\n // Merge manual into existing, preserving custom fields like 'collection'\n mergedRelationsRaw[existingIndex] = {\n ...manual,\n ...mergedRelationsRaw[existingIndex]\n };\n }\n }\n }\n\n let mergedRelations = mergedRelationsRaw;\n\n // 2b. Sanitize each relation so derived fields (through, localKey,\n // foreignKeyOnTarget, etc.) are populated. Without this the\n // property.relation stamp is missing junction-table metadata and\n // the backend cannot fetch many-to-many data.\n if (getDataSourceCapabilities(result.driver).supportsRelations) {\n mergedRelations = mergedRelationsRaw.map(r => {\n try {\n return sanitizeRelation(r, result, (slug) => this.get(slug));\n } catch {\n // sanitizeRelation may throw for incomplete configs\n // (e.g. missing target). Keep the raw relation as-is.\n return r;\n }\n });\n\n // 3. Set the merged relations on the result copy\n relResult.relations = mergedRelations;\n }\n\n // 4. Normalize properties (which stamps relation on each property)\n const properties: Properties = this.normalizeProperties(result.properties, mergedRelations);\n result.properties = properties;\n\n // Populate childCollections from driver-specific fields\n if (!result.childCollections) {\n if (getDataSourceCapabilities(result.driver).supportsSubcollections && (result as CollectionWithSubcollections).subcollections) {\n result.childCollections = (result as CollectionWithSubcollections).subcollections;\n } else if (getDataSourceCapabilities(result.driver).supportsRelations && relResult.relations) {\n const manyRelations = relResult.relations.filter((r: Relation) => r.cardinality === \"many\");\n if (manyRelations.length > 0) {\n result.childCollections = () => manyRelations.map((r: Relation) => {\n const target = r.target();\n return r.overrides ? mergeDeep(target, r.overrides) : target;\n });\n }\n }\n }\n\n return result;\n }\n\n /**\n * Extract Relation[] from properties that have inline relation config (i.e. `target` is set).\n * This allows developers to define relations directly on properties without a separate\n * `relations[]` entry on the collection.\n */\n private extractRelationsFromProperties(properties: Properties): Relation[] {\n const relations: Relation[] = [];\n for (const [key, property] of Object.entries(properties as Record<string, Property>)) {\n if (property.type === \"relation\") {\n const relProp = property as RelationProperty;\n // Support both inline config (target directly on property)\n // and nested config (target inside property.relation)\n const target = relProp.target ?? relProp.relation?.target;\n if (target) {\n const relationName = relProp.relationName ?? relProp.relation?.relationName ?? key;\n relations.push({\n relationName,\n target,\n cardinality: relProp.cardinality ?? relProp.relation?.cardinality ?? \"one\",\n direction: relProp.direction ?? relProp.relation?.direction ?? \"owning\",\n inverseRelationName: relProp.inverseRelationName ?? relProp.relation?.inverseRelationName,\n localKey: relProp.localKey ?? relProp.relation?.localKey,\n foreignKeyOnTarget: relProp.foreignKeyOnTarget ?? relProp.relation?.foreignKeyOnTarget,\n through: relProp.through ?? relProp.relation?.through,\n joinPath: relProp.joinPath ?? relProp.relation?.joinPath,\n onUpdate: relProp.onUpdate ?? relProp.relation?.onUpdate,\n onDelete: relProp.onDelete ?? relProp.relation?.onDelete,\n overrides: relProp.overrides ?? relProp.relation?.overrides,\n });\n }\n } else if (property.type === \"map\" && property.properties) {\n // Recurse into map children to extract nested inline relations\n relations.push(...this.extractRelationsFromProperties(property.properties));\n }\n }\n return relations;\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(key, properties[key], relations);\n }\n return newProperties;\n }\n\n private normalizeProperty(key: string, 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 // Cast to get a properly typed mutable reference\n const arrayProp = newProperty as ArrayProperty;\n if (arrayProp.of) {\n if (Array.isArray(arrayProp.of)) {\n (arrayProp as { of: Property | Property[] }).of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, relations));\n } else {\n arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, relations);\n }\n } else if (arrayProp.oneOf && arrayProp.oneOf.properties) {\n arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.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.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 name = relationProperty.relationName || key;\n const relation = relations.find(r => r.relationName === name);\n if (relation) {\n // we attach the resolved relation to the property\n (relationProperty as RelationProperty & { relation?: Relation }).relation = relation;\n } else {\n console.warn(`Could not find relation for property '${key}' with relationName: ${name}`);\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: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.collectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n // Fallback to table name lookup\n return this.collectionsByTableName.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\n // Fallback: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.rawCollectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n return this.rawCollectionsByTableName.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 if (!getDataSourceCapabilities(currentCollection.driver).supportsRelations) {\n throw new Error(`Relation path navigation requires a collection that supports relations, but '${currentCollection.slug}' uses driver '${currentCollection.driver}'`);\n }\n const resolvedRelations = resolveCollectionRelations(currentCollection);\n const relation = findRelation(resolvedRelations, relationKey);\n\n if (!relation) {\n throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);\n }\n\n // Move to the target collection\n const target = relation.target();\n const targetRelationKey = relation.relationName || target.slug;\n const targetSlug = relation.overrides?.slug ?? targetRelationKey;\n currentCollection = this.get(targetSlug) || this.normalizeCollection(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 if (!this.cachedCollectionsList) {\n this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());\n }\n return this.cachedCollectionsList;\n }\n\n getRawCollections(): EntityCollection[] {\n if (!this.cachedRawCollectionsList) {\n this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());\n }\n return this.cachedRawCollectionsList;\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 = getSubcollections(currentCollection);\n if (!subcollections || subcollections.length === 0) {\n throw new Error(`No subcollections found for ${currentCollection.slug} 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}`);\n }\n currentCollection = this.get(subcollection.slug) || this.normalizeCollection(subcollection);\n collections.push(currentCollection);\n }\n }\n\n return {\n collections,\n entityIds,\n finalCollection: currentCollection\n };\n }\n\n}\n\n","import type { PostgresCollection } from \"@rebasepro/types\";\n\n/**\n * Default users collection.\n *\n * Prepended to the developer's collections array by the admin and server.\n * Slug-based dedup (Map keyed by slug, last-write-wins) lets developers\n * override by defining their own collection with `slug: \"users\"`.\n */\nexport const defaultUsersCollection: PostgresCollection = {\n name: \"Users\",\n singularName: \"User\",\n slug: \"users\",\n table: \"users\",\n schema: \"rebase\",\n icon: \"Users\",\n group: \"Settings\",\n openEntityMode: \"dialog\",\n disableDefaultActions: [\"copy\"],\n securityRules: [\n { operation: \"select\", roles: [\"admin\"] },\n { operations: [\"insert\", \"update\", \"delete\"], roles: [\"admin\"] }\n ],\n sort: [\"createdAt\", \"desc\"],\n properties: {\n id: {\n name: \"ID\",\n type: \"string\",\n isId: \"uuid\",\n ui: { readOnly: true }\n },\n email: {\n name: \"Email\",\n type: \"string\",\n validation: { required: true, unique: true }\n },\n displayName: {\n name: \"Name\",\n type: \"string\",\n columnName: \"display_name\",\n validation: { required: true }\n },\n photoURL: {\n name: \"Photo URL\",\n type: \"string\",\n columnName: \"photo_url\",\n url: \"image\"\n },\n roles: {\n name: \"Roles\",\n type: \"array\",\n columnType: \"text[]\",\n of: {\n name: \"Role\",\n type: \"string\",\n enum: {\n admin: \"Admin\",\n editor: \"Editor\",\n viewer: \"Viewer\"\n }\n }\n },\n passwordHash: {\n name: \"Password Hash\",\n type: \"string\",\n columnName: \"password_hash\",\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n emailVerified: {\n name: \"Email Verified\",\n type: \"boolean\",\n columnName: \"email_verified\",\n defaultValue: false,\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n emailVerificationToken: {\n name: \"Email Verification Token\",\n type: \"string\",\n columnName: \"email_verification_token\",\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n emailVerificationSentAt: {\n name: \"Email Verification Sent At\",\n type: \"date\",\n columnName: \"email_verification_sent_at\",\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n metadata: {\n name: \"Metadata\",\n type: \"map\",\n defaultValue: {},\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n },\n createdAt: {\n name: \"Created At\",\n type: \"date\",\n columnName: \"created_at\",\n autoValue: \"on_create\",\n ui: { readOnly: true }\n },\n updatedAt: {\n name: \"Updated At\",\n type: \"date\",\n columnName: \"updated_at\",\n autoValue: \"on_update\",\n ui: { hideFromCollection: true, disabled: { hidden: true } }\n }\n },\n listProperties: [\"displayName\", \"email\", \"roles\", \"createdAt\"],\n propertiesOrder: [\"id\", \"email\", \"displayName\", \"roles\", \"createdAt\"]\n};\n","import { FindParams, Entity, FindResponse, CollectionAccessor, QueryBuilderInterface, FilterOperator, LogicalCondition, WhereValue, FilterCondition } from \"@rebasepro/types\";\n\nexport function or(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"or\", conditions };\n}\n\nexport function and(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"and\", conditions };\n}\n\nexport function cond(column: string, operator: FilterOperator, value: unknown): FilterCondition {\n return { column, operator, value };\n}\n\nexport class QueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> implements QueryBuilderInterface<M> {\n private params: FindParams = { where: {} };\n\n constructor(private collection: CollectionAccessor<M>) {}\n\n /**\n * Add a filter condition to your query.\n * @example\n * client.collection('users').where('age', '>=', 18).find()\n */\n where<K extends keyof M & string>(column: K, operator: FilterOperator, value: WhereValue<M[K]>): this;\n where(logicalCondition: LogicalCondition): this;\n where(columnOrCondition: string | LogicalCondition, operator?: FilterOperator, value?: unknown): this {\n // Handle LogicalCondition signature\n if (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n this.params.logical = columnOrCondition as LogicalCondition;\n return this;\n }\n\n if (!this.params.where) {\n this.params.where = {};\n }\n\n const column = columnOrCondition as string;\n const condition: [FilterOperator, unknown] = [operator!, value];\n const existing = this.params.where[column];\n\n if (existing === undefined) {\n this.params.where[column] = condition;\n } else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) {\n (this.params.where[column] as [FilterOperator, unknown][]).push(condition);\n } else {\n // Convert existing single tuple/value into array of tuples\n let firstCondition: [FilterOperator, unknown];\n if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") {\n firstCondition = existing as [FilterOperator, unknown];\n } else {\n firstCondition = [\"==\", existing];\n }\n this.params.where[column] = [firstCondition, condition];\n }\n\n return this;\n }\n\n /**\n * Order the results by a specific column.\n * @example\n * client.collection('users').orderBy('createdAt', 'desc').find()\n */\n orderBy(column: keyof M & string, ascending: \"asc\" | \"desc\" = \"asc\"): this {\n this.params.orderBy = `${column}:${ascending}`;\n return this;\n }\n\n /**\n * Limit the number of results returned.\n */\n limit(count: number): this {\n this.params.limit = count;\n return this;\n }\n\n /**\n * Skip the first N results.\n */\n offset(count: number): this {\n this.params.offset = count;\n return this;\n }\n\n /**\n * Set a free-text search string if supported by the backend.\n */\n search(searchString: string): this {\n this.params.searchString = searchString;\n return this;\n }\n\n /**\n * Include related entities in the response.\n * Relations will be populated with full entity data instead of just IDs.\n *\n * @param relations - Relation names to include, or \"*\" for all.\n * @example\n * // Include specific relations\n * client.data.posts.include(\"tags\", \"author\").find()\n *\n * // Include all relations\n * client.data.posts.include(\"*\").find()\n */\n include(...relations: string[]): this {\n this.params.include = relations;\n return this;\n }\n\n /**\n * Execute the find query and return the results.\n */\n async find(): Promise<FindResponse<M>> {\n return this.collection.find(this.params) as Promise<FindResponse<M>>;\n }\n\n /**\n * Listen to realtime updates matching this query.\n */\n listen(onUpdate: (data: FindResponse<M>) => void, onError?: (error: Error) => void): () => void {\n if (!this.collection.listen) {\n throw new Error(\"Listen is only available when RebaseClient is configured with a websocketUrl.\");\n }\n return this.collection.listen(this.params, onUpdate, onError);\n }\n}\n","import {\n DataDriver,\n RebaseData,\n CollectionAccessor,\n FindParams,\n FindResponse,\n Entity,\n EntityValues,\n FilterValues,\n WhereFilterOp,\n WhereFieldValue,\n WhereFilterOpShort,\n LogicalCondition,\n WhereValue\n} from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport { QueryBuilder } from \"./query_builder\";\n\n/**\n * Convert where-clause filter object to the internal DataDriver FilterValues format.\n *\n * Supports multiple value formats:\n * - PostgREST string: { status: \"eq.published\", age: \"gte.18\" }\n * - Equality shorthand: { company_profile_id: null, status: \"active\", age: 18 }\n * - Tuple syntax: { age: [\">=\", 18], role: [\"in\", [\"admin\", \"editor\"]] }\n *\n * Internal: { status: [\"==\", \"published\"], age: [\">=\", 18] }\n */\nfunction convertWhereToFilter(where?: Record<string, WhereFieldValue>): FilterValues<string> | undefined {\n if (!where) return undefined;\n\n const operatorMap: Record<string, WhereFilterOp> = {\n \"eq\": \"==\",\n \"neq\": \"!=\",\n \"gt\": \">\",\n \"gte\": \">=\",\n \"lt\": \"<\",\n \"lte\": \"<=\",\n \"in\": \"in\",\n \"nin\": \"not-in\",\n \"not-in\": \"not-in\",\n \"cs\": \"array-contains\",\n \"csa\": \"array-contains-any\",\n \"==\": \"==\",\n\"!=\": \"!=\",\n \">\": \">\",\n\">=\": \">=\",\n \"<\": \"<\",\n\"<=\": \"<=\",\n \"array-contains\": \"array-contains\",\n \"array-contains-any\": \"array-contains-any\"\n };\n\n const filter: FilterValues<string> = {};\n\n for (const [field, rawValue] of Object.entries(where)) {\n // Handle null → equality\n if (rawValue === null) {\n filter[field] = [\"==\", null];\n continue;\n }\n\n // Handle boolean → equality\n if (typeof rawValue === \"boolean\") {\n filter[field] = [\"==\", rawValue];\n continue;\n }\n\n // Handle number → equality\n if (typeof rawValue === \"number\") {\n filter[field] = [\"==\", rawValue];\n continue;\n }\n\n // Handle tuple or array of tuples\n if (Array.isArray(rawValue)) {\n const conditions: [WhereFilterOpShort, unknown][] = Array.isArray(rawValue[0])\n ? (rawValue as [WhereFilterOpShort, unknown][])\n : [rawValue as [WhereFilterOpShort, unknown]];\n\n const mappedConditions: [WhereFilterOp, unknown][] = conditions.map(([rawOp, val]) => {\n const mappedOp = operatorMap[rawOp] ?? \"==\";\n return [mappedOp, val];\n });\n\n filter[field] = Array.isArray(rawValue[0]) ? mappedConditions : mappedConditions[0];\n continue;\n }\n\n // Handle PostgREST string format: \"op.value\"\n if (typeof rawValue === \"string\") {\n const dotIndex = rawValue.indexOf(\".\");\n if (dotIndex === -1) {\n // Plain string equality\n filter[field] = [\"==\", rawValue];\n continue;\n }\n\n const op = rawValue.substring(0, dotIndex);\n let value: unknown = rawValue.substring(dotIndex + 1);\n\n // Parse list values like \"(admin,editor)\"\n if (typeof value === \"string\" && value.startsWith(\"(\") && value.endsWith(\")\")) {\n value = value.slice(1, -1).split(\",\").map((v: string) => v.trim());\n }\n\n // Parse null string\n if (value === \"null\") {\n value = null;\n }\n // Parse boolean strings\n else if (value === \"true\") {\n value = true;\n } else if (value === \"false\") {\n value = false;\n }\n // Try to parse numbers\n else if (typeof value === \"string\" && !isNaN(Number(value)) && value.trim() !== \"\") {\n value = Number(value);\n }\n\n const mappedOp = operatorMap[op];\n if (mappedOp) {\n filter[field] = [mappedOp, value];\n }\n }\n }\n\n return Object.keys(filter).length > 0 ? filter : undefined;\n}\n\n/**\n * Parse an orderBy string like \"created_at:desc\" into [field, direction].\n */\nfunction parseOrderBy(orderBy?: string): [string, \"asc\" | \"desc\"] | undefined {\n if (!orderBy) return undefined;\n const parts = orderBy.split(\":\");\n const field = parts[0];\n const direction = (parts[1] as \"asc\" | \"desc\") || \"asc\";\n return [field, direction];\n}\n\nfunction createDriverAccessor<M extends Record<string, unknown> = Record<string, unknown>>(\n driver: DataDriver,\n slug: string\n): CollectionAccessor<M> {\n const accessor: CollectionAccessor<M> = {\n async find(params?: FindParams): Promise<FindResponse<M>> {\n const orderParsed = parseOrderBy(params?.orderBy);\n const entities = await driver.fetchCollection<M>({\n path: slug,\n limit: params?.limit,\n offset: params?.offset,\n filter: convertWhereToFilter(params?.where),\n orderBy: orderParsed?.[0],\n order: orderParsed?.[1],\n searchString: params?.searchString\n });\n const limit = params?.limit ?? 20;\n const offset = params?.offset ?? 0;\n return {\n data: entities,\n meta: {\n total: entities.length,\n limit,\n offset,\n hasMore: entities.length >= limit\n }\n };\n },\n\n async findById(id: string | number): Promise<Entity<M> | undefined> {\n return driver.fetchEntity<M>({ path: slug,\nentityId: id });\n },\n\n async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {\n return driver.saveEntity<M>({\n path: slug,\n values: data,\n entityId: id,\n status: \"new\"\n });\n },\n\n async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {\n return driver.saveEntity<M>({\n path: slug,\n values: data,\n entityId: id,\n status: \"existing\"\n });\n },\n\n async delete(id: string | number): Promise<void> {\n return driver.deleteEntity({\n entity: { id,\npath: slug,\nvalues: {} as Record<string, unknown> }\n });\n },\n\n deleteAll: driver.deleteAll\n ? async (): Promise<void> => {\n return driver.deleteAll!(slug);\n }\n : undefined,\n\n count: driver.countEntities\n ? async (params?: FindParams): Promise<number> => {\n return driver.countEntities!({\n path: slug,\n filter: convertWhereToFilter(params?.where)\n });\n }\n : undefined,\n\n listen: driver.listenCollection\n ? (params: FindParams | undefined, onUpdate: (response: FindResponse<M>) => void, onError?: (error: Error) => void) => {\n const orderParsed = parseOrderBy(params?.orderBy);\n const limit = params?.limit ?? 20;\n const offset = params?.offset ?? 0;\n return driver.listenCollection!<M>({\n path: slug,\n limit: params?.limit,\n offset: params?.offset,\n filter: convertWhereToFilter(params?.where),\n orderBy: orderParsed?.[0],\n order: orderParsed?.[1],\n searchString: params?.searchString,\n onUpdate: (entities) => {\n onUpdate({\n data: entities,\n meta: {\n total: entities.length,\n limit,\n offset,\n hasMore: entities.length >= limit\n }\n });\n },\n onError\n });\n } : undefined,\n\n listenById: driver.listenEntity\n ? (id: string | number, onUpdate: (entity: Entity<M> | undefined) => void, onError?: (error: Error) => void) => {\n return driver.listenEntity!<M>({\n path: slug,\n entityId: id,\n onUpdate: (entity) => onUpdate(entity ?? undefined),\n onError\n });\n } : undefined,\n\n // Fluent Query Builder\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOpShort, value?: unknown) {\n const builder = new QueryBuilder<M>(accessor);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValue<M[keyof M & string]>);\n },\n orderBy(column: keyof M & string, ascending?: \"asc\" | \"desc\") {\n return new QueryBuilder<M>(accessor).orderBy(column, ascending);\n },\n limit(count: number) {\n return new QueryBuilder<M>(accessor).limit(count);\n },\n offset(count: number) {\n return new QueryBuilder<M>(accessor).offset(count);\n },\n search(searchString: string) {\n return new QueryBuilder<M>(accessor).search(searchString);\n },\n include(...relations: string[]) {\n return new QueryBuilder<M>(accessor).include(...relations);\n }\n };\n\n return accessor;\n}\n\n/**\n * Build a `RebaseData` object from a `DataDriver` using JavaScript Proxy.\n *\n * This is the key bridge: any property access like `data.products` returns\n * a `CollectionAccessor` backed by the underlying DataDriver, without\n * needing per-collection code generation.\n *\n * @example\n * const data = buildRebaseData(driver);\n * await data.products.create({ name: \"Camera\", price: 299 });\n * const { data: items } = await data.products.find({ where: { status: \"eq.published\" } });\n */\nexport function buildRebaseData(driver: DataDriver): RebaseData {\n const cache = new Map<string, CollectionAccessor>();\n\n function getAccessor(slug: string): CollectionAccessor {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = createDriverAccessor(driver, slug);\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = {\n collection: getAccessor\n } as RebaseData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n // Ignore Symbol properties (e.g. Symbol.toPrimitive, Symbol.iterator)\n if (typeof prop === \"symbol\") return undefined;\n // Ignore internal JS properties\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n\n // Convert camelCase property names to snake_case slugs\n const slug = toSnakeCase(prop);\n return getAccessor(slug);\n }\n });\n}\n"],"names":["DEFAULT_ONE_OF_TYPE","DEFAULT_ONE_OF_VALUE","isReadOnly","property","ui","readOnly","type","autoValue","path","Field","isHidden","disabled","Boolean","hidden","isPropertyBuilder","dynamicProps","getDefaultValuesFor","properties","Object","entries","map","key","value","getDefaultValueFor","undefined","reduce","a","b","defaultValue","defaultValuesFor","keys","length","getDefaultValueFortype","updateDateAutoValues","inputValues","status","timestampNowValue","traverseValuesProperties","inputValue","sanitizeData","values","result","forEach","validation","required","getReferenceFrom","entity","id","Error","EntityReference","driver","databaseId","getRelationFrom","EntityRelation","normalizeToEntityRelation","Array","isArray","obj","isRelationLike","__type","isEntityRelation","isEntityReference","data","operation","safeInputValues","updatedValues","updatedValue","traverseValueProperty","mergeDeep","of","e","i","filter","oneOf","typeField","valueField","rec","childProperty","createRelationRef","createRelationRefWithData","sortProperties","propertiesOrder","propertiesKeys","validOrderKeys","includes","processedKeys","Set","orderedResult","missingProperties","has","console","error","resolveDefaultSelectedView","defaultSelectedView","params","getLocalChangesBackup","collection","localChangesBackup","getPrimaryKeys","ids","prop","isId","enumToObjectEntries","enumValues","label","getLabelOrConfigFrom","find","entry","String","COLLECTION_PATH_SEPARATOR","stripCollectionPath","segmentsToStrippedPath","fullPathToCollectionSegments","paths","split","sanitizeRelation","relation","sourceCollection","resolveCollection","target","rawTarget","targetCollection","slug","name","evaluated","newRelation","relationName","toSnakeCase","direction","foreignKeyOnTarget","through","cardinality","joinPath","sourceName","localKey","generateForeignKeyName","foundForeignKey","targetRelations","getDataSourceCapabilities","supportsRelations","relations","targetRel","targetRelTarget","keyPrefix","inverseRelationName","isManyToManyInverse","propKey","relProp","relName","sourceTableName","getTableName","targetTableName","table","sort","join","sourceColumn","targetColumn","_resolvedRelationsCache","WeakMap","resolveCollectionRelations","cached","get","relCollection","registeredRelationNames","normalizedRelation","relationKey","add","resolvePropertyRelation","propertyKey","set","onUpdate","onDelete","overrides","warn","getTableVarName","tableName","replace","_","char","toUpperCase","getEnumVarName","propName","tableVar","propVar","charAt","slice","getColumnName","fullColumn","pop","findRelation","resolvedRelations","slugKey","snakeKey","resolveProperty","props","ignoreMissingFields","rest","resultProperty","usedPropertyValue","getIn","propertyValue","previousValues","dynamicPropsResult","resolvedProperty","resolveProperties","enum","resolvePropertyEnum","propertyConfig","isDefaultFieldConfigId","cmsFields","propertyConfigs","customField","restConfigProperty","customFieldProperty","resolveRelationProperty","rel","childResolvedProperty","resolveArrayProperties","p","index","resolvedProperties","getArrayResolvedProperties","ofProperty","v","resolveEnumValues","input","getSubcollections","childCollections","supportsSubcollections","subcollections","manyRelations","r","customName","baseOverrides","singularName","targetWithOverrides","c","evaluateAST","sqlString","auth","cleanedSQL","trim","startsWith","endsWith","openCount","isEnclosing","substring","splitByTopLevel","str","delimiter","parts","current","push","orParts","some","part","andParts","every","upperSQL","roleIntersectMatch","match","requiredRoles","userRoles","user","roles","roleContainMatch","pattern1","RegExp","pattern2","match1","uid","match2","simpleEqualityMatch","field","operator","entityValue","evaluateRule","rule","access","ownerField","using","withCheck","checkOperation","authController","targetOperation","securityRules","supportsRLS","applicableRules","operations","userRoleIds","roleApplicableRules","grantedByPermissive","deniedByRestrictive","mode","passed","hasPermissive","canReadCollection","canEditEntity","canCreateEntity","canDeleteEntity","getEntityImagePreviewPropertyKey","storage","acceptedFiles","url","removeInitialAndTrailingSlashes","s","removeInitialSlash","removeTrailingSlash","addInitialSlash","getLastSegment","cleanPath","segments","resolveCollectionPathIds","allCollections","remainingPath","currentCollections","resolvedPathParts","foundMatch","potentialMatches","flatMap","col","foundCollection","matchString","idSeparatorIndex","indexOf","entityId","getCollectionBySlugWithin","slugOrPath","collections","subpaths","subpathCombinations","getCollectionPathsCombinations","subpathCombination","navigationEntry","localeCompare","newPath","splice","getNavigationEntriesFromPath","currentFullPath","collectionPath","restOfThePath","nextSegments","parentCollection","entityViews","customView","resolveEntityView","contextEntityViews","view","entityView","getParentReferencesFromPath","buildCollection","buildProperty","buildProperties","buildPropertiesOrBuilder","propertiesOrBuilder","buildEnum","buildEnumValueConfig","enumValueConfig","buildEntityCallbacks","callbacks","buildAdditionalFieldDelegate","additionalFieldDelegate","resolveStorageFilenameString","file","replacePlaceholders","randomString","resolveStoragePathString","ext","hasPropertyCallbacks","callbackName","ofs","processProperties","propsContext","currentValue","previousValue","Promise","all","item","prevItem","singlePropData","res","cbRes","resolve","buildPropertyCallbacks","propertyCallbacks","afterRead","processedValues","beforeSave","acc","operationsRegistered","registerConditionOperations","jsonLogic","add_operation","roleId","roleIds","role","timestamp","date","Date","today","getFullYear","getMonth","getDate","now","evaluateCondition","context","apply","serializeValueForConditions","getTime","toMillis","toDate","buildConditionContext","serializedValues","serializedPreviousValues","isNew","email","displayName","photoURL","applyPropertyConditions","conditions","isDisabled","clearOnDisabled","disabledMessage","isRequired","requiredMessage","enumConditions","allowedEnumValues","excludedEnumValues","applyEnumConditions","referencePath","referenceFilter","fixedFilter","canAddElements","sortable","objectToArray","k","isNaN","Number","allowed","allowedArray","ev","excluded","excludedArray","evConditions","CollectionRegistry","collectionsByTableName","Map","collectionsBySlug","rootCollections","cachedCollectionsList","rawCollectionsByTableName","rawCollectionsBySlug","rawRootCollections","cachedRawCollectionsList","lastRawInputSnapshot","constructor","registerMultiple","reset","clear","rawSnapshot","removeFunctions","deepEqual","normalizedCollections","normalizeCollection","raw","deepClone","normalized","subCollection","_registerRecursively","register","rawCollection","normalizedCollection","extractedRelations","extractRelationsFromProperties","relResult","manualRelations","mergedRelationsRaw","manual","existingIndex","findIndex","mergedRelations","normalizeProperties","newProperties","normalizeProperty","newProperty","arrayProp","stringOrNumberProperty","relationProperty","bySlug","byNormalized","getRaw","getCollectionByPath","pathSegments","rootCollectionPath","currentCollection","targetRelationKey","targetSlug","getCollections","from","getRawCollections","resolvePathToCollections","entityIds","subcollectionSlug","subcollection","finalCollection","defaultUsersCollection","schema","icon","group","openEntityMode","disableDefaultActions","unique","columnName","columnType","admin","editor","viewer","passwordHash","hideFromCollection","emailVerified","emailVerificationToken","emailVerificationSentAt","metadata","createdAt","updatedAt","listProperties","or","and","cond","column","QueryBuilder","where","columnOrCondition","logical","condition","existing","firstCondition","orderBy","ascending","limit","count","offset","search","searchString","include","listen","onError","convertWhereToFilter","operatorMap","rawValue","mappedConditions","rawOp","val","mappedOp","dotIndex","op","parseOrderBy","createDriverAccessor","accessor","orderParsed","entities","fetchCollection","order","meta","total","hasMore","findById","fetchEntity","create","saveEntity","update","delete","deleteEntity","deleteAll","countEntities","listenCollection","listenById","listenEntity","builder","buildRebaseData","cache","getAccessor","Proxy","_target"],"mappings":";;;;AAAO,MAAMA,sBAAsB;AAC5B,MAAMC,uBAAuB;ACY7B,SAASC,WAAWC,UAA6B;AACpD,MAAIA,SAASC,IAAIC,SACb,QAAO;AACX,MAAIF,SAASG,SAAS,QAAQ;AAC1B,QAAIH,SAASI,UACT,QAAO;AAAA,EACf;AACA,MAAIJ,SAASG,SAAS,aAAa;AAC/B,WAAO,CAACH,SAASK,QAAQ,EAAE,YAAYL,SAASC,MAAM,OAAOD,SAASC,IAAIK;AAAAA,EAC9E;AACA,SAAO;AACX;AAEO,SAASC,SAASP,UAA6B;AAClD,SAAO,OAAOA,SAASC,IAAIO,aAAa,YAAYC,QAAQT,SAASC,IAAIO,SAASE,MAAM;AAC5F;AAEO,SAASC,kBAAkBX,UAAqB;AACnD,SAAO,OAAOA,UAAUY,iBAAiB;AAC7C;AAEO,SAASC,oBAAuDC,YAAkD;AACrH,MAAI,CAACA,WAAY,QAAO,CAAA;AACxB,SAAOC,OAAOC,QAAQF,UAAU,EAC3BG,IAAI,CAAC,CAACC,KAAKlB,QAAQ,MAAM;AACtB,QAAI,CAACA,S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