@rebasepro/cms 0.27.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/collection_editor/serializable_utils.js +5 -2
  2. package/dist/collection_editor/serializable_utils.js.map +1 -1
  3. package/dist/collection_editor/ui/collection_editor/EnumForm.d.ts +17 -0
  4. package/dist/collection_editor/ui/collection_editor/EnumForm.js +31 -17
  5. package/dist/collection_editor/ui/collection_editor/EnumForm.js.map +1 -1
  6. package/dist/collection_editor/ui/collection_editor/properties/EnumPropertyField.js +6 -5
  7. package/dist/collection_editor/ui/collection_editor/properties/EnumPropertyField.js.map +1 -1
  8. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js +3 -2
  9. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
  10. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +32 -16
  11. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
  12. package/dist/components/DetailViewBinding.js +4 -3
  13. package/dist/components/DetailViewBinding.js.map +1 -1
  14. package/dist/components/EditViewBinding.js +23 -5
  15. package/dist/components/EditViewBinding.js.map +1 -1
  16. package/dist/components/EntityPreviewBinding.js +1 -0
  17. package/dist/components/EntityPreviewBinding.js.map +1 -1
  18. package/dist/components/SelectableTable/filters/StringNumberFilterField.js +3 -3
  19. package/dist/components/SelectableTable/filters/StringNumberFilterField.js.map +1 -1
  20. package/dist/components/SidePanelBinding.js +7 -6
  21. package/dist/components/SidePanelBinding.js.map +1 -1
  22. package/dist/components/app/Scaffold.js +16 -1
  23. package/dist/components/app/Scaffold.js.map +1 -1
  24. package/dist/components/history/EntityHistoryView.js +2 -1
  25. package/dist/components/history/EntityHistoryView.js.map +1 -1
  26. package/dist/data_export/export/export.js +3 -3
  27. package/dist/data_export/export/export.js.map +1 -1
  28. package/dist/data_import/import/ImportCollectionAction.js +10 -12
  29. package/dist/data_import/import/ImportCollectionAction.js.map +1 -1
  30. package/dist/data_import/utils/id_column.d.ts +19 -0
  31. package/dist/data_import/utils/id_column.js +19 -1
  32. package/dist/data_import/utils/id_column.js.map +1 -1
  33. package/dist/data_import/utils/transforms.js +24 -7
  34. package/dist/data_import/utils/transforms.js.map +1 -1
  35. package/dist/form/EntityForm.d.ts +1 -1
  36. package/dist/form/EntityForm.js +14 -4
  37. package/dist/form/EntityForm.js.map +1 -1
  38. package/dist/form/EntityFormBinding.js +12 -8
  39. package/dist/form/EntityFormBinding.js.map +1 -1
  40. package/dist/form/components/FieldBlock.js +2 -1
  41. package/dist/form/components/FieldBlock.js.map +1 -1
  42. package/dist/form/field_bindings/KeyValueFieldBinding.js +3 -1
  43. package/dist/form/field_bindings/KeyValueFieldBinding.js.map +1 -1
  44. package/dist/form/field_bindings/ReadOnlyFieldBinding.js +0 -2
  45. package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
  46. package/dist/form/field_bindings/TextFieldBinding.js +3 -2
  47. package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
  48. package/dist/form/validation.js +12 -1
  49. package/dist/form/validation.js.map +1 -1
  50. package/dist/hooks/navigation/url_segments.d.ts +33 -0
  51. package/dist/hooks/navigation/url_segments.js +56 -0
  52. package/dist/hooks/navigation/url_segments.js.map +1 -0
  53. package/dist/hooks/navigation/useBuildUrlController.js +4 -2
  54. package/dist/hooks/navigation/useBuildUrlController.js.map +1 -1
  55. package/dist/hooks/useBuildSidePanel.js +6 -5
  56. package/dist/hooks/useBuildSidePanel.js.map +1 -1
  57. package/dist/hooks/useHistory.js +4 -3
  58. package/dist/hooks/useHistory.js.map +1 -1
  59. package/dist/routes/RebaseRoute.js +20 -30
  60. package/dist/routes/RebaseRoute.js.map +1 -1
  61. package/dist/util/navigation_utils.js +4 -3
  62. package/dist/util/navigation_utils.js.map +1 -1
  63. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","names":[],"sources":["../../src/form/validation.ts"],"sourcesContent":["import type { Properties } from \"@rebasepro/types\";\nimport type { ArrayProperty, MapProperty, NumberProperty, Property, BooleanProperty, DateProperty, GeopointProperty, ReferenceProperty, RelationProperty, StringProperty, StringPropertyValidationSchema, VectorProperty, BinaryProperty } from \"@rebasepro/types\";\n;\nimport { z, ZodTypeAny } from \"zod\";\nimport { deepEqual as isDeepEqual } from \"fast-equals\";\nimport { DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, enumToObjectEntries, isPropertyBuilder } from \"@rebasepro/common\";\nimport { getValueInPath, hydrateRegExp, isPlainObject, prettifyIdentifier } from \"@rebasepro/utils\";\n\n/** Whether an authored relation yields many rows. Derived from its kind. */\n/**\n * What to call this field in a validation message.\n *\n * `property.name` is the author's label and is optional — a headless project has\n * no panel and no reason to invent display names. Every message here\n * interpolated it directly, so an unnamed property produced\n * \"undefined must be min 3 characters long\" in front of a user.\n *\n * The fallback is the field's own key, prettified the same way the panel derives\n * a column header, so the message names the field the author would recognise.\n */\nfunction fieldLabel(property: Property, name?: string): string {\n return property.name ?? (name ? prettifyIdentifier(name) : \"This field\");\n}\n\nfunction relationCardinality(relation: { kind?: string; cardinality?: string } | undefined): \"one\" | \"many\" | undefined {\n if (!relation) return undefined;\n if (relation.kind === \"via\") return relation.cardinality as \"one\" | \"many\" | undefined;\n if (relation.kind === \"hasMany\" || relation.kind === \"manyToMany\") return \"many\";\n if (relation.kind === \"belongsTo\" || relation.kind === \"hasOne\") return \"one\";\n return relation.cardinality as \"one\" | \"many\" | undefined;\n}\n\n\nexport type CustomFieldValidator = (props: {\n name: string,\n value: unknown,\n property: Property,\n entityId?: string | number,\n parentProperty?: MapProperty | ArrayProperty,\n}) => Promise<boolean>;\n\ninterface PropertyContext<P extends Property> {\n property: P,\n parentProperty?: MapProperty | ArrayProperty,\n entityId?: string | number,\n customFieldValidator?: CustomFieldValidator,\n name?: string\n}\n\n/**\n * `validation.unique`, for the top-level properties that declare it: whether\n * another record already holds the value, asked of the data source through\n * `validator`. One error per field that fails, keyed like the schema's.\n *\n * Asked only for a value worth asking about — set (not empty), changed from\n * `storedValues` when there are any (a value the edit left alone is the stored\n * record's business, and it may predate the rule), and without an error of its\n * own already in `errors` — so a save makes one lookup per unique field it\n * actually changes, and typing makes none: this runs where validation runs, on\n * submit.\n */\nexport async function uniqueValueErrors({\n properties,\n values,\n storedValues,\n entityId,\n errors,\n validator\n}: {\n properties: Properties,\n values: Record<string, unknown>,\n storedValues?: Record<string, unknown>,\n entityId?: string | number,\n errors?: Record<string, unknown>,\n validator: CustomFieldValidator\n}): Promise<Record<string, string>> {\n const found: Record<string, string> = {};\n await Promise.all(Object.entries(properties as Record<string, Property>).map(async ([name, property]) => {\n if (!property?.validation?.unique) return;\n if (errors && name in errors) return;\n const value = values[name];\n if (value === undefined || value === null || value === \"\") return;\n if (storedValues && isDeepEqual(value, storedValues[name])) return;\n const unique = await validator({ name, value, property, entityId });\n if (!unique) found[name] = `${fieldLabel(property, name)} must be unique: another record already has this value`;\n }));\n return found;\n}\n\nexport function getEntitySchema<M extends Record<string, unknown>>(\n entityId: string | number | undefined,\n properties: Properties,\n customFieldValidator?: CustomFieldValidator): z.ZodObject<Record<string, ZodTypeAny>> {\n const shape: Record<string, ZodTypeAny> = {};\n Object.entries(properties as Record<string, Property>)\n .forEach(([name, property]) => {\n const isStringOrNumber = property.type === \"string\" || property.type === \"number\";\n const isIdAndAuto = isStringOrNumber && \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n if (entityId === undefined && isIdAndAuto) {\n return; // Skip validation for auto-generated IDs on new entities\n }\n shape[name] = mapPropertyToZod({\n property: property as Property,\n customFieldValidator,\n name,\n entityId\n });\n });\n return z.object(shape).passthrough();\n}\n\n\nexport function mapPropertyToZod(propertyContext: PropertyContext<Property>): ZodTypeAny {\n\n const property = propertyContext.property;\n if (isPropertyBuilder(property) && !property.type) {\n console.error(\"Error in property\", propertyContext);\n // Return a schema that always fails\n return z.any().refine(\n () => false,\n { message: \"Invalid property configuration: property builder should be resolved\" }\n );\n }\n\n if (property.type === \"string\") {\n return getZodStringSchema(propertyContext as PropertyContext<StringProperty>);\n } else if (property.type === \"number\") {\n return getZodNumberSchema(propertyContext as PropertyContext<NumberProperty>);\n } else if (property.type === \"boolean\") {\n return getZodBooleanSchema(propertyContext as PropertyContext<BooleanProperty>);\n } else if (property.type === \"map\") {\n return getZodMapObjectSchema(propertyContext as PropertyContext<MapProperty>);\n } else if (property.type === \"array\") {\n return getZodArraySchema(propertyContext as PropertyContext<ArrayProperty>);\n } else if (property.type === \"date\") {\n return getZodDateSchema(propertyContext as PropertyContext<DateProperty>);\n } else if (property.type === \"geopoint\") {\n return getZodGeoPointSchema(propertyContext as PropertyContext<GeopointProperty>);\n } else if (property.type === \"reference\") {\n return getZodReferenceSchema(propertyContext as PropertyContext<ReferenceProperty>);\n } else if (property.type === \"relation\") {\n return getZodRelationSchema(propertyContext as PropertyContext<RelationProperty>);\n } else if (property.type === \"vector\") {\n return getZodVectorSchema(propertyContext as PropertyContext<VectorProperty>);\n } else if (property.type === \"binary\") {\n return getZodBinarySchema(propertyContext as PropertyContext<BinaryProperty>);\n }\n\n // Log the error but don't crash the form\n console.error(\"Unsupported data type in zod mapping\", property);\n const dataType = \"dataType\" in (property as Record<string, unknown>) ? String((property as Record<string, unknown>).dataType) : \"unknown\";\n return z.any().refine(\n () => false,\n { message: `Unsupported data type: ${dataType}` }\n );\n}\n\n\nexport function getZodMapObjectSchema({\n property,\n entityId,\n customFieldValidator,\n name\n}: PropertyContext<MapProperty>): ZodTypeAny {\n const shape: Record<string, ZodTypeAny> = {};\n const validation = property.validation;\n if (property.properties)\n Object.entries(property.properties).forEach(([childName, childProperty]) => {\n const typedChildProperty = childProperty as Readonly<Property>;\n try {\n shape[childName] = mapPropertyToZod({\n property: typedChildProperty,\n parentProperty: property as MapProperty,\n customFieldValidator,\n name: `${name}[${childName}]`,\n entityId\n });\n } catch (e: unknown) {\n console.error(`Error creating validation schema for property ${childName}:`, e);\n shape[childName] = z.any().refine(\n () => false,\n { message: `Validation error: ${e instanceof Error ? e.message : \"Unknown error\"}` }\n );\n }\n });\n\n let schema: ZodTypeAny = z.object(shape).passthrough();\n if (validation?.required) {\n schema = schema.nullable().optional().refine(\n (value) => value !== undefined,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n } else {\n schema = schema.nullable().optional();\n }\n return schema;\n}\n\nfunction getZodStringSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<StringProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.string().nullable().optional();\n const validation = property.validation;\n\n const isRequired = validation?.required || property.isId === true || property.isId === \"manual\";\n\n if (property.enum) {\n if (isRequired) {\n schema = z.string().nullable().optional().refine(\n (value) => value !== undefined && value !== null && value !== \"\",\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n const entries = enumToObjectEntries(property.enum);\n const allowedValues = (isRequired ? entries : [...entries, null])\n .map((enumValueConfig) => enumValueConfig?.id ?? null);\n schema = schema.refine(\n (value: unknown) => allowedValues.includes(value as string | null),\n { message: `Must be one of: ${allowedValues.filter(Boolean).join(\", \")}` }\n );\n }\n\n if (isRequired && !property.enum) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null && value !== \"\",\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n if (validation) {\n\n if (validation.min || validation.min === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"string\" && value.length >= validation.min!),\n { message: `${fieldLabel(property, name)} must be min ${validation.min} characters long` }\n );\n if (validation.max || validation.max === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"string\" && value.length <= validation.max!),\n { message: `${fieldLabel(property, name)} must be max ${validation.max} characters long` }\n );\n if (validation.matches) {\n const regExp = typeof validation.matches === \"string\" ? hydrateRegExp(validation.matches) : validation.matches;\n if (regExp) {\n schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"string\" && regExp.test(value)),\n { message: validation.matchesMessage ?? \"Invalid format\" }\n );\n }\n }\n if (validation.length !== undefined) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"string\" && value.length === validation.length),\n { message: `${fieldLabel(property, name)} must be exactly ${validation.length} characters long` }\n );\n if (validation.trim || validation.lowercase || validation.uppercase) schema = z.preprocess(\n (v: unknown) => typeof v === \"string\" ? transformString(v, validation) : v,\n schema\n );\n }\n\n // Checked the way the server checks them: on every string that declares\n // them, `validation` block or not, and with the empty string let through —\n // it is what a cleared text field holds, and whether the field may be\n // empty is `required`'s question.\n if (property.email) schema = schema.refine(\n (value: unknown) => value == null || value === \"\" || (typeof value === \"string\" && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)),\n { message: `${fieldLabel(property, name)} must be an email` }\n );\n if (property.url) {\n if (!property.storage || property.storage?.storeUrl) {\n schema = schema.refine(\n (value: unknown) => {\n if (value == null || value === \"\") return true;\n try {\n new URL(value as string);\n return true;\n } catch {\n return false;\n }\n },\n { message: `${fieldLabel(property, name)} must be a url` }\n );\n } else {\n console.warn(`Property ${fieldLabel(property, name)} has a url validation but its storage configuration is not set to store urls`);\n }\n }\n return schema;\n}\n\n/**\n * A string's declared transforms — `trim`, `lowercase`, `uppercase` — applied.\n * The one definition of them: validation judges its result, and\n * {@link applyValueTransforms} writes it.\n */\nfunction transformString(value: string, validation: StringPropertyValidationSchema): string {\n let result = value;\n if (validation.trim) result = result.trim();\n if (validation.lowercase) result = result.toLowerCase();\n if (validation.uppercase) result = result.toUpperCase();\n return result;\n}\n\n/**\n * The values as they are to be written: every `trim`, `lowercase` and\n * `uppercase` a string property declares applied to its value, inside maps and\n * arrays too.\n *\n * They are documented as changing the value that is written, and only the\n * panel applies them — the server checks what it receives. Validation judges\n * the transformed value, so without this the form passed \"my-slug\" and sent\n * \" My-Slug \", which a `matches` on the server then refused.\n *\n * Returns `values` itself when nothing changes.\n */\nexport function applyValueTransforms<M extends Record<string, unknown>>(values: M, properties: Properties): M {\n let result: M = values;\n for (const [key, property] of Object.entries(properties)) {\n if (!(key in values)) continue;\n const transformed = transformValue(property, values[key]);\n if (transformed !== values[key]) {\n result = { ...result, [key]: transformed };\n }\n }\n return result;\n}\n\nfunction transformValue(property: Property, value: unknown): unknown {\n if (!property || typeof property !== \"object\") return value;\n if (property.type === \"string\") {\n return typeof value === \"string\" && property.validation\n ? transformString(value, property.validation)\n : value;\n }\n if (property.type === \"map\" && property.properties && isPlainObject(value)) {\n return applyValueTransforms(value, property.properties);\n }\n if (property.type === \"array\" && property.of && Array.isArray(value)) {\n const of = property.of;\n const items = value.map((item, index) => {\n const itemProperty = Array.isArray(of) ? of[index] : of;\n return itemProperty ? transformValue(itemProperty, item) : item;\n });\n return items.some((item, index) => item !== value[index]) ? items : value;\n }\n return value;\n}\n\nfunction getZodNumberSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<NumberProperty>): ZodTypeAny {\n const validation = property.validation;\n // Accept number or null, coerce non-numbers to fail\n let schema: ZodTypeAny = z.preprocess(\n (val) => {\n if (val === null || val === undefined) return null;\n if (typeof val === \"number\") return val;\n const n = Number(val);\n return isNaN(n) ? val : n; // pass through non-numeric to let refine catch it\n },\n z.number({ error: \"Must be a number\" }).nullable()\n );\n\n const isRequired = validation?.required || property.isId === true || property.isId === \"manual\";\n\n if (isRequired) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n if (validation) {\n\n if (validation.min || validation.min === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value >= validation.min!),\n { message: `${fieldLabel(property, name)} must be higher or equal to ${validation.min}` }\n );\n if (validation.max || validation.max === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value <= validation.max!),\n { message: `${fieldLabel(property, name)} must be lower or equal to ${validation.max}` }\n );\n if (validation.lessThan || validation.lessThan === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value < validation.lessThan!),\n { message: `${fieldLabel(property, name)} must be lower than ${validation.lessThan}` }\n );\n if (validation.moreThan || validation.moreThan === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value > validation.moreThan!),\n { message: `${fieldLabel(property, name)} must be higher than ${validation.moreThan}` }\n );\n if (validation.positive) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value > 0),\n { message: `${fieldLabel(property, name)} must be positive` }\n );\n if (validation.negative) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value < 0),\n { message: `${fieldLabel(property, name)} must be negative` }\n );\n }\n // An integer column takes a whole number whether or not the property says\n // `validation.integer`; without it, a fraction reached Postgres and came\n // back as `Invalid data format` naming no field.\n if (validation?.integer || isIntegerColumn(property.columnType)) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && Number.isInteger(value)),\n { message: `${fieldLabel(property, name)} must be an integer` }\n );\n return schema;\n}\n\nfunction getZodGeoPointSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<GeopointProperty>): ZodTypeAny {\n // The field marks a coordinate off the globe in red; the schema has to\n // refuse it too, or Save wrote latitude 200 under the red message.\n // A `GeoPoint` instance or a plain `{ latitude, longitude }`.\n const coordinate = (value: unknown, axis: \"latitude\" | \"longitude\"): number | undefined => {\n if (typeof value !== \"object\" || value === null) return undefined;\n const n = (value as Record<string, unknown>)[axis];\n return typeof n === \"number\" ? n : undefined;\n };\n let schema: ZodTypeAny = z.object({}).passthrough().nullable().optional()\n .refine(\n (value: unknown) => Math.abs(coordinate(value, \"latitude\") ?? 0) <= 90,\n { message: \"Latitude must be between -90 and 90\" }\n )\n .refine(\n (value: unknown) => Math.abs(coordinate(value, \"longitude\") ?? 0) <= 180,\n { message: \"Longitude must be between -180 and 180\" }\n );\n const validation = property.validation;\n\n if (validation?.required) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n return schema;\n}\n\nfunction getZodDateSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<DateProperty>): ZodTypeAny {\n if (property.autoValue) {\n return z.date().nullable().optional();\n }\n // Accept Date objects and null, reject everything else\n let schema: ZodTypeAny = z.custom<Date | null | undefined>(\n (v) => v === null || v === undefined || v instanceof Date,\n { message: \"Expected a Date\" }\n ).optional();\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n // Both bounds are inclusive, and the message says so: it said \"after\"\n // the bound, which the bound itself is not, and printed the bound with\n // `Date.toString()` (\"Wed Jan 01 2020 01:00:00 GMT+0100 (…)\").\n if (validation.min) schema = schema.refine(\n (value: unknown) => value == null || (value instanceof Date && value >= validation.min!),\n { message: `${fieldLabel(property, name)} must not be before ${formatDateBound(validation.min, property.columnType)}` }\n );\n if (validation.max) schema = schema.refine(\n (value: unknown) => value == null || (value instanceof Date && value <= validation.max!),\n { message: `${fieldLabel(property, name)} must not be after ${formatDateBound(validation.max, property.columnType)}` }\n );\n }\n return schema;\n}\n\nfunction getZodReferenceSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<ReferenceProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.object({}).passthrough().nullable().optional();\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n }\n return schema;\n}\n\nfunction getZodRelationSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<RelationProperty>): ZodTypeAny {\n const isMany = relationCardinality(property.relation) === \"many\";\n let schema: ZodTypeAny = isMany\n ? z.array(z.object({}).passthrough()).nullable().optional()\n : z.object({}).passthrough().nullable().optional();\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n schema = schema.refine(\n (value: unknown) => {\n if (isMany) {\n return value !== undefined && value !== null && Array.isArray(value) && value.length > 0;\n }\n return value !== undefined && value !== null;\n },\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n }\n return schema;\n}\n\nfunction getZodBooleanSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<BooleanProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.boolean().nullable().optional();\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n }\n return schema;\n}\n\n/** The Postgres number column types that hold whole numbers only. */\nfunction isIntegerColumn(columnType: string | undefined): boolean {\n return columnType === \"integer\" || columnType === \"bigint\" || columnType === \"serial\" || columnType === \"bigserial\";\n}\n\n/** A date bound as a reader writes it: the day for a date column, else an ISO instant. */\nfunction formatDateBound(bound: Date, columnType: string | undefined): string {\n const date = bound instanceof Date ? bound : new Date(bound);\n if (Number.isNaN(date.getTime())) return String(bound);\n return columnType === \"date\" ? date.toISOString().slice(0, 10) : date.toISOString();\n}\n\n/**\n * What `uniqueInArray` compares an item by. Relations and references are\n * objects built per read, so comparing them by identity never found the same\n * row linked twice; they compare by the row they point at.\n */\nfunction uniqueInArrayKey(value: unknown): unknown {\n if (value instanceof Date) return `date:${value.getTime()}`;\n if (typeof value === \"object\" && value !== null && \"id\" in value) {\n const { id, path } = value as { id?: unknown; path?: unknown };\n if (typeof id === \"string\" || typeof id === \"number\") return `row:${typeof path === \"string\" ? path : \"\"}:${String(id)}`;\n }\n return value;\n}\n\nfunction hasUniqueInArrayModifier(property: Property): boolean | [string, Property][] {\n if (property.validation?.uniqueInArray) {\n return true;\n } else if (property.type === \"map\" && property.properties) {\n return Object.entries(property.properties)\n .filter(([key, childProperty]) => (childProperty as Readonly<Property>).validation?.uniqueInArray) as [string, Property][];\n }\n return false;\n}\n\nfunction getZodArraySchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<ArrayProperty>): ZodTypeAny {\n\n let arraySchema: ZodTypeAny = z.array(z.any()).nullable().optional();\n\n if (!property.of && property.oneOf?.properties) {\n // Blocks: each item is `{ [typeField]: key, [valueField]: value }`, and\n // its value answers to `oneOf.properties[key]`, as an `of` item answers\n // to `of`. The error lands on `blocks.<i>.<valueField>`, which is the\n // key the block's inner field is bound to.\n const typeField = property.oneOf.typeField ?? DEFAULT_ONE_OF_TYPE;\n const valueField = property.oneOf.valueField ?? DEFAULT_ONE_OF_VALUE;\n const blockProperties = property.oneOf.properties as Record<string, Property>;\n const blockSchemas = new Map<string, ZodTypeAny>();\n const schemaFor = (type: string): ZodTypeAny | undefined => {\n if (!Object.prototype.hasOwnProperty.call(blockProperties, type)) return undefined;\n const blockProperty = blockProperties[type];\n if (!blockProperty || isPropertyBuilder(blockProperty)) return undefined;\n let schema = blockSchemas.get(type);\n if (!schema) {\n schema = mapPropertyToZod({ property: blockProperty, parentProperty: property, entityId, name: type });\n blockSchemas.set(type, schema);\n }\n return schema;\n };\n arraySchema = z.array(z.any()).superRefine(async (items, ctx) => {\n for (let index = 0; index < items.length; index++) {\n const item: unknown = items[index];\n if (!isPlainObject(item)) continue;\n const type = (item as Record<string, unknown>)[typeField];\n if (typeof type !== \"string\") continue;\n const schema = schemaFor(type);\n if (!schema) continue;\n const result = await schema.safeParseAsync((item as Record<string, unknown>)[valueField]);\n if (!result.success) {\n result.error.issues.forEach((issue) => {\n ctx.addIssue({\n code: \"custom\",\n message: issue.message,\n path: [index, valueField, ...issue.path]\n });\n });\n }\n }\n }).nullable().optional();\n }\n\n if (property.of) {\n if (Array.isArray(property.of)) {\n // One property per position: the value is a tuple, and item `i`\n // answers to `of[i]` alone. Checked against every position, a\n // mixed tuple failed its own declaration and could never be saved.\n const positionSchemas: ZodTypeAny[] = (property.of as Property[]).map((p, index) => {\n try {\n return mapPropertyToZod({\n property: p as Property,\n parentProperty: property,\n entityId\n });\n } catch (e: unknown) {\n console.error(`Error creating validation schema for array item ${index}:`, e);\n return z.any().refine(\n () => false,\n { message: `Validation error: ${e instanceof Error ? e.message : \"Unknown error\"}` }\n );\n }\n });\n arraySchema = z.array(z.any()).superRefine(async (items, ctx) => {\n for (let index = 0; index < items.length && index < positionSchemas.length; index++) {\n const result = await positionSchemas[index].safeParseAsync(items[index]);\n if (!result.success) {\n result.error.issues.forEach((issue) => {\n ctx.addIssue({\n code: \"custom\",\n message: issue.message,\n path: [index, ...issue.path]\n });\n });\n }\n }\n }).nullable().optional();\n } else {\n try {\n const ofSchema = mapPropertyToZod({\n property: property.of,\n parentProperty: property,\n entityId\n });\n arraySchema = z.array(ofSchema).nullable().optional();\n } catch (e: unknown) {\n console.error(\"Error creating validation schema for array of property:\", e);\n arraySchema = z.array(z.any().refine(\n () => false,\n { message: `Validation error: ${e instanceof Error ? e.message : \"Unknown error\"}` }\n )).nullable().optional();\n }\n const arrayUniqueFields = hasUniqueInArrayModifier(property.of);\n if (arrayUniqueFields) {\n if (typeof arrayUniqueFields === \"boolean\") {\n arraySchema = arraySchema.refine(\n (values: unknown) => !values || !Array.isArray(values) || values.length === new Set(values.map(uniqueInArrayKey)).size,\n { message: `${fieldLabel(property, name)} should have unique values within the array` }\n );\n } else if (Array.isArray(arrayUniqueFields)) {\n arrayUniqueFields.forEach(([fieldName, childProperty]) => {\n arraySchema = arraySchema.refine(\n (values: unknown) => !values || !Array.isArray(values) || values.length === new Set(values.map((v: unknown) => uniqueInArrayKey(v && typeof v === \"object\" ? (v as Record<string, unknown>)[fieldName] : v))).size,\n { message: `${fieldLabel(property, name)} → ${childProperty.name ?? fieldName}: should have unique values within the array` }\n );\n });\n }\n }\n }\n }\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n arraySchema = arraySchema.refine(\n (value: unknown) => value !== undefined && value !== null && Array.isArray(value) && value.length > 0,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n if (validation.min || validation.min === 0) arraySchema = arraySchema.refine(\n (value: unknown) => !value || !Array.isArray(value) || value.length >= validation.min!,\n { message: `${fieldLabel(property, name)} should be min ${validation.min} entries long` }\n );\n if (validation.max) arraySchema = arraySchema.refine(\n (value: unknown) => !value || !Array.isArray(value) || value.length <= validation.max!,\n { message: `${fieldLabel(property, name)} should be max ${validation.max} entries long` }\n );\n // Handle uniqueInArray at the array level\n if (validation.uniqueInArray) {\n arraySchema = arraySchema.refine(\n (values: unknown) => !values || !Array.isArray(values) || values.length === new Set(values.map(uniqueInArrayKey)).size,\n { message: `${fieldLabel(property, name)} should have unique values within the array` }\n );\n }\n }\n return arraySchema;\n}\n\nfunction getZodVectorSchema({\n property\n}: PropertyContext<VectorProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.preprocess(\n (val: unknown) => {\n if (val && typeof val === \"object\" && \"__type\" in val && (val as Record<string, unknown>).__type === \"Vector\") {\n return (val as Record<string, unknown>).value;\n }\n if (val && typeof val === \"object\" && \"value\" in val && Array.isArray((val as Record<string, unknown>).value)) {\n return (val as Record<string, unknown>).value;\n }\n return val;\n },\n z.array(z.number()).nullable().optional()\n );\n\n if (property.dimensions) {\n schema = schema.refine(\n (val: unknown) => val === null || val === undefined || (Array.isArray(val) && val.length === property.dimensions),\n { message: `${property.name ?? \"Vector\"} must have exactly ${property.dimensions} dimensions` }\n );\n }\n\n if (property.validation?.required) {\n schema = schema.refine(\n (val: unknown) => val !== null && val !== undefined && Array.isArray(val) && val.length > 0,\n { message: property.validation?.requiredMessage ?? \"Required\" }\n );\n }\n\n return schema;\n}\n\nfunction getZodBinarySchema({\n property\n}: PropertyContext<BinaryProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.string().nullable().optional();\n const validation = property.validation;\n\n if (validation?.required) {\n schema = schema.nullable().optional().refine(\n (value: unknown) => value !== undefined && value !== null && value !== \"\",\n { message: validation.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n return schema;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SAAS,WAAW,UAAoB,MAAuB;CAC3D,OAAO,SAAS,SAAS,OAAO,mBAAmB,IAAI,IAAI;AAC/D;AAEA,SAAS,oBAAoB,UAA2F;CACpH,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,IAAI,SAAS,SAAS,OAAO,OAAO,SAAS;CAC7C,IAAI,SAAS,SAAS,aAAa,SAAS,SAAS,cAAc,OAAO;CAC1E,IAAI,SAAS,SAAS,eAAe,SAAS,SAAS,UAAU,OAAO;CACxE,OAAO,SAAS;AACpB;;;;;;;;;;;;;AA+BA,eAAsB,kBAAkB,EACpC,YACA,QACA,cACA,UACA,QACA,aAQgC;CAChC,MAAM,QAAgC,CAAC;CACvC,MAAM,QAAQ,IAAI,OAAO,QAAQ,UAAsC,CAAC,CAAC,IAAI,OAAO,CAAC,MAAM,cAAc;EACrG,IAAI,CAAC,UAAU,YAAY,QAAQ;EACnC,IAAI,UAAU,QAAQ,QAAQ;EAC9B,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,IAAI;EAC3D,IAAI,gBAAgB,UAAY,OAAO,aAAa,KAAK,GAAG;EAE5D,IAAI,CAAC,MADgB,UAAU;GAAE;GAAM;GAAO;GAAU;EAAS,CAAC,GACrD,MAAM,QAAQ,GAAG,WAAW,UAAU,IAAI,EAAE;CAC7D,CAAC,CAAC;CACF,OAAO;AACX;AAEA,SAAgB,gBACZ,UACA,YACA,sBAAsF;CACtF,MAAM,QAAoC,CAAC;CAC3C,OAAO,QAAQ,UAAsC,CAAC,CACjD,SAAS,CAAC,MAAM,cAAc;EAE3B,MAAM,eADmB,SAAS,SAAS,YAAY,SAAS,SAAS,aACjC,UAAU,YAAY,OAAO,SAAS,SAAS,YAAY,SA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/validation.ts"],"sourcesContent":["import type { Properties } from \"@rebasepro/types\";\nimport type { ArrayProperty, MapProperty, NumberProperty, Property, BooleanProperty, DateProperty, GeopointProperty, ReferenceProperty, RelationProperty, StringProperty, StringPropertyValidationSchema, VectorProperty, BinaryProperty } from \"@rebasepro/types\";\n;\nimport { z, ZodTypeAny } from \"zod\";\nimport { deepEqual as isDeepEqual } from \"fast-equals\";\nimport { DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, enumToObjectEntries, isPropertyBuilder } from \"@rebasepro/common\";\nimport { getValueInPath, hydrateRegExp, isPlainObject, prettifyIdentifier } from \"@rebasepro/utils\";\n\n/** Whether an authored relation yields many rows. Derived from its kind. */\n/**\n * What to call this field in a validation message.\n *\n * `property.name` is the author's label and is optional — a headless project has\n * no panel and no reason to invent display names. Every message here\n * interpolated it directly, so an unnamed property produced\n * \"undefined must be min 3 characters long\" in front of a user.\n *\n * The fallback is the field's own key, prettified the same way the panel derives\n * a column header, so the message names the field the author would recognise.\n */\nfunction fieldLabel(property: Property, name?: string): string {\n return property.name ?? (name ? prettifyIdentifier(name) : \"This field\");\n}\n\nfunction relationCardinality(relation: { kind?: string; cardinality?: string } | undefined): \"one\" | \"many\" | undefined {\n if (!relation) return undefined;\n if (relation.kind === \"via\") return relation.cardinality as \"one\" | \"many\" | undefined;\n if (relation.kind === \"hasMany\" || relation.kind === \"manyToMany\") return \"many\";\n if (relation.kind === \"belongsTo\" || relation.kind === \"hasOne\") return \"one\";\n return relation.cardinality as \"one\" | \"many\" | undefined;\n}\n\n\nexport type CustomFieldValidator = (props: {\n name: string,\n value: unknown,\n property: Property,\n entityId?: string | number,\n parentProperty?: MapProperty | ArrayProperty,\n}) => Promise<boolean>;\n\ninterface PropertyContext<P extends Property> {\n property: P,\n parentProperty?: MapProperty | ArrayProperty,\n entityId?: string | number,\n customFieldValidator?: CustomFieldValidator,\n name?: string\n}\n\n/**\n * `validation.unique`, for the top-level properties that declare it: whether\n * another record already holds the value, asked of the data source through\n * `validator`. One error per field that fails, keyed like the schema's.\n *\n * Asked only for a value worth asking about — set (not empty), changed from\n * `storedValues` when there are any (a value the edit left alone is the stored\n * record's business, and it may predate the rule), and without an error of its\n * own already in `errors` — so a save makes one lookup per unique field it\n * actually changes, and typing makes none: this runs where validation runs, on\n * submit.\n */\nexport async function uniqueValueErrors({\n properties,\n values,\n storedValues,\n entityId,\n errors,\n validator\n}: {\n properties: Properties,\n values: Record<string, unknown>,\n storedValues?: Record<string, unknown>,\n entityId?: string | number,\n errors?: Record<string, unknown>,\n validator: CustomFieldValidator\n}): Promise<Record<string, string>> {\n const found: Record<string, string> = {};\n await Promise.all(Object.entries(properties as Record<string, Property>).map(async ([name, property]) => {\n if (!property?.validation?.unique) return;\n if (errors && name in errors) return;\n const value = values[name];\n if (value === undefined || value === null || value === \"\") return;\n if (storedValues && isDeepEqual(value, storedValues[name])) return;\n const unique = await validator({ name, value, property, entityId });\n if (!unique) found[name] = `${fieldLabel(property, name)} must be unique: another record already has this value`;\n }));\n return found;\n}\n\nexport function getEntitySchema<M extends Record<string, unknown>>(\n entityId: string | number | undefined,\n properties: Properties,\n customFieldValidator?: CustomFieldValidator): z.ZodObject<Record<string, ZodTypeAny>> {\n const shape: Record<string, ZodTypeAny> = {};\n Object.entries(properties as Record<string, Property>)\n .forEach(([name, property]) => {\n const isStringOrNumber = property.type === \"string\" || property.type === \"number\";\n const isIdAndAuto = isStringOrNumber && \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n if (entityId === undefined && isIdAndAuto) {\n return; // Skip validation for auto-generated IDs on new entities\n }\n shape[name] = mapPropertyToZod({\n property: property as Property,\n customFieldValidator,\n name,\n entityId\n });\n });\n return z.object(shape).passthrough();\n}\n\n\nexport function mapPropertyToZod(propertyContext: PropertyContext<Property>): ZodTypeAny {\n\n const property = propertyContext.property;\n if (isPropertyBuilder(property) && !property.type) {\n console.error(\"Error in property\", propertyContext);\n // Return a schema that always fails\n return z.any().refine(\n () => false,\n { message: \"Invalid property configuration: property builder should be resolved\" }\n );\n }\n\n if (property.type === \"string\") {\n return getZodStringSchema(propertyContext as PropertyContext<StringProperty>);\n } else if (property.type === \"number\") {\n return getZodNumberSchema(propertyContext as PropertyContext<NumberProperty>);\n } else if (property.type === \"boolean\") {\n return getZodBooleanSchema(propertyContext as PropertyContext<BooleanProperty>);\n } else if (property.type === \"map\") {\n return getZodMapObjectSchema(propertyContext as PropertyContext<MapProperty>);\n } else if (property.type === \"array\") {\n return getZodArraySchema(propertyContext as PropertyContext<ArrayProperty>);\n } else if (property.type === \"date\") {\n return getZodDateSchema(propertyContext as PropertyContext<DateProperty>);\n } else if (property.type === \"geopoint\") {\n return getZodGeoPointSchema(propertyContext as PropertyContext<GeopointProperty>);\n } else if (property.type === \"reference\") {\n return getZodReferenceSchema(propertyContext as PropertyContext<ReferenceProperty>);\n } else if (property.type === \"relation\") {\n return getZodRelationSchema(propertyContext as PropertyContext<RelationProperty>);\n } else if (property.type === \"vector\") {\n return getZodVectorSchema(propertyContext as PropertyContext<VectorProperty>);\n } else if (property.type === \"binary\") {\n return getZodBinarySchema(propertyContext as PropertyContext<BinaryProperty>);\n }\n\n // Log the error but don't crash the form\n console.error(\"Unsupported data type in zod mapping\", property);\n const dataType = \"dataType\" in (property as Record<string, unknown>) ? String((property as Record<string, unknown>).dataType) : \"unknown\";\n return z.any().refine(\n () => false,\n { message: `Unsupported data type: ${dataType}` }\n );\n}\n\n\nexport function getZodMapObjectSchema({\n property,\n entityId,\n customFieldValidator,\n name\n}: PropertyContext<MapProperty>): ZodTypeAny {\n const shape: Record<string, ZodTypeAny> = {};\n const validation = property.validation;\n if (property.properties)\n Object.entries(property.properties).forEach(([childName, childProperty]) => {\n const typedChildProperty = childProperty as Readonly<Property>;\n try {\n shape[childName] = mapPropertyToZod({\n property: typedChildProperty,\n parentProperty: property as MapProperty,\n customFieldValidator,\n name: `${name}[${childName}]`,\n entityId\n });\n } catch (e: unknown) {\n console.error(`Error creating validation schema for property ${childName}:`, e);\n shape[childName] = z.any().refine(\n () => false,\n { message: `Validation error: ${e instanceof Error ? e.message : \"Unknown error\"}` }\n );\n }\n });\n\n let schema: ZodTypeAny = z.object(shape).passthrough();\n if (validation?.required) {\n schema = schema.nullable().optional().refine(\n (value) => value !== undefined,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n } else {\n schema = schema.nullable().optional();\n }\n return schema;\n}\n\nfunction getZodStringSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<StringProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.string().nullable().optional();\n const validation = property.validation;\n\n const isRequired = validation?.required || property.isId === true || property.isId === \"manual\";\n\n if (property.enum) {\n if (isRequired) {\n schema = z.string().nullable().optional().refine(\n (value) => value !== undefined && value !== null && value !== \"\",\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n const entries = enumToObjectEntries(property.enum);\n const allowedValues = (isRequired ? entries : [...entries, null])\n .map((enumValueConfig) => enumValueConfig?.id ?? null);\n schema = schema.refine(\n (value: unknown) => allowedValues.includes(value as string | null),\n { message: `Must be one of: ${allowedValues.filter(Boolean).join(\", \")}` }\n );\n }\n\n if (isRequired && !property.enum) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null && value !== \"\",\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n if (validation) {\n\n if (validation.min || validation.min === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"string\" && value.length >= validation.min!),\n { message: `${fieldLabel(property, name)} must be min ${validation.min} characters long` }\n );\n if (validation.max || validation.max === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"string\" && value.length <= validation.max!),\n { message: `${fieldLabel(property, name)} must be max ${validation.max} characters long` }\n );\n if (validation.matches) {\n const regExp = toMatchesPattern(validation.matches);\n if (regExp) {\n schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"string\" && regExp.test(value)),\n { message: validation.matchesMessage ?? \"Invalid format\" }\n );\n }\n }\n if (validation.length !== undefined) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"string\" && value.length === validation.length),\n { message: `${fieldLabel(property, name)} must be exactly ${validation.length} characters long` }\n );\n if (validation.trim || validation.lowercase || validation.uppercase) schema = z.preprocess(\n (v: unknown) => typeof v === \"string\" ? transformString(v, validation) : v,\n schema\n );\n }\n\n // Checked the way the server checks them: on every string that declares\n // them, `validation` block or not, and with the empty string let through —\n // it is what a cleared text field holds, and whether the field may be\n // empty is `required`'s question.\n if (property.email) schema = schema.refine(\n (value: unknown) => value == null || value === \"\" || (typeof value === \"string\" && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)),\n { message: `${fieldLabel(property, name)} must be an email` }\n );\n if (property.url) {\n if (!property.storage || property.storage?.storeUrl) {\n schema = schema.refine(\n (value: unknown) => {\n if (value == null || value === \"\") return true;\n try {\n new URL(value as string);\n return true;\n } catch {\n return false;\n }\n },\n { message: `${fieldLabel(property, name)} must be a url` }\n );\n } else {\n console.warn(`Property ${fieldLabel(property, name)} has a url validation but its storage configuration is not set to store urls`);\n }\n }\n return schema;\n}\n\n/**\n * `validation.matches` as a regex that answers the same for the same value\n * every time. A `g` or `y` regex keeps `lastIndex` between `test` calls, so a\n * value it accepted once it refused on the next validation; the flags are\n * dropped, as the server's write validation drops them.\n */\nfunction toMatchesPattern(matches: string | RegExp): RegExp | undefined {\n const regExp = typeof matches === \"string\" ? hydrateRegExp(matches) : matches;\n if (!regExp) return undefined;\n return regExp.global || regExp.sticky ? new RegExp(regExp.source, regExp.flags.replace(/[gy]/g, \"\")) : regExp;\n}\n\n/**\n * A string's declared transforms — `trim`, `lowercase`, `uppercase` — applied.\n * The one definition of them: validation judges its result, and\n * {@link applyValueTransforms} writes it.\n */\nfunction transformString(value: string, validation: StringPropertyValidationSchema): string {\n let result = value;\n if (validation.trim) result = result.trim();\n if (validation.lowercase) result = result.toLowerCase();\n if (validation.uppercase) result = result.toUpperCase();\n return result;\n}\n\n/**\n * The values as they are to be written: every `trim`, `lowercase` and\n * `uppercase` a string property declares applied to its value, inside maps and\n * arrays too.\n *\n * They are documented as changing the value that is written, and only the\n * panel applies them — the server checks what it receives. Validation judges\n * the transformed value, so without this the form passed \"my-slug\" and sent\n * \" My-Slug \", which a `matches` on the server then refused.\n *\n * Returns `values` itself when nothing changes.\n */\nexport function applyValueTransforms<M extends Record<string, unknown>>(values: M, properties: Properties): M {\n let result: M = values;\n for (const [key, property] of Object.entries(properties)) {\n if (!(key in values)) continue;\n const transformed = transformValue(property, values[key]);\n if (transformed !== values[key]) {\n result = { ...result, [key]: transformed };\n }\n }\n return result;\n}\n\nfunction transformValue(property: Property, value: unknown): unknown {\n if (!property || typeof property !== \"object\") return value;\n if (property.type === \"string\") {\n return typeof value === \"string\" && property.validation\n ? transformString(value, property.validation)\n : value;\n }\n if (property.type === \"map\" && property.properties && isPlainObject(value)) {\n return applyValueTransforms(value, property.properties);\n }\n if (property.type === \"array\" && property.of && Array.isArray(value)) {\n const of = property.of;\n const items = value.map((item, index) => {\n const itemProperty = Array.isArray(of) ? of[index] : of;\n return itemProperty ? transformValue(itemProperty, item) : item;\n });\n return items.some((item, index) => item !== value[index]) ? items : value;\n }\n return value;\n}\n\nfunction getZodNumberSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<NumberProperty>): ZodTypeAny {\n const validation = property.validation;\n // Accept number or null, coerce non-numbers to fail\n let schema: ZodTypeAny = z.preprocess(\n (val) => {\n if (val === null || val === undefined) return null;\n if (typeof val === \"number\") return val;\n const n = Number(val);\n return isNaN(n) ? val : n; // pass through non-numeric to let refine catch it\n },\n z.number({ error: \"Must be a number\" }).nullable()\n );\n\n const isRequired = validation?.required || property.isId === true || property.isId === \"manual\";\n\n if (isRequired) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n if (validation) {\n\n if (validation.min || validation.min === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value >= validation.min!),\n { message: `${fieldLabel(property, name)} must be higher or equal to ${validation.min}` }\n );\n if (validation.max || validation.max === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value <= validation.max!),\n { message: `${fieldLabel(property, name)} must be lower or equal to ${validation.max}` }\n );\n if (validation.lessThan || validation.lessThan === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value < validation.lessThan!),\n { message: `${fieldLabel(property, name)} must be lower than ${validation.lessThan}` }\n );\n if (validation.moreThan || validation.moreThan === 0) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value > validation.moreThan!),\n { message: `${fieldLabel(property, name)} must be higher than ${validation.moreThan}` }\n );\n if (validation.positive) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value > 0),\n { message: `${fieldLabel(property, name)} must be positive` }\n );\n if (validation.negative) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && value < 0),\n { message: `${fieldLabel(property, name)} must be negative` }\n );\n }\n // An integer column takes a whole number whether or not the property says\n // `validation.integer`; without it, a fraction reached Postgres and came\n // back as `Invalid data format` naming no field.\n if (validation?.integer || isIntegerColumn(property.columnType)) schema = schema.refine(\n (value: unknown) => value == null || (typeof value === \"number\" && Number.isInteger(value)),\n { message: `${fieldLabel(property, name)} must be an integer` }\n );\n return schema;\n}\n\nfunction getZodGeoPointSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<GeopointProperty>): ZodTypeAny {\n // The field marks a coordinate off the globe in red; the schema has to\n // refuse it too, or Save wrote latitude 200 under the red message.\n // A `GeoPoint` instance or a plain `{ latitude, longitude }`.\n const coordinate = (value: unknown, axis: \"latitude\" | \"longitude\"): number | undefined => {\n if (typeof value !== \"object\" || value === null) return undefined;\n const n = (value as Record<string, unknown>)[axis];\n return typeof n === \"number\" ? n : undefined;\n };\n let schema: ZodTypeAny = z.object({}).passthrough().nullable().optional()\n .refine(\n (value: unknown) => Math.abs(coordinate(value, \"latitude\") ?? 0) <= 90,\n { message: \"Latitude must be between -90 and 90\" }\n )\n .refine(\n (value: unknown) => Math.abs(coordinate(value, \"longitude\") ?? 0) <= 180,\n { message: \"Longitude must be between -180 and 180\" }\n );\n const validation = property.validation;\n\n if (validation?.required) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n return schema;\n}\n\nfunction getZodDateSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<DateProperty>): ZodTypeAny {\n if (property.autoValue) {\n return z.date().nullable().optional();\n }\n // Accept Date objects and null, reject everything else\n let schema: ZodTypeAny = z.custom<Date | null | undefined>(\n (v) => v === null || v === undefined || v instanceof Date,\n { message: \"Expected a Date\" }\n ).optional();\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n // Both bounds are inclusive, and the message says so: it said \"after\"\n // the bound, which the bound itself is not, and printed the bound with\n // `Date.toString()` (\"Wed Jan 01 2020 01:00:00 GMT+0100 (…)\").\n if (validation.min) schema = schema.refine(\n (value: unknown) => value == null || (value instanceof Date && value >= validation.min!),\n { message: `${fieldLabel(property, name)} must not be before ${formatDateBound(validation.min, property.columnType)}` }\n );\n if (validation.max) schema = schema.refine(\n (value: unknown) => value == null || (value instanceof Date && value <= validation.max!),\n { message: `${fieldLabel(property, name)} must not be after ${formatDateBound(validation.max, property.columnType)}` }\n );\n }\n return schema;\n}\n\nfunction getZodReferenceSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<ReferenceProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.object({}).passthrough().nullable().optional();\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n }\n return schema;\n}\n\nfunction getZodRelationSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<RelationProperty>): ZodTypeAny {\n const isMany = relationCardinality(property.relation) === \"many\";\n let schema: ZodTypeAny = isMany\n ? z.array(z.object({}).passthrough()).nullable().optional()\n : z.object({}).passthrough().nullable().optional();\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n schema = schema.refine(\n (value: unknown) => {\n if (isMany) {\n return value !== undefined && value !== null && Array.isArray(value) && value.length > 0;\n }\n return value !== undefined && value !== null;\n },\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n }\n return schema;\n}\n\nfunction getZodBooleanSchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<BooleanProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.boolean().nullable().optional();\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n schema = schema.refine(\n (value: unknown) => value !== undefined && value !== null,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n\n }\n return schema;\n}\n\n/** The Postgres number column types that hold whole numbers only. */\nfunction isIntegerColumn(columnType: string | undefined): boolean {\n return columnType === \"integer\" || columnType === \"bigint\" || columnType === \"serial\" || columnType === \"bigserial\";\n}\n\n/** A date bound as a reader writes it: the day for a date column, else an ISO instant. */\nfunction formatDateBound(bound: Date, columnType: string | undefined): string {\n const date = bound instanceof Date ? bound : new Date(bound);\n if (Number.isNaN(date.getTime())) return String(bound);\n return columnType === \"date\" ? date.toISOString().slice(0, 10) : date.toISOString();\n}\n\n/**\n * What `uniqueInArray` compares an item by. Relations and references are\n * objects built per read, so comparing them by identity never found the same\n * row linked twice; they compare by the row they point at.\n */\nfunction uniqueInArrayKey(value: unknown): unknown {\n if (value instanceof Date) return `date:${value.getTime()}`;\n if (typeof value === \"object\" && value !== null && \"id\" in value) {\n const { id, path } = value as { id?: unknown; path?: unknown };\n if (typeof id === \"string\" || typeof id === \"number\") return `row:${typeof path === \"string\" ? path : \"\"}:${String(id)}`;\n }\n return value;\n}\n\nfunction hasUniqueInArrayModifier(property: Property): boolean | [string, Property][] {\n if (property.validation?.uniqueInArray) {\n return true;\n } else if (property.type === \"map\" && property.properties) {\n return Object.entries(property.properties)\n .filter(([key, childProperty]) => (childProperty as Readonly<Property>).validation?.uniqueInArray) as [string, Property][];\n }\n return false;\n}\n\nfunction getZodArraySchema({\n property,\n parentProperty,\n customFieldValidator,\n name,\n entityId\n}: PropertyContext<ArrayProperty>): ZodTypeAny {\n\n let arraySchema: ZodTypeAny = z.array(z.any()).nullable().optional();\n\n if (!property.of && property.oneOf?.properties) {\n // Blocks: each item is `{ [typeField]: key, [valueField]: value }`, and\n // its value answers to `oneOf.properties[key]`, as an `of` item answers\n // to `of`. The error lands on `blocks.<i>.<valueField>`, which is the\n // key the block's inner field is bound to.\n const typeField = property.oneOf.typeField ?? DEFAULT_ONE_OF_TYPE;\n const valueField = property.oneOf.valueField ?? DEFAULT_ONE_OF_VALUE;\n const blockProperties = property.oneOf.properties as Record<string, Property>;\n const blockSchemas = new Map<string, ZodTypeAny>();\n const schemaFor = (type: string): ZodTypeAny | undefined => {\n if (!Object.prototype.hasOwnProperty.call(blockProperties, type)) return undefined;\n const blockProperty = blockProperties[type];\n if (!blockProperty || isPropertyBuilder(blockProperty)) return undefined;\n let schema = blockSchemas.get(type);\n if (!schema) {\n schema = mapPropertyToZod({ property: blockProperty, parentProperty: property, entityId, name: type });\n blockSchemas.set(type, schema);\n }\n return schema;\n };\n arraySchema = z.array(z.any()).superRefine(async (items, ctx) => {\n for (let index = 0; index < items.length; index++) {\n const item: unknown = items[index];\n if (!isPlainObject(item)) continue;\n const type = (item as Record<string, unknown>)[typeField];\n if (typeof type !== \"string\") continue;\n const schema = schemaFor(type);\n if (!schema) continue;\n const result = await schema.safeParseAsync((item as Record<string, unknown>)[valueField]);\n if (!result.success) {\n result.error.issues.forEach((issue) => {\n ctx.addIssue({\n code: \"custom\",\n message: issue.message,\n path: [index, valueField, ...issue.path]\n });\n });\n }\n }\n }).nullable().optional();\n }\n\n if (property.of) {\n if (Array.isArray(property.of)) {\n // One property per position: the value is a tuple, and item `i`\n // answers to `of[i]` alone. Checked against every position, a\n // mixed tuple failed its own declaration and could never be saved.\n const positionSchemas: ZodTypeAny[] = (property.of as Property[]).map((p, index) => {\n try {\n return mapPropertyToZod({\n property: p as Property,\n parentProperty: property,\n entityId\n });\n } catch (e: unknown) {\n console.error(`Error creating validation schema for array item ${index}:`, e);\n return z.any().refine(\n () => false,\n { message: `Validation error: ${e instanceof Error ? e.message : \"Unknown error\"}` }\n );\n }\n });\n arraySchema = z.array(z.any()).superRefine(async (items, ctx) => {\n for (let index = 0; index < items.length && index < positionSchemas.length; index++) {\n const result = await positionSchemas[index].safeParseAsync(items[index]);\n if (!result.success) {\n result.error.issues.forEach((issue) => {\n ctx.addIssue({\n code: \"custom\",\n message: issue.message,\n path: [index, ...issue.path]\n });\n });\n }\n }\n }).nullable().optional();\n } else {\n try {\n const ofSchema = mapPropertyToZod({\n property: property.of,\n parentProperty: property,\n entityId\n });\n arraySchema = z.array(ofSchema).nullable().optional();\n } catch (e: unknown) {\n console.error(\"Error creating validation schema for array of property:\", e);\n arraySchema = z.array(z.any().refine(\n () => false,\n { message: `Validation error: ${e instanceof Error ? e.message : \"Unknown error\"}` }\n )).nullable().optional();\n }\n const arrayUniqueFields = hasUniqueInArrayModifier(property.of);\n if (arrayUniqueFields) {\n if (typeof arrayUniqueFields === \"boolean\") {\n arraySchema = arraySchema.refine(\n (values: unknown) => !values || !Array.isArray(values) || values.length === new Set(values.map(uniqueInArrayKey)).size,\n { message: `${fieldLabel(property, name)} should have unique values within the array` }\n );\n } else if (Array.isArray(arrayUniqueFields)) {\n arrayUniqueFields.forEach(([fieldName, childProperty]) => {\n arraySchema = arraySchema.refine(\n (values: unknown) => !values || !Array.isArray(values) || values.length === new Set(values.map((v: unknown) => uniqueInArrayKey(v && typeof v === \"object\" ? (v as Record<string, unknown>)[fieldName] : v))).size,\n { message: `${fieldLabel(property, name)} → ${childProperty.name ?? fieldName}: should have unique values within the array` }\n );\n });\n }\n }\n }\n }\n const validation = property.validation;\n\n if (validation) {\n if (validation.required) {\n arraySchema = arraySchema.refine(\n (value: unknown) => value !== undefined && value !== null && Array.isArray(value) && value.length > 0,\n { message: validation?.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n if (validation.min || validation.min === 0) arraySchema = arraySchema.refine(\n (value: unknown) => !value || !Array.isArray(value) || value.length >= validation.min!,\n { message: `${fieldLabel(property, name)} should be min ${validation.min} entries long` }\n );\n if (validation.max) arraySchema = arraySchema.refine(\n (value: unknown) => !value || !Array.isArray(value) || value.length <= validation.max!,\n { message: `${fieldLabel(property, name)} should be max ${validation.max} entries long` }\n );\n // Handle uniqueInArray at the array level\n if (validation.uniqueInArray) {\n arraySchema = arraySchema.refine(\n (values: unknown) => !values || !Array.isArray(values) || values.length === new Set(values.map(uniqueInArrayKey)).size,\n { message: `${fieldLabel(property, name)} should have unique values within the array` }\n );\n }\n }\n return arraySchema;\n}\n\nfunction getZodVectorSchema({\n property\n}: PropertyContext<VectorProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.preprocess(\n (val: unknown) => {\n if (val && typeof val === \"object\" && \"__type\" in val && (val as Record<string, unknown>).__type === \"Vector\") {\n return (val as Record<string, unknown>).value;\n }\n if (val && typeof val === \"object\" && \"value\" in val && Array.isArray((val as Record<string, unknown>).value)) {\n return (val as Record<string, unknown>).value;\n }\n return val;\n },\n z.array(z.number()).nullable().optional()\n );\n\n if (property.dimensions) {\n schema = schema.refine(\n (val: unknown) => val === null || val === undefined || (Array.isArray(val) && val.length === property.dimensions),\n { message: `${property.name ?? \"Vector\"} must have exactly ${property.dimensions} dimensions` }\n );\n }\n\n if (property.validation?.required) {\n schema = schema.refine(\n (val: unknown) => val !== null && val !== undefined && Array.isArray(val) && val.length > 0,\n { message: property.validation?.requiredMessage ?? \"Required\" }\n );\n }\n\n return schema;\n}\n\nfunction getZodBinarySchema({\n property\n}: PropertyContext<BinaryProperty>): ZodTypeAny {\n let schema: ZodTypeAny = z.string().nullable().optional();\n const validation = property.validation;\n\n if (validation?.required) {\n schema = schema.nullable().optional().refine(\n (value: unknown) => value !== undefined && value !== null && value !== \"\",\n { message: validation.requiredMessage ? validation.requiredMessage : \"Required\" }\n );\n }\n return schema;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SAAS,WAAW,UAAoB,MAAuB;CAC3D,OAAO,SAAS,SAAS,OAAO,mBAAmB,IAAI,IAAI;AAC/D;AAEA,SAAS,oBAAoB,UAA2F;CACpH,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,IAAI,SAAS,SAAS,OAAO,OAAO,SAAS;CAC7C,IAAI,SAAS,SAAS,aAAa,SAAS,SAAS,cAAc,OAAO;CAC1E,IAAI,SAAS,SAAS,eAAe,SAAS,SAAS,UAAU,OAAO;CACxE,OAAO,SAAS;AACpB;;;;;;;;;;;;;AA+BA,eAAsB,kBAAkB,EACpC,YACA,QACA,cACA,UACA,QACA,aAQgC;CAChC,MAAM,QAAgC,CAAC;CACvC,MAAM,QAAQ,IAAI,OAAO,QAAQ,UAAsC,CAAC,CAAC,IAAI,OAAO,CAAC,MAAM,cAAc;EACrG,IAAI,CAAC,UAAU,YAAY,QAAQ;EACnC,IAAI,UAAU,QAAQ,QAAQ;EAC9B,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,IAAI;EAC3D,IAAI,gBAAgB,UAAY,OAAO,aAAa,KAAK,GAAG;EAE5D,IAAI,CAAC,MADgB,UAAU;GAAE;GAAM;GAAO;GAAU;EAAS,CAAC,GACrD,MAAM,QAAQ,GAAG,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A,KAAa,MAAM,QAAQ,GAAG,KAAK,IAAI,SAAS,GAC1F,EAAE,SAAS,SAAS,YAAY,mBAAmB,WAAW,CAClE;CAGJ,OAAO;AACX;AAEA,SAAS,mBAAmB,EACxB,YAC4C;CAC5C,IAAI,SAAqB,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CACxD,MAAM,aAAa,SAAS;CAE5B,IAAI,YAAY,UACZ,SAAS,OAAO,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,QACjC,UAAmB,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,IACvE,EAAE,SAAS,WAAW,kBAAkB,WAAW,kBAAkB,WAAW,CACpF;CAEJ,OAAO;AACX"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * How a data path (`products/café/variants/a#b`) and the URL path that names
3
+ * it (`products/caf%C3%A9/variants/a%23b`) map onto each other.
4
+ *
5
+ * A record id is whatever string the database holds, so it is written into a
6
+ * URL one percent-encoded segment at a time: raw, a `#` or `?` ends the path
7
+ * and the rest reads as the hash or the query, and the browser hands the
8
+ * router a pathname it has percent-encoded itself. Each segment is encoded
9
+ * once where a URL is built and decoded once where a URL is read.
10
+ */
11
+ /** One data-path segment (a slug part, a record id, a tab key) as a URL path segment. */
12
+ export declare function encodeUrlPathSegment(segment: string): string;
13
+ /**
14
+ * One URL path segment as the data-path segment it names.
15
+ *
16
+ * A segment whose escapes are malformed (a bare `%` typed into the address
17
+ * bar) is not an encoded one, so it is kept as it is. An encoded slash stays
18
+ * encoded: a data path is split on `/`, and decoding it would turn the record
19
+ * `a/b` into the record `a` followed by a tab `b`.
20
+ */
21
+ export declare function decodeUrlPathSegment(segment: string): string;
22
+ /** A data path as a URL path: every segment encoded, the separators kept. */
23
+ export declare function encodeUrlPath(path: string): string;
24
+ /** A URL path as a data path: every segment decoded, the separators kept. */
25
+ export declare function decodeUrlPath(path: string): string;
26
+ /**
27
+ * What a pathname holds after the record at `recordUrl`, the record's tab or
28
+ * `edit`, as data-path segments joined by `/`. Matched segment by segment on
29
+ * decoded text, so the record is found however the pathname spells its id.
30
+ * Empty when nothing follows the record, `undefined` when the pathname is not
31
+ * at or below it.
32
+ */
33
+ export declare function getPathAfterRecord(pathname: string, recordUrl: string): string | undefined;
@@ -0,0 +1,56 @@
1
+ //#region src/hooks/navigation/url_segments.ts
2
+ /**
3
+ * How a data path (`products/café/variants/a#b`) and the URL path that names
4
+ * it (`products/caf%C3%A9/variants/a%23b`) map onto each other.
5
+ *
6
+ * A record id is whatever string the database holds, so it is written into a
7
+ * URL one percent-encoded segment at a time: raw, a `#` or `?` ends the path
8
+ * and the rest reads as the hash or the query, and the browser hands the
9
+ * router a pathname it has percent-encoded itself. Each segment is encoded
10
+ * once where a URL is built and decoded once where a URL is read.
11
+ */
12
+ /** One data-path segment (a slug part, a record id, a tab key) as a URL path segment. */
13
+ function encodeUrlPathSegment(segment) {
14
+ return encodeURIComponent(segment);
15
+ }
16
+ /**
17
+ * One URL path segment as the data-path segment it names.
18
+ *
19
+ * A segment whose escapes are malformed (a bare `%` typed into the address
20
+ * bar) is not an encoded one, so it is kept as it is. An encoded slash stays
21
+ * encoded: a data path is split on `/`, and decoding it would turn the record
22
+ * `a/b` into the record `a` followed by a tab `b`.
23
+ */
24
+ function decodeUrlPathSegment(segment) {
25
+ try {
26
+ return decodeURIComponent(segment).replace(/\//g, "%2F");
27
+ } catch {
28
+ return segment;
29
+ }
30
+ }
31
+ /** A data path as a URL path: every segment encoded, the separators kept. */
32
+ function encodeUrlPath(path) {
33
+ return path.split("/").map(encodeUrlPathSegment).join("/");
34
+ }
35
+ /** A URL path as a data path: every segment decoded, the separators kept. */
36
+ function decodeUrlPath(path) {
37
+ return path.split("/").map(decodeUrlPathSegment).join("/");
38
+ }
39
+ /**
40
+ * What a pathname holds after the record at `recordUrl`, the record's tab or
41
+ * `edit`, as data-path segments joined by `/`. Matched segment by segment on
42
+ * decoded text, so the record is found however the pathname spells its id.
43
+ * Empty when nothing follows the record, `undefined` when the pathname is not
44
+ * at or below it.
45
+ */
46
+ function getPathAfterRecord(pathname, recordUrl) {
47
+ const pathSegments = pathname.split("/");
48
+ const recordSegments = recordUrl.split("/");
49
+ if (pathSegments.length < recordSegments.length) return void 0;
50
+ for (let i = 0; i < recordSegments.length; i++) if (decodeUrlPathSegment(pathSegments[i]) !== decodeUrlPathSegment(recordSegments[i])) return void 0;
51
+ return pathSegments.slice(recordSegments.length).filter((segment) => segment.length > 0).map(decodeUrlPathSegment).join("/");
52
+ }
53
+ //#endregion
54
+ export { decodeUrlPath, decodeUrlPathSegment, encodeUrlPath, encodeUrlPathSegment, getPathAfterRecord };
55
+
56
+ //# sourceMappingURL=url_segments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url_segments.js","names":[],"sources":["../../../src/hooks/navigation/url_segments.ts"],"sourcesContent":["/**\n * How a data path (`products/café/variants/a#b`) and the URL path that names\n * it (`products/caf%C3%A9/variants/a%23b`) map onto each other.\n *\n * A record id is whatever string the database holds, so it is written into a\n * URL one percent-encoded segment at a time: raw, a `#` or `?` ends the path\n * and the rest reads as the hash or the query, and the browser hands the\n * router a pathname it has percent-encoded itself. Each segment is encoded\n * once where a URL is built and decoded once where a URL is read.\n */\n\n/** One data-path segment (a slug part, a record id, a tab key) as a URL path segment. */\nexport function encodeUrlPathSegment(segment: string): string {\n return encodeURIComponent(segment);\n}\n\n/**\n * One URL path segment as the data-path segment it names.\n *\n * A segment whose escapes are malformed (a bare `%` typed into the address\n * bar) is not an encoded one, so it is kept as it is. An encoded slash stays\n * encoded: a data path is split on `/`, and decoding it would turn the record\n * `a/b` into the record `a` followed by a tab `b`.\n */\nexport function decodeUrlPathSegment(segment: string): string {\n try {\n return decodeURIComponent(segment).replace(/\\//g, \"%2F\");\n } catch {\n return segment;\n }\n}\n\n/** A data path as a URL path: every segment encoded, the separators kept. */\nexport function encodeUrlPath(path: string): string {\n return path.split(\"/\").map(encodeUrlPathSegment).join(\"/\");\n}\n\n/** A URL path as a data path: every segment decoded, the separators kept. */\nexport function decodeUrlPath(path: string): string {\n return path.split(\"/\").map(decodeUrlPathSegment).join(\"/\");\n}\n\n/**\n * What a pathname holds after the record at `recordUrl`, the record's tab or\n * `edit`, as data-path segments joined by `/`. Matched segment by segment on\n * decoded text, so the record is found however the pathname spells its id.\n * Empty when nothing follows the record, `undefined` when the pathname is not\n * at or below it.\n */\nexport function getPathAfterRecord(pathname: string, recordUrl: string): string | undefined {\n const pathSegments = pathname.split(\"/\");\n const recordSegments = recordUrl.split(\"/\");\n if (pathSegments.length < recordSegments.length)\n return undefined;\n for (let i = 0; i < recordSegments.length; i++) {\n if (decodeUrlPathSegment(pathSegments[i]) !== decodeUrlPathSegment(recordSegments[i]))\n return undefined;\n }\n return pathSegments.slice(recordSegments.length)\n .filter((segment) => segment.length > 0)\n .map(decodeUrlPathSegment)\n .join(\"/\");\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAgB,qBAAqB,SAAyB;CAC1D,OAAO,mBAAmB,OAAO;AACrC;;;;;;;;;AAUA,SAAgB,qBAAqB,SAAyB;CAC1D,IAAI;EACA,OAAO,mBAAmB,OAAO,CAAC,CAAC,QAAQ,OAAO,KAAK;CAC3D,QAAQ;EACJ,OAAO;CACX;AACJ;;AAGA,SAAgB,cAAc,MAAsB;CAChD,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,oBAAoB,CAAC,CAAC,KAAK,GAAG;AAC7D;;AAGA,SAAgB,cAAc,MAAsB;CAChD,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,oBAAoB,CAAC,CAAC,KAAK,GAAG;AAC7D;;;;;;;;AASA,SAAgB,mBAAmB,UAAkB,WAAuC;CACxF,MAAM,eAAe,SAAS,MAAM,GAAG;CACvC,MAAM,iBAAiB,UAAU,MAAM,GAAG;CAC1C,IAAI,aAAa,SAAS,eAAe,QACrC,OAAO,KAAA;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,KACvC,IAAI,qBAAqB,aAAa,EAAE,MAAM,qBAAqB,eAAe,EAAE,GAChF,OAAO,KAAA;CAEf,OAAO,aAAa,MAAM,eAAe,MAAM,CAAC,CAC3C,QAAQ,YAAY,QAAQ,SAAS,CAAC,CAAC,CACvC,IAAI,oBAAoB,CAAC,CACzB,KAAK,GAAG;AACjB"}
@@ -1,3 +1,4 @@
1
+ import { decodeUrlPath, encodeUrlPath } from "./url_segments.js";
1
2
  import { useCallback, useMemo } from "react";
2
3
  import { removeInitialAndTrailingSlashes, resolveCollectionPathIds } from "@rebasepro/app";
3
4
  import { useNavigate } from "react-router";
@@ -7,7 +8,8 @@ function useBuildUrlController(props) {
7
8
  const navigate = useNavigate();
8
9
  const homeUrl = basePath === "/" ? "/" : `/${removeInitialAndTrailingSlashes(basePath)}`;
9
10
  const buildUrlCollectionPath = useCallback((path) => {
10
- return (basePath === "/" ? `${baseCollectionPath}/${path}` : `${basePath}${baseCollectionPath}/${path}`).replace(/\/\//g, "/");
11
+ const urlPath = encodeUrlPath(path);
12
+ return (basePath === "/" ? `${baseCollectionPath}/${urlPath}` : `${basePath}${baseCollectionPath}/${urlPath}`).replace(/\/\//g, "/");
11
13
  }, [basePath, baseCollectionPath]);
12
14
  const buildAppUrlPath = useCallback((path) => {
13
15
  return (basePath === "/" ? `/${path}` : `${basePath}/${path}`).replace(/\/\//g, "/");
@@ -16,7 +18,7 @@ function useBuildUrlController(props) {
16
18
  let path = cmsPath;
17
19
  if (basePath !== "/" && path.startsWith(basePath)) path = path.replace(basePath, "");
18
20
  if (path.startsWith(baseCollectionPath)) path = path.replace(baseCollectionPath, "");
19
- return removeInitialAndTrailingSlashes(path);
21
+ return decodeUrlPath(removeInitialAndTrailingSlashes(path));
20
22
  }, [basePath, baseCollectionPath]);
21
23
  const isUrlCollectionPath = useCallback((urlPath) => {
22
24
  let path = urlPath;
@@ -1 +1 @@
1
- {"version":3,"file":"useBuildUrlController.js","names":[],"sources":["../../../src/hooks/navigation/useBuildUrlController.tsx"],"sourcesContent":["import type { UrlController, NavigateOptions } from \"@rebasepro/cms-types\";\nimport { useCallback, useMemo } from \"react\";\nimport { removeInitialAndTrailingSlashes, resolveCollectionPathIds } from \"@rebasepro/app\";\nimport { CollectionRegistryController } from \"@rebasepro/types\";\nimport { useNavigate } from \"react-router\";\n\nexport function useBuildUrlController(props: {\n basePath: string,\n baseCollectionPath: string,\n collectionRegistryController: CollectionRegistryController\n}): UrlController {\n\n const { basePath, baseCollectionPath, collectionRegistryController } = props;\n const navigate = useNavigate();\n\n const homeUrl = basePath === \"/\" ? \"/\" : `/${removeInitialAndTrailingSlashes(basePath)}`;\n\n const buildUrlCollectionPath = useCallback((path: string): string => {\n const fullPath = basePath === \"/\" ? `${baseCollectionPath}/${path}` : `${basePath}${baseCollectionPath}/${path}`;\n return fullPath.replace(/\\/\\//g, \"/\");\n }, [basePath, baseCollectionPath]);\n\n const buildAppUrlPath = useCallback((path: string): string => {\n const fullPath = basePath === \"/\" ? `/${path}` : `${basePath}/${path}`;\n return fullPath.replace(/\\/\\//g, \"/\");\n }, [basePath]);\n\n const urlPathToDataPath = useCallback((cmsPath: string): string => {\n let path = cmsPath;\n if (basePath !== \"/\" && path.startsWith(basePath)) {\n path = path.replace(basePath, \"\");\n }\n if (path.startsWith(baseCollectionPath)) {\n path = path.replace(baseCollectionPath, \"\");\n }\n return removeInitialAndTrailingSlashes(path);\n }, [basePath, baseCollectionPath]);\n\n const isUrlCollectionPath = useCallback((urlPath: string): boolean => {\n let path = urlPath;\n if (basePath !== \"/\" && path.startsWith(basePath)) {\n path = path.replace(basePath, \"\");\n }\n return path === baseCollectionPath || path.startsWith(baseCollectionPath + \"/\");\n }, [basePath, baseCollectionPath]);\n\n const resolveDatabasePathsFrom = useCallback((path: string): string => {\n return resolveCollectionPathIds(path, collectionRegistryController.collections ?? []);\n }, [collectionRegistryController]);\n\n const navigateTo = useCallback((to: string, options?: NavigateOptions) => {\n navigate(to, options);\n }, [navigate]);\n\n return useMemo(() => ({\n basePath,\n baseCollectionPath,\n urlPathToDataPath,\n homeUrl,\n isUrlCollectionPath,\n buildUrlCollectionPath,\n buildAppUrlPath,\n resolveDatabasePathsFrom,\n navigate: navigateTo\n }), [basePath, baseCollectionPath, urlPathToDataPath, homeUrl, isUrlCollectionPath, buildUrlCollectionPath, buildAppUrlPath, resolveDatabasePathsFrom, navigateTo]);\n}\n"],"mappings":";;;;AAMA,SAAgB,sBAAsB,OAIpB;CAEd,MAAM,EAAE,UAAU,oBAAoB,iCAAiC;CACvE,MAAM,WAAW,YAAY;CAE7B,MAAM,UAAU,aAAa,MAAM,MAAM,IAAI,gCAAgC,QAAQ;CAErF,MAAM,yBAAyB,aAAa,SAAyB;EAEjE,QADiB,aAAa,MAAM,GAAG,mBAAmB,GAAG,SAAS,GAAG,WAAW,mBAAmB,GAAG,OAAA,CAC1F,QAAQ,SAAS,GAAG;CACxC,GAAG,CAAC,UAAU,kBAAkB,CAAC;CAEjC,MAAM,kBAAkB,aAAa,SAAyB;EAE1D,QADiB,aAAa,MAAM,IAAI,SAAS,GAAG,SAAS,GAAG,OAAA,CAChD,QAAQ,SAAS,GAAG;CACxC,GAAG,CAAC,QAAQ,CAAC;CAEb,MAAM,oBAAoB,aAAa,YAA4B;EAC/D,IAAI,OAAO;EACX,IAAI,aAAa,OAAO,KAAK,WAAW,QAAQ,GAC5C,OAAO,KAAK,QAAQ,UAAU,EAAE;EAEpC,IAAI,KAAK,WAAW,kBAAkB,GAClC,OAAO,KAAK,QAAQ,oBAAoB,EAAE;EAE9C,OAAO,gCAAgC,IAAI;CAC/C,GAAG,CAAC,UAAU,kBAAkB,CAAC;CAEjC,MAAM,sBAAsB,aAAa,YAA6B;EAClE,IAAI,OAAO;EACX,IAAI,aAAa,OAAO,KAAK,WAAW,QAAQ,GAC5C,OAAO,KAAK,QAAQ,UAAU,EAAE;EAEpC,OAAO,SAAS,sBAAsB,KAAK,WAAW,qBAAqB,GAAG;CAClF,GAAG,CAAC,UAAU,kBAAkB,CAAC;CAEjC,MAAM,2BAA2B,aAAa,SAAyB;EACnE,OAAO,yBAAyB,MAAM,6BAA6B,eAAe,CAAC,CAAC;CACxF,GAAG,CAAC,4BAA4B,CAAC;CAEjC,MAAM,aAAa,aAAa,IAAY,YAA8B;EACtE,SAAS,IAAI,OAAO;CACxB,GAAG,CAAC,QAAQ,CAAC;CAEb,OAAO,eAAe;EAClB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU;CACd,IAAI;EAAC;EAAU;EAAoB;EAAmB;EAAS;EAAqB;EAAwB;EAAiB;EAA0B;CAAU,CAAC;AACtK"}
1
+ {"version":3,"file":"useBuildUrlController.js","names":[],"sources":["../../../src/hooks/navigation/useBuildUrlController.tsx"],"sourcesContent":["import type { UrlController, NavigateOptions } from \"@rebasepro/cms-types\";\nimport { useCallback, useMemo } from \"react\";\nimport { removeInitialAndTrailingSlashes, resolveCollectionPathIds } from \"@rebasepro/app\";\nimport { CollectionRegistryController } from \"@rebasepro/types\";\nimport { useNavigate } from \"react-router\";\nimport { decodeUrlPath, encodeUrlPath } from \"./url_segments\";\n\nexport function useBuildUrlController(props: {\n basePath: string,\n baseCollectionPath: string,\n collectionRegistryController: CollectionRegistryController\n}): UrlController {\n\n const { basePath, baseCollectionPath, collectionRegistryController } = props;\n const navigate = useNavigate();\n\n const homeUrl = basePath === \"/\" ? \"/\" : `/${removeInitialAndTrailingSlashes(basePath)}`;\n\n // `path` is a data path: each of its segments, record ids included, is\n // written percent-encoded, and a query or hash goes after the result.\n const buildUrlCollectionPath = useCallback((path: string): string => {\n const urlPath = encodeUrlPath(path);\n const fullPath = basePath === \"/\" ? `${baseCollectionPath}/${urlPath}` : `${basePath}${baseCollectionPath}/${urlPath}`;\n return fullPath.replace(/\\/\\//g, \"/\");\n }, [basePath, baseCollectionPath]);\n\n const buildAppUrlPath = useCallback((path: string): string => {\n const fullPath = basePath === \"/\" ? `/${path}` : `${basePath}/${path}`;\n return fullPath.replace(/\\/\\//g, \"/\");\n }, [basePath]);\n\n const urlPathToDataPath = useCallback((cmsPath: string): string => {\n let path = cmsPath;\n if (basePath !== \"/\" && path.startsWith(basePath)) {\n path = path.replace(basePath, \"\");\n }\n if (path.startsWith(baseCollectionPath)) {\n path = path.replace(baseCollectionPath, \"\");\n }\n // The pathname arrives percent-encoded, by the browser or by\n // `buildUrlCollectionPath`; the data path holds the ids themselves.\n return decodeUrlPath(removeInitialAndTrailingSlashes(path));\n }, [basePath, baseCollectionPath]);\n\n const isUrlCollectionPath = useCallback((urlPath: string): boolean => {\n let path = urlPath;\n if (basePath !== \"/\" && path.startsWith(basePath)) {\n path = path.replace(basePath, \"\");\n }\n return path === baseCollectionPath || path.startsWith(baseCollectionPath + \"/\");\n }, [basePath, baseCollectionPath]);\n\n const resolveDatabasePathsFrom = useCallback((path: string): string => {\n return resolveCollectionPathIds(path, collectionRegistryController.collections ?? []);\n }, [collectionRegistryController]);\n\n const navigateTo = useCallback((to: string, options?: NavigateOptions) => {\n navigate(to, options);\n }, [navigate]);\n\n return useMemo(() => ({\n basePath,\n baseCollectionPath,\n urlPathToDataPath,\n homeUrl,\n isUrlCollectionPath,\n buildUrlCollectionPath,\n buildAppUrlPath,\n resolveDatabasePathsFrom,\n navigate: navigateTo\n }), [basePath, baseCollectionPath, urlPathToDataPath, homeUrl, isUrlCollectionPath, buildUrlCollectionPath, buildAppUrlPath, resolveDatabasePathsFrom, navigateTo]);\n}\n"],"mappings":";;;;;AAOA,SAAgB,sBAAsB,OAIpB;CAEd,MAAM,EAAE,UAAU,oBAAoB,iCAAiC;CACvE,MAAM,WAAW,YAAY;CAE7B,MAAM,UAAU,aAAa,MAAM,MAAM,IAAI,gCAAgC,QAAQ;CAIrF,MAAM,yBAAyB,aAAa,SAAyB;EACjE,MAAM,UAAU,cAAc,IAAI;EAElC,QADiB,aAAa,MAAM,GAAG,mBAAmB,GAAG,YAAY,GAAG,WAAW,mBAAmB,GAAG,UAAA,CAC7F,QAAQ,SAAS,GAAG;CACxC,GAAG,CAAC,UAAU,kBAAkB,CAAC;CAEjC,MAAM,kBAAkB,aAAa,SAAyB;EAE1D,QADiB,aAAa,MAAM,IAAI,SAAS,GAAG,SAAS,GAAG,OAAA,CAChD,QAAQ,SAAS,GAAG;CACxC,GAAG,CAAC,QAAQ,CAAC;CAEb,MAAM,oBAAoB,aAAa,YAA4B;EAC/D,IAAI,OAAO;EACX,IAAI,aAAa,OAAO,KAAK,WAAW,QAAQ,GAC5C,OAAO,KAAK,QAAQ,UAAU,EAAE;EAEpC,IAAI,KAAK,WAAW,kBAAkB,GAClC,OAAO,KAAK,QAAQ,oBAAoB,EAAE;EAI9C,OAAO,cAAc,gCAAgC,IAAI,CAAC;CAC9D,GAAG,CAAC,UAAU,kBAAkB,CAAC;CAEjC,MAAM,sBAAsB,aAAa,YAA6B;EAClE,IAAI,OAAO;EACX,IAAI,aAAa,OAAO,KAAK,WAAW,QAAQ,GAC5C,OAAO,KAAK,QAAQ,UAAU,EAAE;EAEpC,OAAO,SAAS,sBAAsB,KAAK,WAAW,qBAAqB,GAAG;CAClF,GAAG,CAAC,UAAU,kBAAkB,CAAC;CAEjC,MAAM,2BAA2B,aAAa,SAAyB;EACnE,OAAO,yBAAyB,MAAM,6BAA6B,eAAe,CAAC,CAAC;CACxF,GAAG,CAAC,4BAA4B,CAAC;CAEjC,MAAM,aAAa,aAAa,IAAY,YAA8B;EACtE,SAAS,IAAI,OAAO;CACxB,GAAG,CAAC,QAAQ,CAAC;CAEb,OAAO,eAAe;EAClB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU;CACd,IAAI;EAAC;EAAU;EAAoB;EAAmB;EAAS;EAAqB;EAAwB;EAAiB;EAA0B;CAAU,CAAC;AACtK"}
@@ -2,6 +2,7 @@ import { LazySidePanelBinding } from "../components/lazy_record_views.js";
2
2
  import { Suspense, useCallback, useEffect, useMemo, useRef } from "react";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  import { CircularProgressCenter } from "@rebasepro/ui";
5
+ import { hasEntityId } from "@rebasepro/common";
5
6
  import { CONTAINER_FULL_WIDTH, CollectionScopeProvider, SIDE_PANEL_DEFAULT_WIDTH, getNavigationEntriesFromPath, removeInitialAndTrailingSlashes, removeTrailingSlash, resolveDefaultSelectedView, useComponentOverride, useCustomizationController, useLargeLayout } from "@rebasepro/app";
6
7
  import { useLocation } from "react-router";
7
8
  //#region src/hooks/useBuildSidePanel.tsx
@@ -106,9 +107,9 @@ var useBuildSidePanel = (collectionRegistryController, urlController, navigation
106
107
  updateUrl: false,
107
108
  allowFullScreen: false
108
109
  };
109
- if (props.copy && !props.entityId) throw Error("If you want to copy a entity you need to provide a entityId");
110
+ if (props.copy && !hasEntityId(props.entityId)) throw Error("If you want to copy a entity you need to provide a entityId");
110
111
  const defaultSelectedView = resolveDefaultSelectedView(props.collection ? props.collection.defaultSelectedView : void 0, {
111
- status: props.copy ? "copy" : props.entityId ? "existing" : "new",
112
+ status: props.copy ? "copy" : hasEntityId(props.entityId) ? "existing" : "new",
112
113
  entityId: props.entityId
113
114
  });
114
115
  sideDialogsController.open(propsToSidePanel({
@@ -129,7 +130,7 @@ var useBuildSidePanel = (collectionRegistryController, urlController, navigation
129
130
  updateUrl: false,
130
131
  allowFullScreen: false
131
132
  };
132
- if (props.copy && !props.entityId) throw Error("If you want to copy a entity you need to provide a entityId");
133
+ if (props.copy && !hasEntityId(props.entityId)) throw Error("If you want to copy a entity you need to provide a entityId");
133
134
  sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));
134
135
  }, [
135
136
  urlController.buildUrlCollectionPath,
@@ -183,7 +184,7 @@ function buildSidePanelsFromUrl(path, collections, newFlag) {
183
184
  if (sidePanel && !sidePanel.selectedTab && removeTrailingSlash(path).endsWith("/edit")) sidePanel.selectedTab = "edit";
184
185
  if (sidePanel && !sidePanel.selectedTab && sidePanel.collection) {
185
186
  const defaultView = resolveDefaultSelectedView(sidePanel.collection.defaultSelectedView, {
186
- status: sidePanel.copy ? "copy" : sidePanel.entityId ? "existing" : "new",
187
+ status: sidePanel.copy ? "copy" : hasEntityId(sidePanel.entityId) ? "existing" : "new",
187
188
  entityId: sidePanel.entityId
188
189
  });
189
190
  if (defaultView) sidePanel.selectedTab = defaultView;
@@ -198,7 +199,7 @@ var propsToSidePanel = (props, buildUrlCollectionPath, resolveIdsFrom, smallLayo
198
199
  const collectionPath = removeInitialAndTrailingSlashes(props.path);
199
200
  const locationSearch = typeof window !== "undefined" ? window.location.search : "";
200
201
  const shouldUpdateUrl = props.updateUrl !== false;
201
- const urlPath = shouldUpdateUrl ? props.entityId ? buildUrlCollectionPath(`${collectionPath}/${props.entityId}${props.selectedTab ? "/" + props.selectedTab : ""}${locationSearch}#${SIDE_URL_HASH}`) : buildUrlCollectionPath(`${collectionPath}${locationSearch}#${NEW_URL_HASH}`) : void 0;
202
+ const urlPath = shouldUpdateUrl ? hasEntityId(props.entityId) ? `${buildUrlCollectionPath(`${collectionPath}/${props.entityId}${props.selectedTab ? "/" + props.selectedTab : ""}`)}${locationSearch}#${SIDE_URL_HASH}` : `${buildUrlCollectionPath(collectionPath)}${locationSearch}#${NEW_URL_HASH}` : void 0;
202
203
  const parentUrlPath = shouldUpdateUrl ? buildUrlCollectionPath(collectionPath) : void 0;
203
204
  const resolvedPanelProps = {
204
205
  ...props,
@@ -1 +1 @@
1
- {"version":3,"file":"useBuildSidePanel.js","names":[],"sources":["../../src/hooks/useBuildSidePanel.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport type { CustomizationController, SidePanelBindingProps, SideDialogPanelProps, SideDialogsController, SidePanelController, UrlController, NavigationStateController, AdminCollection } from \"@rebasepro/cms-types\";\nimport { useCallback, useEffect, useRef, useMemo } from \"react\";\nimport { CollectionRegistryController } from \"@rebasepro/types\";\nimport { AuthController } from \"@rebasepro/cms-types\";\nimport { useLocation } from \"react-router\";\nimport { NavigationViewInternal } from \"@rebasepro/app\";\nimport { getNavigationEntriesFromPath, removeInitialAndTrailingSlashes, removeTrailingSlash, resolveDefaultSelectedView } from \"@rebasepro/app\";\nimport { resolvedSelectedEntityView } from \"../util/resolutions\";\nimport { CONTAINER_FULL_WIDTH, SIDE_PANEL_DEFAULT_WIDTH } from \"@rebasepro/app\";\nimport { useCustomizationController, useLargeLayout, useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { JSON_TAB_VALUE, HISTORY_TAB_VALUE } from \"../util/view_constants\";\nimport React, { Suspense } from \"react\";\nimport { CircularProgressCenter } from \"@rebasepro/ui\";\n// Lazy: this hook runs on every page (the side-panel provider is mounted by\n// RebaseNavigation), and the panel's form stack is not needed until one opens.\nimport { LazySidePanelBinding as SidePanelBinding } from \"../components/lazy_record_views\";\n\n/**\n * Thin wrapper that resolves the Entity.SidePanel component override.\n * Because the JSX is created inside `propsToSidePanel` (a plain function,\n * not a React component), we need this wrapper so the hook is called at the\n * top level of a React component per the Rules of Hooks.\n */\nfunction ResolvedSidePanelBindingInner(props: SidePanelBindingProps) {\n const Resolved = useComponentOverride<SidePanelBindingProps>(\"Entity.SidePanel\", SidePanelBinding);\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Resolved {...props}/>\n </Suspense>;\n}\n\nfunction ResolvedSidePanelBinding(props: SidePanelBindingProps) {\n if (props.collection) {\n return (\n <CollectionScopeProvider collection={props.collection}>\n <ResolvedSidePanelBindingInner {...props}/>\n </CollectionScopeProvider>\n );\n }\n return <ResolvedSidePanelBindingInner {...props}/>;\n}\n\nconst NEW_URL_HASH = \"new_side\";\nconst SIDE_URL_HASH = \"side\";\n\n/**\n * How wide the side panel opens.\n *\n * One width for the whole panel, whatever tab is showing. It used to depend on\n * the selected tab — the form got one width and a subcollection or custom view\n * got `calc(55vw + 768px)` — so the panel physically resized under the cursor\n * every time you switched tabs. And the \"form\" width was derived from how\n * deeply nested the collection's *properties* were, which is not a thing anyone\n * can predict from looking at the panel.\n *\n * Now: `width` prop, then the collection's `sideDialogWidth`, then a default\n * sized for the content the panel actually has to hold — the form column plus\n * its metadata rail — capped so it never eats the whole window.\n */\nexport function getEntityViewWidth(props: SidePanelBindingProps<any>, small: boolean, customizationController: CustomizationController): string {\n if (small) return CONTAINER_FULL_WIDTH;\n\n if (props.width) {\n return typeof props.width === \"number\" ? `${props.width}px` : props.width;\n }\n if (props.collection?.sideDialogWidth) {\n return typeof props.collection.sideDialogWidth === \"number\"\n ? `${props.collection.sideDialogWidth}px`\n : props.collection.sideDialogWidth;\n }\n return SIDE_PANEL_DEFAULT_WIDTH;\n}\n\nexport const useBuildSidePanel = (collectionRegistryController: CollectionRegistryController,\n urlController: UrlController,\n navigationStateController: NavigationStateController,\n sideDialogsController: SideDialogsController,\n authController: AuthController\n): SidePanelController => {\n\n const location = useLocation();\n const initialised = useRef<boolean>(false);\n const currentPanelKeysRef = useRef<string[]>([]);\n const customizationController = useCustomizationController();\n\n const smallLayout = !useLargeLayout();\n\n useEffect(() => {\n\n const newFlag = location.hash === `#${NEW_URL_HASH}`;\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n\n if (!navigationStateController.loading) {\n if ((newFlag || sideFlag) && urlController.isUrlCollectionPath(location.pathname)) {\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], newFlag);\n for (let i = 0; i < panelsFromUrl.length; i++) {\n const props = panelsFromUrl[i];\n if (i === 0)\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n else\n sideDialogsController.open(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController))\n }\n }\n initialised.current = true;\n }\n }, [navigationStateController.loading]);\n\n // sync panels if URL changes with #side\n // Use a ref for currentPanelKeys so this effect only fires on URL changes,\n // not on panel state changes. This prevents a race condition with React Router 7\n // where close() clears panels before the URL updates, causing the effect to\n // re-open the panel from the stale #side hash.\n currentPanelKeysRef.current = sideDialogsController.sidePanels.map(p => p.key);\n useEffect(() => {\n if (initialised.current) {\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n if (sideFlag) {\n const currentKeys = currentPanelKeysRef.current;\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], false);\n // if we have more panels than determined by the url, we ignore the url. We might have references open\n if (panelsFromUrl.length <= currentKeys.length) {\n return;\n }\n const lastPanel = panelsFromUrl[panelsFromUrl.length - 1];\n const panelProps = propsToSidePanel(lastPanel, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController);\n const lastCurrentPanel = currentKeys.length > 0 ? currentKeys[currentKeys.length - 1] : undefined;\n if (!lastCurrentPanel || lastCurrentPanel !== panelProps.key) {\n sideDialogsController.replace(panelProps);\n }\n }\n }\n }, [location.pathname, location.hash]);\n\n // update side panels to match browser size\n // Only update panel widths on layout change — don't recreate components.\n // Recreating components would unmount/remount SidePanelBinding, losing\n // scroll position, unsaved form state, and triggering unnecessary data fetches.\n useEffect(() => {\n const updatedSidePanels = sideDialogsController.sidePanels.map(sidePanelProps => {\n if (sidePanelProps.additional) {\n const entityProps = sidePanelProps.additional as SidePanelBindingProps;\n const newWidth = getEntityViewWidth(entityProps, smallLayout, customizationController);\n if (sidePanelProps.width !== newWidth) {\n return { ...sidePanelProps,\nwidth: newWidth };\n }\n }\n return sidePanelProps;\n });\n sideDialogsController.setSidePanels(updatedSidePanels);\n }, [smallLayout]);\n\n const close = useCallback(() => {\n sideDialogsController.close();\n }, [sideDialogsController]);\n\n // Where no CMS route serves the page, a panel is an overlay and nothing\n // more: it writes no URL (one would lead nowhere) and offers no way to a\n // full-screen route that does not exist.\n const routesMounted = urlController.routesMounted !== false;\n\n const open = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !props.entityId) {\n throw Error(\"If you want to copy a entity you need to provide a entityId\");\n }\n\n const defaultSelectedView = resolveDefaultSelectedView(\n props.collection ? props.collection.defaultSelectedView : undefined,\n {\n status: props.copy ? \"copy\" : (props.entityId ? \"existing\" : \"new\"),\n entityId: props.entityId\n }\n );\n\n sideDialogsController.open(\n propsToSidePanel({\n ...props,\n selectedTab: props.selectedTab ?? defaultSelectedView\n },\n urlController.buildUrlCollectionPath,\n urlController.resolveDatabasePathsFrom,\n smallLayout,\n customizationController,\n authController\n ));\n\n }, [sideDialogsController, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, authController.user, routesMounted]);\n\n const replace = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !props.entityId) {\n throw Error(\"If you want to copy a entity you need to provide a entityId\");\n }\n\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n\n }, [urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, sideDialogsController, smallLayout, authController.user, routesMounted]);\n\n return useMemo(() => ({\n close,\n open,\n replace\n }), [close, open, replace]);\n};\n\nexport function buildSidePanelsFromUrl(path: string, collections: AdminCollection[], newFlag: boolean): SidePanelBindingProps<any>[] {\n\n const navigationViewsForPath: NavigationViewInternal<any>[] = getNavigationEntriesFromPath({\n path,\n collections\n });\n\n let sidePanel: SidePanelBindingProps<any> | undefined = undefined;\n let lastCollectionPath = \"\";\n let lastCollectionId: string | undefined = undefined;\n for (let i = 0; i < navigationViewsForPath.length; i++) {\n const navigationEntry = navigationViewsForPath[i];\n\n if (navigationEntry.type === \"collection\") {\n lastCollectionPath = navigationEntry.slug;\n lastCollectionId = navigationEntry.collection.slug;\n }\n\n const previousEntry = navigationViewsForPath[i - 1];\n if (navigationEntry.type === \"entity\") {\n sidePanel = {\n path: navigationEntry.slug,\n entityId: navigationEntry.entityId,\n copy: false,\n collection: navigationEntry.parentCollection,\n width: navigationEntry.parentCollection?.sideDialogWidth\n };\n } else if (navigationEntry.type === \"custom_view\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.view.key;\n }\n } else if (navigationEntry.type === \"collection\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.collection.slug;\n }\n }\n\n }\n\n // `edit` is not a registered view, so the navigation parser skips it. Pick it\n // up from the raw path so that reloading an edit URL reopens the edit form\n // rather than silently dropping the user back on the detail view.\n if (sidePanel && !sidePanel.selectedTab && removeTrailingSlash(path).endsWith(\"/edit\")) {\n sidePanel.selectedTab = \"edit\";\n }\n\n // When the URL doesn't contain a tab segment but the collection has a\n // defaultSelectedView, resolve it so the panel opens with the correct\n // width and the URL is updated on the next replace() cycle.\n if (sidePanel && !sidePanel.selectedTab && sidePanel.collection) {\n const defaultView = resolveDefaultSelectedView(\n sidePanel.collection.defaultSelectedView,\n {\n status: sidePanel.copy ? \"copy\" : (sidePanel.entityId ? \"existing\" : \"new\"),\n entityId: sidePanel.entityId\n }\n );\n if (defaultView) {\n sidePanel.selectedTab = defaultView;\n }\n }\n\n if (newFlag) {\n sidePanel = {\n path: lastCollectionPath,\n copy: false\n }\n }\n\n return sidePanel ? [sidePanel] : [];\n}\n\nconst propsToSidePanel = (props: SidePanelBindingProps,\n buildUrlCollectionPath: (path: string) => string,\n resolveIdsFrom: (pathWithAliases: string) => string,\n smallLayout: boolean,\n customizationController: CustomizationController,\n authController: AuthController\n): SideDialogPanelProps => {\n\n const collectionPath = removeInitialAndTrailingSlashes(props.path);\n\n // The list's state — search, filters, sort, view mode — read from the\n // address bar at the moment the panel opens. Not react-router's\n // `location.search`: the list writes its state with `replaceState`, which\n // the router does not observe, so that value is whatever the view mounted\n // with, and the list reads a panel URL built from it back as its state.\n const locationSearch = typeof window !== \"undefined\" ? window.location.search : \"\";\n\n // When updateUrl is explicitly false, don't generate URL paths — the dialog\n // opens as an overlay without affecting the browser URL / router.\n const shouldUpdateUrl = props.updateUrl !== false;\n\n const urlPath = shouldUpdateUrl\n ? (props.entityId\n ? buildUrlCollectionPath(`${collectionPath}/${props.entityId}${props.selectedTab ? \"/\" + props.selectedTab : \"\"}${locationSearch}#${SIDE_URL_HASH}`)\n : buildUrlCollectionPath(`${collectionPath}${locationSearch}#${NEW_URL_HASH}`))\n : undefined;\n\n const parentUrlPath = shouldUpdateUrl\n ? buildUrlCollectionPath(collectionPath)\n : undefined;\n\n const resolvedPanelProps: SidePanelBindingProps<any> = {\n ...props,\n formProps: props.formProps\n };\n\n const entityViewWidth = getEntityViewWidth(props, smallLayout, customizationController);\n return {\n key: `${props.path}/${props.entityId}`,\n component: <ResolvedSidePanelBinding {...resolvedPanelProps}/>,\n urlPath: urlPath,\n parentUrlPath: parentUrlPath,\n width: entityViewWidth,\n onClose: props.onClose,\n additional: resolvedPanelProps\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAyBA,SAAS,8BAA8B,OAA8B;CACjE,MAAM,WAAW,qBAA4C,oBAAoB,oBAAgB;CACjG,OAAO,oBAAC,UAAD;EAAU,UAAU,oBAAC,wBAAD,CAAwB,CAAA;YAC/C,oBAAC,UAAD,EAAU,GAAI,MAAO,CAAA;CACf,CAAA;AACd;AAEA,SAAS,yBAAyB,OAA8B;CAC5D,IAAI,MAAM,YACN,OACI,oBAAC,yBAAD;EAAyB,YAAY,MAAM;YACvC,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;CACrB,CAAA;CAGjC,OAAO,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;AACrD;AAEA,IAAM,eAAe;AACrB,IAAM,gBAAgB;;;;;;;;;;;;;;;AAgBtB,SAAgB,mBAAmB,OAAmC,OAAgB,yBAA0D;CAC5I,IA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uildSidePanel.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport { hasEntityId } from \"@rebasepro/common\";\nimport type { CustomizationController, SidePanelBindingProps, SideDialogPanelProps, SideDialogsController, SidePanelController, UrlController, NavigationStateController, AdminCollection } from \"@rebasepro/cms-types\";\nimport { useCallback, useEffect, useRef, useMemo } from \"react\";\nimport { CollectionRegistryController } from \"@rebasepro/types\";\nimport { AuthController } from \"@rebasepro/cms-types\";\nimport { useLocation } from \"react-router\";\nimport { NavigationViewInternal } from \"@rebasepro/app\";\nimport { getNavigationEntriesFromPath, removeInitialAndTrailingSlashes, removeTrailingSlash, resolveDefaultSelectedView } from \"@rebasepro/app\";\nimport { resolvedSelectedEntityView } from \"../util/resolutions\";\nimport { CONTAINER_FULL_WIDTH, SIDE_PANEL_DEFAULT_WIDTH } from \"@rebasepro/app\";\nimport { useCustomizationController, useLargeLayout, useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { JSON_TAB_VALUE, HISTORY_TAB_VALUE } from \"../util/view_constants\";\nimport React, { Suspense } from \"react\";\nimport { CircularProgressCenter } from \"@rebasepro/ui\";\n// Lazy: this hook runs on every page (the side-panel provider is mounted by\n// RebaseNavigation), and the panel's form stack is not needed until one opens.\nimport { LazySidePanelBinding as SidePanelBinding } from \"../components/lazy_record_views\";\n\n/**\n * Thin wrapper that resolves the Entity.SidePanel component override.\n * Because the JSX is created inside `propsToSidePanel` (a plain function,\n * not a React component), we need this wrapper so the hook is called at the\n * top level of a React component per the Rules of Hooks.\n */\nfunction ResolvedSidePanelBindingInner(props: SidePanelBindingProps) {\n const Resolved = useComponentOverride<SidePanelBindingProps>(\"Entity.SidePanel\", SidePanelBinding);\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Resolved {...props}/>\n </Suspense>;\n}\n\nfunction ResolvedSidePanelBinding(props: SidePanelBindingProps) {\n if (props.collection) {\n return (\n <CollectionScopeProvider collection={props.collection}>\n <ResolvedSidePanelBindingInner {...props}/>\n </CollectionScopeProvider>\n );\n }\n return <ResolvedSidePanelBindingInner {...props}/>;\n}\n\nconst NEW_URL_HASH = \"new_side\";\nconst SIDE_URL_HASH = \"side\";\n\n/**\n * How wide the side panel opens.\n *\n * One width for the whole panel, whatever tab is showing. It used to depend on\n * the selected tab — the form got one width and a subcollection or custom view\n * got `calc(55vw + 768px)` — so the panel physically resized under the cursor\n * every time you switched tabs. And the \"form\" width was derived from how\n * deeply nested the collection's *properties* were, which is not a thing anyone\n * can predict from looking at the panel.\n *\n * Now: `width` prop, then the collection's `sideDialogWidth`, then a default\n * sized for the content the panel actually has to hold — the form column plus\n * its metadata rail — capped so it never eats the whole window.\n */\nexport function getEntityViewWidth(props: SidePanelBindingProps<any>, small: boolean, customizationController: CustomizationController): string {\n if (small) return CONTAINER_FULL_WIDTH;\n\n if (props.width) {\n return typeof props.width === \"number\" ? `${props.width}px` : props.width;\n }\n if (props.collection?.sideDialogWidth) {\n return typeof props.collection.sideDialogWidth === \"number\"\n ? `${props.collection.sideDialogWidth}px`\n : props.collection.sideDialogWidth;\n }\n return SIDE_PANEL_DEFAULT_WIDTH;\n}\n\nexport const useBuildSidePanel = (collectionRegistryController: CollectionRegistryController,\n urlController: UrlController,\n navigationStateController: NavigationStateController,\n sideDialogsController: SideDialogsController,\n authController: AuthController\n): SidePanelController => {\n\n const location = useLocation();\n const initialised = useRef<boolean>(false);\n const currentPanelKeysRef = useRef<string[]>([]);\n const customizationController = useCustomizationController();\n\n const smallLayout = !useLargeLayout();\n\n useEffect(() => {\n\n const newFlag = location.hash === `#${NEW_URL_HASH}`;\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n\n if (!navigationStateController.loading) {\n if ((newFlag || sideFlag) && urlController.isUrlCollectionPath(location.pathname)) {\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], newFlag);\n for (let i = 0; i < panelsFromUrl.length; i++) {\n const props = panelsFromUrl[i];\n if (i === 0)\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n else\n sideDialogsController.open(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController))\n }\n }\n initialised.current = true;\n }\n }, [navigationStateController.loading]);\n\n // sync panels if URL changes with #side\n // Use a ref for currentPanelKeys so this effect only fires on URL changes,\n // not on panel state changes. This prevents a race condition with React Router 7\n // where close() clears panels before the URL updates, causing the effect to\n // re-open the panel from the stale #side hash.\n currentPanelKeysRef.current = sideDialogsController.sidePanels.map(p => p.key);\n useEffect(() => {\n if (initialised.current) {\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n if (sideFlag) {\n const currentKeys = currentPanelKeysRef.current;\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], false);\n // if we have more panels than determined by the url, we ignore the url. We might have references open\n if (panelsFromUrl.length <= currentKeys.length) {\n return;\n }\n const lastPanel = panelsFromUrl[panelsFromUrl.length - 1];\n const panelProps = propsToSidePanel(lastPanel, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController);\n const lastCurrentPanel = currentKeys.length > 0 ? currentKeys[currentKeys.length - 1] : undefined;\n if (!lastCurrentPanel || lastCurrentPanel !== panelProps.key) {\n sideDialogsController.replace(panelProps);\n }\n }\n }\n }, [location.pathname, location.hash]);\n\n // update side panels to match browser size\n // Only update panel widths on layout change — don't recreate components.\n // Recreating components would unmount/remount SidePanelBinding, losing\n // scroll position, unsaved form state, and triggering unnecessary data fetches.\n useEffect(() => {\n const updatedSidePanels = sideDialogsController.sidePanels.map(sidePanelProps => {\n if (sidePanelProps.additional) {\n const entityProps = sidePanelProps.additional as SidePanelBindingProps;\n const newWidth = getEntityViewWidth(entityProps, smallLayout, customizationController);\n if (sidePanelProps.width !== newWidth) {\n return { ...sidePanelProps,\nwidth: newWidth };\n }\n }\n return sidePanelProps;\n });\n sideDialogsController.setSidePanels(updatedSidePanels);\n }, [smallLayout]);\n\n const close = useCallback(() => {\n sideDialogsController.close();\n }, [sideDialogsController]);\n\n // Where no CMS route serves the page, a panel is an overlay and nothing\n // more: it writes no URL (one would lead nowhere) and offers no way to a\n // full-screen route that does not exist.\n const routesMounted = urlController.routesMounted !== false;\n\n const open = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.entityId)) {\n throw Error(\"If you want to copy a entity you need to provide a entityId\");\n }\n\n const defaultSelectedView = resolveDefaultSelectedView(\n props.collection ? props.collection.defaultSelectedView : undefined,\n {\n status: props.copy ? \"copy\" : (hasEntityId(props.entityId) ? \"existing\" : \"new\"),\n entityId: props.entityId\n }\n );\n\n sideDialogsController.open(\n propsToSidePanel({\n ...props,\n selectedTab: props.selectedTab ?? defaultSelectedView\n },\n urlController.buildUrlCollectionPath,\n urlController.resolveDatabasePathsFrom,\n smallLayout,\n customizationController,\n authController\n ));\n\n }, [sideDialogsController, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, authController.user, routesMounted]);\n\n const replace = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.entityId)) {\n throw Error(\"If you want to copy a entity you need to provide a entityId\");\n }\n\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n\n }, [urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, sideDialogsController, smallLayout, authController.user, routesMounted]);\n\n return useMemo(() => ({\n close,\n open,\n replace\n }), [close, open, replace]);\n};\n\nexport function buildSidePanelsFromUrl(path: string, collections: AdminCollection[], newFlag: boolean): SidePanelBindingProps<any>[] {\n\n const navigationViewsForPath: NavigationViewInternal<any>[] = getNavigationEntriesFromPath({\n path,\n collections\n });\n\n let sidePanel: SidePanelBindingProps<any> | undefined = undefined;\n let lastCollectionPath = \"\";\n let lastCollectionId: string | undefined = undefined;\n for (let i = 0; i < navigationViewsForPath.length; i++) {\n const navigationEntry = navigationViewsForPath[i];\n\n if (navigationEntry.type === \"collection\") {\n lastCollectionPath = navigationEntry.slug;\n lastCollectionId = navigationEntry.collection.slug;\n }\n\n const previousEntry = navigationViewsForPath[i - 1];\n if (navigationEntry.type === \"entity\") {\n sidePanel = {\n path: navigationEntry.slug,\n entityId: navigationEntry.entityId,\n copy: false,\n collection: navigationEntry.parentCollection,\n width: navigationEntry.parentCollection?.sideDialogWidth\n };\n } else if (navigationEntry.type === \"custom_view\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.view.key;\n }\n } else if (navigationEntry.type === \"collection\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.collection.slug;\n }\n }\n\n }\n\n // `edit` is not a registered view, so the navigation parser skips it. Pick it\n // up from the raw path so that reloading an edit URL reopens the edit form\n // rather than silently dropping the user back on the detail view.\n if (sidePanel && !sidePanel.selectedTab && removeTrailingSlash(path).endsWith(\"/edit\")) {\n sidePanel.selectedTab = \"edit\";\n }\n\n // When the URL doesn't contain a tab segment but the collection has a\n // defaultSelectedView, resolve it so the panel opens with the correct\n // width and the URL is updated on the next replace() cycle.\n if (sidePanel && !sidePanel.selectedTab && sidePanel.collection) {\n const defaultView = resolveDefaultSelectedView(\n sidePanel.collection.defaultSelectedView,\n {\n status: sidePanel.copy ? \"copy\" : (hasEntityId(sidePanel.entityId) ? \"existing\" : \"new\"),\n entityId: sidePanel.entityId\n }\n );\n if (defaultView) {\n sidePanel.selectedTab = defaultView;\n }\n }\n\n if (newFlag) {\n sidePanel = {\n path: lastCollectionPath,\n copy: false\n }\n }\n\n return sidePanel ? [sidePanel] : [];\n}\n\nconst propsToSidePanel = (props: SidePanelBindingProps,\n buildUrlCollectionPath: (path: string) => string,\n resolveIdsFrom: (pathWithAliases: string) => string,\n smallLayout: boolean,\n customizationController: CustomizationController,\n authController: AuthController\n): SideDialogPanelProps => {\n\n const collectionPath = removeInitialAndTrailingSlashes(props.path);\n\n // The list's state — search, filters, sort, view mode — read from the\n // address bar at the moment the panel opens. Not react-router's\n // `location.search`: the list writes its state with `replaceState`, which\n // the router does not observe, so that value is whatever the view mounted\n // with, and the list reads a panel URL built from it back as its state.\n const locationSearch = typeof window !== \"undefined\" ? window.location.search : \"\";\n\n // When updateUrl is explicitly false, don't generate URL paths — the dialog\n // opens as an overlay without affecting the browser URL / router.\n const shouldUpdateUrl = props.updateUrl !== false;\n\n // `buildUrlCollectionPath` encodes every segment of the data path it is\n // given, the record id among them, so the query and the hash go after it.\n const urlPath = shouldUpdateUrl\n ? (hasEntityId(props.entityId)\n ? `${buildUrlCollectionPath(`${collectionPath}/${props.entityId}${props.selectedTab ? \"/\" + props.selectedTab : \"\"}`)}${locationSearch}#${SIDE_URL_HASH}`\n : `${buildUrlCollectionPath(collectionPath)}${locationSearch}#${NEW_URL_HASH}`)\n : undefined;\n\n const parentUrlPath = shouldUpdateUrl\n ? buildUrlCollectionPath(collectionPath)\n : undefined;\n\n const resolvedPanelProps: SidePanelBindingProps<any> = {\n ...props,\n formProps: props.formProps\n };\n\n const entityViewWidth = getEntityViewWidth(props, smallLayout, customizationController);\n return {\n key: `${props.path}/${props.entityId}`,\n component: <ResolvedSidePanelBinding {...resolvedPanelProps}/>,\n urlPath: urlPath,\n parentUrlPath: parentUrlPath,\n width: entityViewWidth,\n onClose: props.onClose,\n additional: resolvedPanelProps\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,SAAS,8BAA8B,OAA8B;CACjE,MAAM,WAAW,qBAA4C,oBAAoB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G,eAAe,GAAG,MAAM,WAAW,MAAM,cAAc,MAAM,MAAM,cAAc,IAAI,IAAI,eAAe,GAAG,kBACxI,GAAG,uBAAuB,cAAc,IAAI,eAAe,GAAG,iBAClE,KAAA;CAEN,MAAM,gBAAgB,kBAChB,uBAAuB,cAAc,IACrC,KAAA;CAEN,MAAM,qBAAiD;EACnD,GAAG;EACH,WAAW,MAAM;CACrB;CAEA,MAAM,kBAAkB,mBAAmB,OAAO,aAAa,uBAAuB;CACtF,OAAO;EACH,KAAK,GAAG,MAAM,KAAK,GAAG,MAAM;EAC5B,WAAW,oBAAC,0BAAD,EAA0B,GAAI,mBAAoB,CAAA;EACpD;EACM;EACf,OAAO;EACP,SAAS,MAAM;EACf,YAAY;CAChB;AACJ"}
@@ -1,4 +1,5 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { hasEntityId } from "@rebasepro/common";
2
3
  import { useApiBase, useApiConfig, useRlsSimulation } from "@rebasepro/app";
3
4
  import { simulationHeaders } from "@rebasepro/types";
4
5
  //#region src/hooks/useHistory.ts
@@ -27,7 +28,7 @@ function useHistory(params) {
27
28
  const entityKey = `${slug}/${entityId}/${refreshToken ?? 0}/${JSON.stringify(simulated)}`;
28
29
  const currentEntityRef = useRef(void 0);
29
30
  const fetchEntries = useCallback(async (currentOffset, signal) => {
30
- if (!apiConfig?.apiUrl || !entityId || !enabled) return;
31
+ if (!apiConfig?.apiUrl || !hasEntityId(entityId) || !enabled) return;
31
32
  setIsLoading(true);
32
33
  setError(void 0);
33
34
  try {
@@ -78,7 +79,7 @@ function useHistory(params) {
78
79
  setHasMore(true);
79
80
  setOffset(0);
80
81
  }
81
- if (!enabled || !entityId) return;
82
+ if (!enabled || !hasEntityId(entityId)) return;
82
83
  const abortController = new AbortController();
83
84
  fetchEntries(isNewEntity ? 0 : offset, abortController.signal);
84
85
  return () => {
@@ -102,7 +103,7 @@ function useHistory(params) {
102
103
  total
103
104
  ]);
104
105
  const revert = useCallback(async (historyId) => {
105
- if (!apiConfig?.apiUrl || !entityId) throw new Error("Cannot revert: missing API configuration or entity ID");
106
+ if (!apiConfig?.apiUrl || !hasEntityId(entityId)) throw new Error("Cannot revert: missing API configuration or entity ID");
106
107
  const token = await apiConfig.getAuthToken?.();
107
108
  const headers = {
108
109
  "Content-Type": "application/json",