@rebasepro/cms 0.29.0-canary.g0e3a0e7 → 0.29.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.
@@ -630,7 +630,10 @@ function EntityForm({ path, id: entityIdProp, collection, onValuesModified, onId
630
630
  ]);
631
631
  const domScope = domScopeFromId(useId());
632
632
  const formFields = () => {
633
- if (customLayout !== void 0) return /* @__PURE__ */ jsx(Fragment, { children: customLayout });
633
+ if (customLayout !== void 0) return /* @__PURE__ */ jsx("div", {
634
+ className: cls("flex flex-col", compact ? "gap-4" : "gap-6"),
635
+ children: customLayout
636
+ });
634
637
  if (Builder) return /* @__PURE__ */ jsx(Suspense, {
635
638
  fallback: /* @__PURE__ */ jsx(CircularProgressCenter, {}),
636
639
  children: /* @__PURE__ */ jsx(Builder, {
@@ -1 +1 @@
1
- {"version":3,"file":"EntityForm.js","names":[],"sources":["../../src/form/EntityForm.tsx"],"sourcesContent":["\nimport type { FormContext } from \"../types/fields\";\nimport React, { Suspense, useCallback, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport type { Properties, Property } from \"@rebasepro/types\";\nimport type { EntityFormProps } from \"../types/components/EntityFormProps\";\nimport { deepEqual as equal } from \"fast-equals\";\n\nimport { ErrorBoundary, isKeyHandled } from \"@rebasepro/ui\";\nimport { useDebouncedCallback } from \"@rebasepro/ui\";\nimport { getCopyValues, getDefaultValuesFor, hasEntityId } from \"@rebasepro/common\";\nimport { isDisabled, isReadOnly } from \"@rebasepro/app\";\nimport { useAuthController, useCustomizationController, useTranslation } from \"@rebasepro/app\";\n\nimport { getFormFieldKeys, resolveFormLayout } from \"@rebasepro/app\";\nimport type { ResolvedFormField, ResolvedFormLayout } from \"@rebasepro/app\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport { Alert, Button, CircularProgressCenter, cls, defaultBorderMixin, Dialog, DialogActions, DialogContent, DialogTitle, Typography } from \"@rebasepro/ui\";\nimport { Formex, FormexController, useCreateFormex } from \"@rebasepro/forms\";\n\nimport { FormRail, RecordMeta } from \"./components/FormRail\";\nimport { FormSections } from \"./components/FormSections\";\nimport { useRailVisible } from \"./components/useRailVisible\";\nimport { FormFieldsContext, renderFormField } from \"./FormFieldsContext\";\nimport type { FormFieldsContextValue } from \"./FormFieldsContext\";\nimport { domScopeFromId, FormDomScopeContext } from \"./form_dom_ids\";\nimport { propertiesOfFields } from \"./resolve_cell_property\";\nimport { collectionShowing } from \"./collection_showing\";\nimport { flattenKeys } from \"@rebasepro/app\";\nimport { ErrorFocus } from \"./components/ErrorFocus\";\nimport { applyValueTransforms, CustomFieldValidator, getEntitySchema, uniqueValueErrors } from \"./validation\";\nimport { formViewer, resolvePropertiesForValidation, withoutUnwritableDefaults } from \"./resolve_form_properties\";\nimport { EntityFormActions } from \"./EntityFormActions\";\nimport type { EntityFormActionsProps } from \"../types/components/EntityFormActionsProps\";\nimport { LocalChangesMenu } from \"./components/LocalChangesMenu\";\nimport { useUndoableDiscard } from \"./useUndoableDiscard\";\nimport { ownsKeystroke, registerKeyboardScope } from \"./form_keyboard_scope\";\nimport { createFormUploadTracker, FormUploadsContext } from \"./form_uploads\";\nimport { entityOfRow, idOfRow, rowOfEntity } from \"@rebasepro/app\";\n\nimport {\n getChangedProperties,\n overlayEdit,\n serverViolationErrors,\n withoutUnsetNulls,\n zodToFormErrors\n} from \"./form_utils\";\n\ntype CollectionProperty = NonNullable<AdminCollection[\"properties\"][string]>;\n\n/**\n * Headless entity form component.\n *\n * Renders a form for a entity collection without any admin or backend dependencies.\n * All backend concerns (save, caching, analytics, plugin slots) are provided via\n * callback props. For admin-connected usage, use {@link EntityFormBinding} instead.\n *\n * @group Components\n */\nexport function EntityForm<M extends Record<string, unknown>>({\n path,\n id: entityIdProp,\n collection,\n onValuesModified,\n onIdChange,\n onSaved,\n row: rowProp,\n initialDirtyValues,\n onFormContextReady,\n initialStatus,\n className,\n onStatusChange,\n onRowChange,\n openEntityMode = \"full_screen\",\n formex: formexProp,\n disabled: disabledProp,\n Builder,\n parentCollectionSlugs,\n parentEntityIds,\n EntityFormActionsComponent = EntityFormActions,\n showDefaultActions = true,\n navigateBack: navigateBackProp,\n children,\n fields: fieldsProp,\n layout: customLayout,\n compact = false,\n // Headless callback props\n onSubmit: onSubmitProp,\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n onReset: onResetProp,\n uniqueFieldValidator: uniqueFieldValidatorProp,\n lockedPropertyKeys,\n // Slots\n beforeFields,\n afterFields,\n pluginActions: pluginActionsProp,\n // Local changes (managed externally)\n computedInitialValues,\n hasLocalChanges: hasLocalChangesProp,\n localChangesData,\n manualApplyLocalChanges,\n localChangesCacheKey,\n onClearLocalChanges\n}: EntityFormProps<M>) {\n\n const navigateBack = useCallback(() => {\n if (navigateBackProp) {\n navigateBackProp();\n }\n }, [navigateBackProp]);\n\n const authController = useAuthController();\n const [status, setStatus] = useState<EntityStatus>(initialStatus);\n\n // The record the row stands for: the admin's own, where the row came from\n // it — its relations' loaded targets, its dates and its version kept.\n const entityProp = useMemo(() => rowProp\n ? entityOfRow(rowProp, entityIdProp ?? idOfRow(rowProp, collection) ?? \"\", path, collection) as Entity<M>\n : undefined, [rowProp, entityIdProp, path, collection]);\n\n /**\n * The record as this form last saved it. A create turns the form into the\n * editor of the record it made, and the `row` prop names that record\n * only once the caller has caught up — a caller that never does (the form\n * used on its own) left an \"existing\" form with no record: it re-seeded\n * itself with the defaults and refused the next Save.\n */\n const [savedEntity, setSavedEntity] = useState<Entity<M> | undefined>(undefined);\n const entity = entityProp ?? (status === \"existing\" ? savedEntity : undefined);\n\n const updateStatus = (status: EntityStatus) => {\n setStatus(status);\n onStatusChange?.(status);\n };\n\n /**\n * The autosave due: what it writes, and the whole form it was taken from\n * — which is what validation judges.\n */\n const [valuesToBeSaved, setValuesToBeSaved] = useState<{ toSave: EntityValues<M>, values: M } | undefined>(undefined);\n useDebouncedCallback(valuesToBeSaved, () => {\n if (!valuesToBeSaved || !onSubmitProp) return;\n const pending = valuesToBeSaved;\n setIsSavingAutoSave(true);\n // An autosave is a save, and is held to what Save is held to. It\n // wrote every edit unchecked; a form that does not validate now shows\n // why, and writes nothing until it does.\n validateForSave(pending.values)\n .then((errors) => {\n if (Object.keys(errors).length > 0) {\n formex.validate();\n return;\n }\n return onSubmitProp(pending.toSave, formex);\n })\n .catch((e) => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked as a Save marks them;\n // an autosave has no submit to make them show, so it counts one.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n if (Object.keys(fieldErrors).length > 0) {\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n formex.setSubmitCount(formex.submitCount + 1);\n }\n })\n .finally(() => setIsSavingAutoSave(false));\n }, false, 2000);\n\n /**\n * The properties the record changed underneath an edit of the user's own,\n * keyed to the value they changed to — each one shown as \"updated\n * elsewhere\" while the form still holds something else. Filled by the\n * effect that follows the baseline, below.\n */\n const [underlyingChanges, setUnderlyingChanges] = useState<Record<string, unknown>>({});\n\n /**\n * Rules the stored record already broke, on fields this edit leaves alone —\n * shown, and not held against the save. Keyed like `formex.errors`.\n */\n const [predatingViolations, setPredatingViolations] = useState<Record<string, unknown>>({});\n\n const initialEntityId: string | number | undefined = useMemo(() => {\n if (status === \"new\" || status === \"copy\") {\n return undefined;\n } else {\n return entityIdProp;\n }\n }, [entityIdProp, status]);\n\n const [entityId, setEntityId] = useState<string | number | undefined>(initialEntityId);\n const [savingError, setSavingError] = useState<Error | undefined>();\n const [isSavingAutoSave, setIsSavingAutoSave] = useState<boolean>(false);\n const [discardDialogOpen, setDiscardDialogOpen] = useState<boolean>(false);\n\n const discard = useUndoableDiscard();\n\n const autoSave = collection.formAutoSave;\n\n // Use externally computed initial values if provided, otherwise compute from entity + collection\n const baseInitialValues = useMemo(() => {\n if (computedInitialValues !== undefined) {\n return computedInitialValues;\n }\n // Fallback: compute from entity/collection (requires authController from context)\n // In headless mode without computedInitialValues, use entity values or defaults\n if (status === \"copy\" && entity) {\n return getCopyValues(collection, entity.values ?? getDefaultValuesFor(collection.properties));\n }\n if (status === \"existing\" && entity) {\n return entity.values ?? getDefaultValuesFor(collection.properties);\n }\n return getDefaultValuesFor(collection.properties);\n }, [computedInitialValues, collection, status, entity]);\n\n const [localChangesCleared, setLocalChangesCleared] = useState<boolean>(false);\n\n const hasLocalChanges = hasLocalChangesProp !== undefined\n ? (hasLocalChangesProp && !localChangesCleared)\n : false;\n\n const onSubmit = (values: EntityValues<M>, formexController: FormexController<EntityValues<M>>) => {\n\n setSavingError(undefined);\n\n if (status === \"existing\") {\n if (!entity?.id) throw Error(\"Form misconfiguration when saving, no id for existing entity\");\n } else if (status !== \"new\" && status !== \"copy\") {\n throw Error(\"New FormType added, check EntityForm\");\n }\n\n if (!onSubmitProp) {\n console.warn(\"EntityForm: no onSubmit callback provided. Form submission has no effect.\");\n formexController.setSubmitting(false);\n return;\n }\n\n return Promise.resolve(save(values))\n ?.then((savedEntity) => {\n if (savedEntity) {\n formexController.resetForm({\n values: savedEntity.values || values,\n submitCount: 0,\n touched: {}\n });\n }\n })\n .finally(() => {\n formexController.setSubmitting(false);\n });\n };\n\n /**\n * What the form opens showing, when that is not what is stored — an edit\n * carried over from the side panel's \"open full screen\", or a draft\n * restored from the local-changes backup.\n *\n * The merge is deliberately *not* folded into the baseline. `mergeDeep`\n * used to produce a single `initialValues` that served as both, with a\n * `initialDirty: true` bolted on beside it to say what the baseline could\n * no longer show — and that flag survived exactly one render, because the\n * record's data arriving replaced the baseline and the form recomputed\n * dirty as false against a baseline that already contained the edit.\n *\n * Read once, at mount: this is a handoff, and re-reading it every render\n * tied the form to a cache that is cleared as soon as it has been consumed.\n */\n const initialModifiedValues = useRef(\n initialDirtyValues && Object.keys(initialDirtyValues).length > 0\n ? overlayEdit(baseInitialValues as Partial<M>, initialDirtyValues as Partial<M>)\n : undefined\n ).current;\n\n /**\n * Every key of the handed-over edit, marked touched. Read once, at mount,\n * like the edit itself: it was rebuilt on every render — a key-value map\n * of 1,000 entries cost ~60 ms per keystroke — by a spread that copied the\n * map once per key.\n */\n const [initialTouched] = useState<Record<string, boolean>>(() => {\n const touched: Record<string, boolean> = {};\n if (initialDirtyValues) {\n for (const key of flattenKeys(initialDirtyValues)) touched[key] = true;\n }\n return touched;\n });\n\n // A Save waits for a file still uploading: its path reaches the values\n // only when the upload ends. See `form_uploads.ts`.\n const [uploadTracker] = useState(createFormUploadTracker);\n\n const internalFormex = useCreateFormex<M>({\n initialValues: baseInitialValues as M,\n beforeSubmit: uploadTracker.wait,\n initialModifiedValues: initialModifiedValues as M | undefined,\n debugId: `EntityForm:${path}/${entityIdProp}`,\n initialTouched,\n onSubmit,\n onReset: () => {\n setUnderlyingChanges({});\n onResetProp?.();\n // The stored values — a reset returns the form to them, and by now\n // that is the baseline whether or not it was at mount.\n onValuesModified?.(false, baseInitialValues as M);\n },\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n validation: (values) => validateForSave(values)\n });\n const formex: FormexController<M> = formexProp ?? internalFormex;\n\n /**\n * The errors that stop a save of `values`. Formex runs it on submit, and\n * the autosave runs it before each write.\n */\n async function validateForSave(values: M): Promise<Record<string, string>> {\n const errors = { ...await validationErrorsFor(values), ...unshownRequiredErrors() };\n if (status !== \"existing\" || !entity?.values || Object.keys(errors).length === 0) {\n setPredatingViolations({});\n return errors;\n }\n // A record stored before a rule existed still breaks it, and the\n // server — which judges only what is sent — would take an\n // unrelated edit. So a field the user did not change, that the\n // stored record already broke, is a warning and not a refusal. A\n // field they changed must be valid, and so must one their edit\n // made invalid: a rule that reads the edited value is the edit's.\n const edited = getChangedProperties<M>(values, entity.values as Partial<M>);\n const storedErrors = await validationErrorsFor(entity.values as M);\n const blocking: Record<string, string> = {};\n const predating: Record<string, string> = {};\n for (const [key, error] of Object.entries(errors)) {\n if (!(key in edited) && key in storedErrors) predating[key] = error;\n else blocking[key] = error;\n }\n setPredatingViolations(predating);\n return blocking;\n }\n\n // One form takes a shortcut: the one the focus is in, else the one\n // mounted last (the top panel). Registered once per mount, so the order\n // is the order the forms opened in. See `form_keyboard_scope.ts`.\n const keyboardScope = useRef<ReturnType<typeof registerKeyboardScope> | undefined>(undefined);\n useEffect(() => {\n const scope = registerKeyboardScope(() => formElementRef.current);\n keyboardScope.current = scope;\n return () => {\n scope.unregister();\n keyboardScope.current = undefined;\n };\n }, []);\n\n useEffect(() => {\n\n const handleKeyDown = (e: KeyboardEvent) => {\n // A layer above the form (a dialog, a menu) already acted on it.\n if (isKeyHandled(e)) return;\n if (!keyboardScope.current || !ownsKeystroke(keyboardScope.current, e)) return;\n const isUndo = (e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"z\";\n const isRedo =\n ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === \"z\") ||\n ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"y\");\n const isSave = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"s\";\n\n if (isSave && !disabled && formex.dirty) {\n e.preventDefault();\n formex.handleSubmit();\n } else if (isUndo && formex.canUndo) {\n e.preventDefault();\n formex.undo();\n } else if (isRedo && formex.canRedo) {\n e.preventDefault();\n formex.redo();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown);\n return () => window.removeEventListener(\"keydown\", handleKeyDown);\n\n }, [formex]);\n\n const afterSave = (updatedEntity: Entity<M>) => {\n setSavedEntity(updatedEntity);\n onResetProp?.();\n onValuesModified?.(false, updatedEntity.values);\n onRowChange?.({ row: rowOfEntity(updatedEntity, collection), id: String(updatedEntity.id) });\n updateStatus(\"existing\");\n setEntityId(updatedEntity.id);\n\n if (onSaved) {\n onSaved({\n row: rowOfEntity(updatedEntity, collection),\n id: String(updatedEntity.id),\n status,\n path,\n collection\n });\n }\n };\n\n // What the form opened with counts as saved: a New form nobody touched\n // has nothing to autosave. Seeded with `entity?.values`, which a new\n // record does not have, the first autosave wrote a record of defaults.\n const lastSavedValues = useRef<EntityValues<M> | undefined>(baseInitialValues as EntityValues<M>);\n const save = async (values: EntityValues<M>): Promise<Entity<M> | void> => {\n // The string transforms a property declares change what is written;\n // validation has already judged the transformed value.\n const writtenValues = applyValueTransforms(values, collection.properties);\n // An existing record sends only what changed; a new one or a copy\n // sends what it holds, less what the user could not have written.\n const valuesToSave = status === \"existing\"\n ? getChangedProperties<M>(writtenValues, entity?.values || {}) as EntityValues<M>\n : withoutUnwritableDefaults<M>(\n status === \"new\"\n ? withoutUnsetNulls(writtenValues, baseInitialValues as Partial<M>)\n : writtenValues,\n baseInitialValues as Partial<M>,\n collection.properties,\n formViewer(authController)\n ) as EntityValues<M>;\n\n if (status === \"existing\" && Object.keys(valuesToSave).length === 0 && entity) {\n return Promise.resolve(entity);\n }\n\n lastSavedValues.current = values;\n\n if (!onSubmitProp) {\n return;\n }\n\n const autoSaveEnabled = autoSave ?? false;\n\n if (autoSaveEnabled) {\n setValuesToBeSaved({ toSave: valuesToSave, values: values as M });\n return Promise.resolve();\n }\n\n return Promise.resolve(onSubmitProp(valuesToSave as M, formex))\n .then((result) => {\n if (!result) return;\n const saved = entityOfRow(result.row, result.id, path, collection) as Entity<M>;\n afterSave(saved);\n return saved;\n })\n .catch(e => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked where the user can\n // see them — not only the sentence in the footer.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n });\n };\n\n const disabled = formex.isSubmitting || Boolean(disabledProp);\n // The record as app code is handed it: the form's context, a Builder.\n const row = entity ? rowOfEntity(entity, collection) : undefined;\n\n const formContext: FormContext<M> = {\n setFieldValue: useCallback((key: string, value: unknown) => formex.setFieldValue(key, value), []),\n values: formex.values,\n collection,\n id: entityId,\n path,\n save,\n submit: formex.handleSubmit,\n formex,\n row,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving: formex.isSubmitting || isSavingAutoSave\n };\n\n /**\n * The context the fields get. Not `formContext`: that one is a new object\n * per render, and a field memoised on its own value would re-render for it\n * on every keystroke anywhere in the form.\n *\n * This one changes identity only with what a field may draw from it — the\n * record, its status, the form's `version` (a reset or re-seed) — and reads\n * `values`, `formex` and `save` through a ref, so a field that did not\n * re-render still sees the current ones from its callbacks (a storage path\n * builder, a markdown file name). A field that reads another field's value\n * *while rendering* has to re-render with it; `PropertyFieldBinding` keeps\n * those — custom `Field`s, `dynamicProps`, `conditions` — on that path.\n */\n const latestRef = useRef({ formex, save });\n latestRef.current = { formex, save };\n const isSaving = formex.isSubmitting || isSavingAutoSave;\n const fieldContext: FormContext<M> = useMemo(() => ({\n get values() {\n return latestRef.current.formex.values;\n },\n get formex() {\n return latestRef.current.formex;\n },\n setFieldValue: formContext.setFieldValue,\n save: (values: M) => latestRef.current.save(values),\n submit: () => latestRef.current.formex.handleSubmit(),\n collection,\n id: entityId,\n path,\n row,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving\n // `formex.version` is a key, not an input: a reset or re-seed has to\n // hand the fields a new context even though nothing above reads it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [formContext.setFieldValue, collection, entityId, path, row, savingError, status, openEntityMode, disabled, isSaving, formex.version]);\n\n useEffect(() => {\n onFormContextReady?.(formContext);\n // `formex.version` only moves on `resetForm`, so these deps used to hand\n // the container one snapshot at mount and never another. That was\n // invisible while Save lived inside the form and read `formex` directly;\n // once the identity bar owned Save, its `dirty` was frozen false and the\n // button never enabled — for any field, not just the one that exposed\n // it. Custom entity views read `formContext.values` through the same\n // channel and were reading a stale copy too.\n //\n // Deps are the state *transitions* a container cares about, not\n // `formex.values`: re-publishing on every keystroke would re-render the\n // whole entity view per character.\n }, [\n formex.version, collection, entityId, path,\n formex.dirty, formex.isSubmitting, formex.submitCount, isSavingAutoSave\n ]);\n\n const actionsDisabled = disabled || formex.isSubmitting || (status === \"existing\" && !formex.dirty) || Boolean(disabledProp);\n\n // The record's title is resolved by the container that renders the identity\n // bar (see `useEntityDisplayTitle`), not here — the form no longer draws a\n // heading of its own.\n\n const modified = formex.dirty;\n\n useEffect(() => {\n if (!autoSave) {\n onValuesModified?.(modified, formex.values);\n }\n }, [formex.dirty]);\n\n // Default no-op unique field validator — always passes\n const defaultUniqueFieldValidator: CustomFieldValidator = useCallback(async () => true, []);\n\n const uniqueFieldValidator: CustomFieldValidator = useMemo(() => {\n if (uniqueFieldValidatorProp) {\n return uniqueFieldValidatorProp as CustomFieldValidator;\n }\n return defaultUniqueFieldValidator;\n }, [uniqueFieldValidatorProp, defaultUniqueFieldValidator]);\n\n const customizationController = useCustomizationController();\n const { t } = useTranslation();\n\n async function validationErrorsFor(values: M): Promise<Record<string, string>> {\n const properties = validationPropertiesFor(values);\n const result = await getEntitySchema(entityId, properties, uniqueFieldValidator).safeParseAsync(values);\n const errors: Record<string, string> = result.success ? {} : zodToFormErrors(result.error);\n // `validation.unique` asks the data source, so it runs here — on\n // submit — and only for values this edit changed that are otherwise\n // valid. It was built and threaded through, and never called.\n const notUnique = await uniqueValueErrors({\n properties,\n values,\n storedValues: status === \"existing\" ? entity?.values : undefined,\n entityId,\n errors,\n validator: uniqueFieldValidator\n });\n return { ...errors, ...notUnique };\n }\n\n /**\n * What the save is judged against: the properties as the form shows them\n * for these values — `dynamicProps` and `conditions` applied — and only\n * the ones the user can change. Built per call because both depend on the\n * values being judged.\n */\n function validationPropertiesFor(values: M) {\n const properties = resolvePropertiesForValidation<M>({\n properties: collection.properties,\n isNew: status === \"new\" || status === \"copy\",\n values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n authController\n });\n // A form that shows some of the fields judges those: an error on one\n // it does not show would block the save with nothing to fix. A\n // layout's fields come and go (a tab), so it also judges every field\n // this edit changed or touched, mounted now or not: what it saves.\n const shown = shownFieldKeys();\n if (!shown) return properties;\n return propertiesOfFields(properties, customLayout !== undefined ? [...shown, ...editedFieldKeys(values)] : shown);\n }\n\n /** The top-level fields this edit changed from the baseline, or touched. */\n function editedFieldKeys(values: M): string[] {\n const baseline: Record<string, unknown> = baseInitialValues ?? {};\n const current: Record<string, unknown> = values;\n const changed = Object.keys(current).filter(key => !equal(current[key], baseline[key]));\n const touched = Object.entries(formex.touched)\n .filter(([, isTouched]) => isTouched)\n .map(([key]) => key.split(\"[\")[0]);\n return [...changed, ...touched];\n }\n\n useOnAutoSave(autoSave, formex, lastSavedValues, save);\n\n /**\n * The record changed while the form was open: someone else saved it, and\n * the listener delivered the new version as a new baseline.\n *\n * An unmodified form follows it whole — formex does that. A modified one\n * keeps the edit, and formex keeps *everything* it holds: a property the\n * user never changed would still show the old value, differ from the new\n * stored one, and be written back by the next save, reverting the other\n * change without a word.\n *\n * So each top-level property that changed underneath is judged on its own,\n * against the baseline the form last followed. One the user has not changed\n * follows the record. One the user has changed keeps the edit — that is\n * what a save writes — and is marked as updated elsewhere, so the overwrite\n * is not a surprise.\n */\n const followedBaseline = useRef(baseInitialValues);\n useEffect(() => {\n const previous: Record<string, unknown> = followedBaseline.current ?? {};\n const next: Record<string, unknown> = baseInitialValues ?? {};\n followedBaseline.current = baseInitialValues;\n if (previous === next) return;\n\n const current: Record<string, unknown> = formex.values;\n if (equal(previous, current)) return;\n\n const conflicts: Record<string, unknown> = {};\n const changedUnderneath = new Set([...Object.keys(previous), ...Object.keys(next)]);\n for (const key of changedUnderneath) {\n if (equal(previous[key], next[key])) {\n changedUnderneath.delete(key);\n } else if (equal(current[key], previous[key])) {\n formex.setFieldValue(key, next[key]);\n } else if (!equal(current[key], next[key])) {\n conflicts[key] = next[key];\n }\n }\n if (changedUnderneath.size === 0) return;\n\n setUnderlyingChanges(prev => {\n const updated = { ...prev };\n changedUnderneath.forEach(key => {\n if (key in conflicts) updated[key] = conflicts[key];\n else delete updated[key];\n });\n return updated;\n });\n }, [baseInitialValues]);\n\n const shownCollection = useMemo(\n () => fieldsProp ? collectionShowing(collection, fieldsProp) : collection,\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `fields` is an inline array at most call sites: its contents, not its identity\n [collection, fieldsProp?.join(\",\")]);\n const formFieldKeys = getFormFieldKeys(shownCollection);\n\n const layout = useMemo(() => resolveFormLayout({\n collection: shownCollection,\n fieldKeys: formFieldKeys,\n status\n }), [shownCollection, formFieldKeys.join(\",\"), status]);\n\n const formElementRef = useRef<HTMLFormElement>(null);\n // Measured, not a breakpoint: the rail holds fields the resolver moved\n // out of the column, so when it cannot be shown they have to come back.\n const railVisible = useRailVisible(formElementRef);\n const generatedFields = !Builder && customLayout === undefined;\n const showRail = generatedFields && layout.hasRail && railVisible && !compact;\n\n // Collapsed sections are per-section-key so a renamed title keeps its state,\n // and initial state comes from the config rather than being forced open.\n const [collapsedSections, setCollapsedSections] = useState<Set<string>>(\n () => new Set(layout.sections.filter(s => s.collapsed).map(s => s.key))\n );\n const toggleSection = useCallback((key: string) => {\n setCollapsedSections(prev => {\n const next = new Set(prev);\n if (next.has(key)) next.delete(key); else next.add(key);\n return next;\n });\n }, []);\n\n const errorKeys = useMemo(\n () => new Set(formex.submitCount > 0 ? Object.keys(formex.errors) : []),\n [formex.errors, formex.submitCount]\n );\n\n // Autofocus lands on the first field the user can actually type into. Tracked\n // across the whole layout rather than per section, so a collapsed leading\n // group does not steal it.\n const autoFocusKey = useMemo(() => {\n if (status !== \"new\" && status !== \"copy\") return undefined;\n if (!generatedFields) return undefined;\n const ordered = [...layout.sections.flatMap(s => s.fields), ...layout.sidebar];\n return ordered.find(field => {\n const property = collection.properties?.[field.key];\n return property ? !isFieldDisabled(field.key, property) : false;\n })?.key;\n }, [layout, collection, status, disabledProp, lockedPropertyKeys, generatedFields]);\n\n /**\n * Every rule that disables a field but a save in progress, which a field\n * reads from the form itself (see `FormFieldsContext`).\n */\n function isFieldDisabled(key: string, property: NonNullable<typeof collection.properties[string]>): boolean {\n const isNew = status === \"new\" || status === \"copy\";\n const isStringOrNumber = property.type === \"string\" || property.type === \"number\";\n const isIdAndAuto = isStringOrNumber && \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n return Boolean(\n disabledProp\n || isReadOnly(property)\n || isDisabled(property)\n || (!isNew && \"isId\" in property && Boolean(property.isId))\n || (isNew && isIdAndAuto)\n || (isNew && lockedPropertyKeys?.includes(key))\n );\n }\n\n // The fields a `<FormField>` has drawn, counted: one key can be drawn\n // twice. Read at validation time from the ref; the version re-renders the\n // form when a field comes or goes, for the create-time check below.\n const registeredFields = useRef(new Map<string, number>());\n const [registeredVersion, setRegisteredVersion] = useState(0);\n const registerField = useCallback((key: string) => {\n const registered = registeredFields.current;\n registered.set(key, (registered.get(key) ?? 0) + 1);\n setRegisteredVersion(v => v + 1);\n return () => {\n const count = (registered.get(key) ?? 1) - 1;\n if (count > 0) registered.set(key, count); else registered.delete(key);\n setRegisteredVersion(v => v + 1);\n };\n }, []);\n\n /**\n * The fields this form shows, when it shows some and not all: the ones a\n * `layout`'s `<FormField>`s draw, or the ones `fields` names. Undefined\n * for the generated form of every field, which judges them all.\n */\n function shownFieldKeys(): string[] | undefined {\n if (customLayout !== undefined) return [...registeredFields.current.keys()];\n if (fieldsProp) return layoutFieldKeys(layout);\n return undefined;\n }\n\n /**\n * What a new record needs that this form will not ask for: a required\n * field it does not show, opening empty — no default, no value handed in,\n * not filled by the server or the database (the validation properties\n * already relax those on create). Such a form can only fail to save, so\n * it says so when it opens.\n */\n const openingValues = (initialModifiedValues ?? baseInitialValues) as Partial<M>;\n const unshownRequired: { key: string, label: string }[] = useMemo(() => {\n if (status !== \"new\" && status !== \"copy\") return [];\n const shown = shownFieldKeys();\n if (!shown) return [];\n const shownSet = new Set(shown);\n const judged = resolvePropertiesForValidation<M>({\n properties: collection.properties,\n isNew: true,\n values: openingValues,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n authController\n });\n return Object.entries(judged)\n .filter(([key, property]) => property.validation?.required\n && !shownSet.has(key)\n && !isGeneratedId(property)\n && isEmptyValue(openingValues[key]))\n .map(([key, property]) => ({ key, label: property.name ?? key }));\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `shownFieldKeys` reads the registered fields, which `registeredVersion` counts\n }, [status, customLayout === undefined, layout, registeredVersion, collection, openingValues, path, entityId, customizationController.propertyConfigs, authController]);\n\n function unshownRequiredErrors(): Record<string, string> {\n if (unshownRequired.length === 0) return {};\n const message = t(\"form_required_fields_not_shown\", { fields: unshownRequired.map(f => f.label).join(\", \") });\n return Object.fromEntries(unshownRequired.map(({ key }) => [key, message]));\n }\n\n /**\n * The field for a key: as the generated layout places it, when it holds\n * the key, else at the property's declared span.\n */\n const fieldFor = useCallback((key: string): ResolvedFormField | undefined => {\n const placed = [...layout.sections.flatMap(s => s.fields), ...layout.sidebar].find(f => f.key === key);\n if (placed) return placed;\n const property = collection.properties?.[key];\n if (property) return { key, span: property.admin?.span ?? 4, additional: false };\n if (collection.additionalFields?.some(f => f.key === key)) return { key, span: 4, additional: true };\n return undefined;\n }, [layout, collection]);\n\n // Read through a ref so the fields' context keeps its identity; its inputs\n // are among the context's dependencies all the same.\n const isFieldDisabledRef = useRef(isFieldDisabled);\n isFieldDisabledRef.current = isFieldDisabled;\n const stableIsFieldDisabled = useCallback(\n (key: string, property: CollectionProperty) => isFieldDisabledRef.current(key, property),\n []);\n\n const fieldsContext: FormFieldsContextValue = useMemo(() => ({\n collection: collection as AdminCollection<Record<string, unknown>>,\n path,\n entityId,\n entity: entity as Entity<Record<string, unknown>> | undefined,\n status,\n fieldContext: fieldContext as FormContext<Record<string, unknown>>,\n previousValues: baseInitialValues as Partial<Record<string, unknown>>,\n underlyingChanges,\n autoSave: Boolean(autoSave),\n autoFocusKey,\n fieldSize: compact ? \"medium\" : \"large\",\n isFieldDisabled: stableIsFieldDisabled,\n renderField: renderFormField,\n fieldFor,\n register: registerField\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `isFieldDisabled` reads `disabledProp` and `lockedPropertyKeys` through its ref\n }), [collection, path, entityId, entity, status, fieldContext, baseInitialValues, underlyingChanges, autoSave, autoFocusKey, compact, stableIsFieldDisabled, fieldFor, registerField, disabledProp, lockedPropertyKeys]);\n\n const domScope = domScopeFromId(useId());\n\n const formFields = () => {\n\n // Your own arrangement of `<FormField>`s, rendered inside the form so\n // they bind to it and an error scrolls to them.\n if (customLayout !== undefined) {\n return <>{customLayout}</>;\n }\n\n if (Builder) {\n // Its own boundary: a Builder is usually a lazy chunk, and without\n // one, loading it suspends the nearest boundary above the record\n // view — which takes the identity bar down with the form.\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Builder\n collection={collection}\n parentCollectionSlugs={parentCollectionSlugs}\n parentEntityIds={parentEntityIds}\n row={row}\n id={entity ? String(entity.id) : undefined}\n modifiedValues={formex.values}\n formContext={formContext}\n />\n </Suspense>;\n }\n\n const sections = showRail || !layout.sidebar.length\n ? layout.sections\n : [\n ...layout.sections,\n // Trailing, not leading. Beside the column these read as\n // peripheral; stacked above it they pushed the record's own name\n // below its status, which is the wrong thing to meet first.\n // Settings come after the content they apply to.\n {\n key: \"__rail\",\n title: \"Settings\",\n collapsible: false,\n collapsed: false,\n fields: layout.sidebar\n }\n ];\n\n return <>\n <FormSections\n sections={sections}\n collapsed={collapsedSections}\n onToggle={toggleSection}\n errorKeys={errorKeys}/>\n\n {/* Folded back with the rail's fields, and for the same reason. The\n rail renders only where it has been measured to fit, so on the\n split pane, the side panel and the dialog this block was dropped\n outright and the record's id was nowhere on screen but the\n truncated chip in the bar. */}\n {!showRail && !compact && layout.showRecordMeta && status === \"existing\" && entity && (\n <div className={cls(\"mt-8 pt-5 border-t max-w-sm\", defaultBorderMixin)}>\n <RecordMeta entity={entity as Entity<Record<string, unknown>>}/>\n </div>\n )}\n </>;\n };\n\n const formRef = useRef<HTMLDivElement>(null);\n\n const hasFormErrors = Object.keys(formex.errors).length > 0 && formex.submitCount > 0;\n\n const predatingViolationLines = useMemo(\n () => errorLines(predatingViolations, collection.properties),\n [predatingViolations, collection.properties]\n );\n\n const formView = <ErrorBoundary>\n <>\n {beforeFields}\n\n {/* The title, the `path/id` chip and the 72px gap under them used to\n live here — 219px above the first field, carrying nothing, and\n scrolling the record's identity away on the first wheel click.\n It is now in the persistent bar, where it stays put. */}\n\n {!entity?.values && initialStatus === \"existing\" &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mb-4 text-xs\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {children}\n\n {hasEntityId(initialEntityId) && !entity && initialStatus !== \"new\" && <Alert color={\"info\"} size={\"small\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {hasFormErrors && <Alert color={\"error\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n {t(\"fix_errors_before_saving\")}\n </Alert>}\n\n {unshownRequired.length > 0 &&\n <Alert color={\"error\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n {t(\"form_required_fields_not_shown\", { fields: unshownRequired.map(f => f.label).join(\", \") })}\n </Alert>}\n\n {predatingViolationLines.length > 0 &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n <Typography variant={\"caption\"} component={\"div\"}>\n {t(\"form_predating_rule_violations\")}\n </Typography>\n <ul className={\"list-disc pl-5 mt-1\"}>\n {predatingViolationLines.map(({ path: errorPath, label, message }) =>\n <li key={errorPath}><Typography variant={\"caption\"}>{`${label}: ${message}`}</Typography></li>)}\n </ul>\n </Alert>}\n\n {formContext && <>\n <div ref={formRef}>\n {formFields()}\n <ErrorFocus containerRef={formRef}/>\n </div>\n </>}\n\n {afterFields}\n\n <Dialog open={discardDialogOpen} onOpenChange={setDiscardDialogOpen} maxWidth={\"sm\"}>\n <DialogTitle>{status === \"existing\" ? \"Discard changes?\" : \"Clear form?\"}</DialogTitle>\n <DialogContent>\n <Typography>\n {status === \"existing\"\n ? \"All unsaved changes will be lost. \"\n : \"All entered values will be cleared. \"}\n You can bring them back with Undo (⌘Z / Ctrl+Z), or from\n the notification, for as long as this form stays open.\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button variant={\"text\"} onClick={() => setDiscardDialogOpen(false)}>\n Cancel\n </Button>\n <Button variant={\"filled\"} color={\"error\"} onClick={() => {\n setDiscardDialogOpen(false);\n discard(formex, status, baseInitialValues);\n }}>\n {status === \"existing\" ? \"Discard\" : \"Clear\"}\n </Button>\n </DialogActions>\n </Dialog>\n </>\n </ErrorBoundary>;\n\n useEffect(() => {\n if (hasEntityId(entityId) && onIdChange)\n onIdChange(entityId);\n }, [entityId, onIdChange]);\n\n if (!collection || !path) {\n throw Error(\"INTERNAL: Collection and path must be defined in form context\");\n }\n\n const EntityFormActionsRender = EntityFormActionsComponent as React.FC<EntityFormActionsProps>;\n\n const dialogActions = <EntityFormActionsRender\n collection={collection}\n path={path}\n entity={entity}\n savingError={savingError}\n formex={formex as FormexController<Record<string, unknown>>}\n disabled={actionsDisabled}\n status={status}\n pluginActions={pluginActionsProp ?? []}\n openEntityMode={openEntityMode}\n showDefaultActions={showDefaultActions}\n navigateBack={navigateBack}\n formContext={formContext as FormContext<Record<string, unknown>>}\n />;\n\n return (\n <Formex value={formex}>\n <FormUploadsContext.Provider value={uploadTracker}>\n <FormDomScopeContext.Provider value={domScope}>\n <FormFieldsContext.Provider value={fieldsContext}>\n <form\n ref={formElementRef}\n data-form-path={path}\n onSubmit={formex.handleSubmit}\n onReset={(e) => {\n e.preventDefault();\n if (formex.dirty) {\n setDiscardDialogOpen(true);\n } else {\n formex.resetForm({ values: baseInitialValues as M });\n }\n }}\n noValidate\n className={cls(\"@container/form flex-1 flex flex-col w-full min-h-0\", className)}>\n\n {/* The actions bar is a sibling of this row rather than absolutely\n positioned over it, so the scroll area ends where the bar\n begins. As an overlay it hid the last field, and the bottom\n padding that compensated was a guess at its height. */}\n <div className={\"flex-1 min-h-0 flex flex-row w-full\"}>\n\n {/* Main column. Its own container scope, so a field's span\n answers to the column it sits in rather than to the window —\n the same form renders at four very different widths. */}\n {/* `items-start`: the column is a flex item, so without it the cross-axis\n default stretches it to the scroller's height. Its content then\n overflows its own box and the bottom padding sits at the bottom of\n the *viewport* instead of after the last field — which is why the\n form appeared to have no padding however large `pb-*` grew. */}\n <div className={\"flex-1 min-w-0 overflow-y-auto flex justify-center items-start\"}>\n <div\n id={domScope}\n className={cls(\n // Two rules widen the column, and they answer to\n // different things on purpose. `@7xl/form` measures\n // the form itself: full screen on a laptop is ~1400px\n // of form, which after the 304px rail leaves room for\n // the wider column with real gutters either side — and\n // it stays 768 in the split pane and the side panel,\n // which never get that wide. `2xl` is the older\n // viewport rule, kept so a panel on a large monitor\n // does not get *narrower* than it is today.\n \"@container/col w-full max-w-3xl @7xl/form:max-w-4xl 2xl:max-w-4xl flex flex-col\",\n compact\n ? \"pt-3 pb-4 px-3\"\n : openEntityMode === \"dialog\"\n ? \"pt-5 pb-8 px-6 sm:px-8\"\n : \"pt-6 pb-12 px-5 sm:px-8\"\n )}>\n\n {manualApplyLocalChanges && hasLocalChanges && localChangesCacheKey &&\n <div className={\"flex justify-end mb-3\"}>\n <LocalChangesMenu<M>\n cacheKey={localChangesCacheKey}\n properties={collection.properties}\n cachedData={localChangesData as Partial<M>}\n formex={formex}\n onClearLocalChanges={() => {\n setLocalChangesCleared(true);\n onClearLocalChanges?.();\n }}\n />\n </div>}\n\n {formView}\n\n </div>\n </div>\n\n {showRail && <FormRail\n fields={layout.sidebar}\n showRecordMeta={layout.showRecordMeta && status === \"existing\"}\n entity={entity as Entity<Record<string, unknown>> | undefined}/>}\n </div>\n\n {dialogActions}\n\n </form>\n </FormFieldsContext.Provider>\n </FormDomScopeContext.Provider>\n </FormUploadsContext.Provider>\n\n </Formex>\n );\n}\n\n/** Every field a resolved layout places, in the column and in the rail. */\nfunction layoutFieldKeys(layout: ResolvedFormLayout): string[] {\n return [...layout.sections.flatMap(section => section.fields), ...layout.sidebar].map(field => field.key);\n}\n\n/** An id the data source or the database generates, which no form asks for. */\nfunction isGeneratedId(property: Property): boolean {\n return \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n}\n\nfunction isEmptyValue(value: unknown): boolean {\n return value === undefined || value === null || value === \"\"\n || (Array.isArray(value) && value.length === 0);\n}\n\nfunction useOnAutoSave<M extends Record<string, unknown>>(autoSave: undefined | boolean, formex: FormexController<M>, lastSavedValues: React.MutableRefObject<EntityValues<M> | undefined>, save: (values: EntityValues<M>) => Promise<Entity<M> | void>) {\n useEffect(() => {\n if (!autoSave) return;\n if (formex.values && !equal(formex.values, lastSavedValues.current)) {\n save(formex.values);\n }\n }, [autoSave, formex.values]);\n}\n\n/**\n * A nested error map — the shape `zodToFormErrors` builds — as one line per\n * failing field, labelled with the property's name.\n */\nfunction errorLines(\n errors: Record<string, unknown>,\n properties: Properties\n): { path: string; label: string; message: string }[] {\n const lines: { path: string; label: string; message: string }[] = [];\n const walk = (value: unknown, path: string[], label: string[], props: Properties | undefined) => {\n if (typeof value === \"string\") {\n lines.push({ path: path.join(\".\"), label: label.join(\" › \"), message: value });\n return;\n }\n if (!value || typeof value !== \"object\") return;\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const property = props?.[key] as Property | undefined;\n const childProps = property?.type === \"map\" ? property.properties as Properties | undefined : undefined;\n walk(child, [...path, key], [...label, property?.name ?? key], childProps);\n }\n };\n walk(errors, [], [], properties);\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,WAA8C,EAC1D,MACA,IAAI,cACJ,YACA,kBACA,YACA,SACA,KAAK,SACL,oBACA,oBACA,eACA,WACA,gBACA,aACA,iBAAiB,eACjB,QAAQ,YACR,UAAU,cACV,SACA,uBACA,iBACA,6BAA6B,mBAC7B,qBAAqB,MACrB,cAAc,kBACd,UACA,QAAQ,YACR,QAAQ,cACR,UAAU,OAEV,UAAU,cACV,wBAAwB,4BACxB,SAAS,aACT,sBAAsB,0BACtB,oBAEA,cACA,aACA,eAAe,mB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M,KAAK,KAAK;IAAG,SAAS;GAAM,CAAC;GAC7E;EACJ;EACA,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU;EACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,GAAG;GACzE,MAAM,WAAW,QAAQ;GACzB,MAAM,aAAa,UAAU,SAAS,QAAQ,SAAS,aAAuC,KAAA;GAC9F,KAAK,OAAO,CAAC,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,OAAO,UAAU,QAAQ,GAAG,GAAG,UAAU;EAC7E;CACJ;CACA,KAAK,QAAQ,CAAC,GAAG,CAAC,GAAG,UAAU;CAC/B,OAAO;AACX"}
1
+ {"version":3,"file":"EntityForm.js","names":[],"sources":["../../src/form/EntityForm.tsx"],"sourcesContent":["\nimport type { FormContext } from \"../types/fields\";\nimport React, { Suspense, useCallback, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport type { Properties, Property } from \"@rebasepro/types\";\nimport type { EntityFormProps } from \"../types/components/EntityFormProps\";\nimport { deepEqual as equal } from \"fast-equals\";\n\nimport { ErrorBoundary, isKeyHandled } from \"@rebasepro/ui\";\nimport { useDebouncedCallback } from \"@rebasepro/ui\";\nimport { getCopyValues, getDefaultValuesFor, hasEntityId } from \"@rebasepro/common\";\nimport { isDisabled, isReadOnly } from \"@rebasepro/app\";\nimport { useAuthController, useCustomizationController, useTranslation } from \"@rebasepro/app\";\n\nimport { getFormFieldKeys, resolveFormLayout } from \"@rebasepro/app\";\nimport type { ResolvedFormField, ResolvedFormLayout } from \"@rebasepro/app\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport { Alert, Button, CircularProgressCenter, cls, defaultBorderMixin, Dialog, DialogActions, DialogContent, DialogTitle, Typography } from \"@rebasepro/ui\";\nimport { Formex, FormexController, useCreateFormex } from \"@rebasepro/forms\";\n\nimport { FormRail, RecordMeta } from \"./components/FormRail\";\nimport { FormSections } from \"./components/FormSections\";\nimport { useRailVisible } from \"./components/useRailVisible\";\nimport { FormFieldsContext, renderFormField } from \"./FormFieldsContext\";\nimport type { FormFieldsContextValue } from \"./FormFieldsContext\";\nimport { domScopeFromId, FormDomScopeContext } from \"./form_dom_ids\";\nimport { propertiesOfFields } from \"./resolve_cell_property\";\nimport { collectionShowing } from \"./collection_showing\";\nimport { flattenKeys } from \"@rebasepro/app\";\nimport { ErrorFocus } from \"./components/ErrorFocus\";\nimport { applyValueTransforms, CustomFieldValidator, getEntitySchema, uniqueValueErrors } from \"./validation\";\nimport { formViewer, resolvePropertiesForValidation, withoutUnwritableDefaults } from \"./resolve_form_properties\";\nimport { EntityFormActions } from \"./EntityFormActions\";\nimport type { EntityFormActionsProps } from \"../types/components/EntityFormActionsProps\";\nimport { LocalChangesMenu } from \"./components/LocalChangesMenu\";\nimport { useUndoableDiscard } from \"./useUndoableDiscard\";\nimport { ownsKeystroke, registerKeyboardScope } from \"./form_keyboard_scope\";\nimport { createFormUploadTracker, FormUploadsContext } from \"./form_uploads\";\nimport { entityOfRow, idOfRow, rowOfEntity } from \"@rebasepro/app\";\n\nimport {\n getChangedProperties,\n overlayEdit,\n serverViolationErrors,\n withoutUnsetNulls,\n zodToFormErrors\n} from \"./form_utils\";\n\ntype CollectionProperty = NonNullable<AdminCollection[\"properties\"][string]>;\n\n/**\n * Headless entity form component.\n *\n * Renders a form for a entity collection without any admin or backend dependencies.\n * All backend concerns (save, caching, analytics, plugin slots) are provided via\n * callback props. For admin-connected usage, use {@link EntityFormBinding} instead.\n *\n * @group Components\n */\nexport function EntityForm<M extends Record<string, unknown>>({\n path,\n id: entityIdProp,\n collection,\n onValuesModified,\n onIdChange,\n onSaved,\n row: rowProp,\n initialDirtyValues,\n onFormContextReady,\n initialStatus,\n className,\n onStatusChange,\n onRowChange,\n openEntityMode = \"full_screen\",\n formex: formexProp,\n disabled: disabledProp,\n Builder,\n parentCollectionSlugs,\n parentEntityIds,\n EntityFormActionsComponent = EntityFormActions,\n showDefaultActions = true,\n navigateBack: navigateBackProp,\n children,\n fields: fieldsProp,\n layout: customLayout,\n compact = false,\n // Headless callback props\n onSubmit: onSubmitProp,\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n onReset: onResetProp,\n uniqueFieldValidator: uniqueFieldValidatorProp,\n lockedPropertyKeys,\n // Slots\n beforeFields,\n afterFields,\n pluginActions: pluginActionsProp,\n // Local changes (managed externally)\n computedInitialValues,\n hasLocalChanges: hasLocalChangesProp,\n localChangesData,\n manualApplyLocalChanges,\n localChangesCacheKey,\n onClearLocalChanges\n}: EntityFormProps<M>) {\n\n const navigateBack = useCallback(() => {\n if (navigateBackProp) {\n navigateBackProp();\n }\n }, [navigateBackProp]);\n\n const authController = useAuthController();\n const [status, setStatus] = useState<EntityStatus>(initialStatus);\n\n // The record the row stands for: the admin's own, where the row came from\n // it — its relations' loaded targets, its dates and its version kept.\n const entityProp = useMemo(() => rowProp\n ? entityOfRow(rowProp, entityIdProp ?? idOfRow(rowProp, collection) ?? \"\", path, collection) as Entity<M>\n : undefined, [rowProp, entityIdProp, path, collection]);\n\n /**\n * The record as this form last saved it. A create turns the form into the\n * editor of the record it made, and the `row` prop names that record\n * only once the caller has caught up — a caller that never does (the form\n * used on its own) left an \"existing\" form with no record: it re-seeded\n * itself with the defaults and refused the next Save.\n */\n const [savedEntity, setSavedEntity] = useState<Entity<M> | undefined>(undefined);\n const entity = entityProp ?? (status === \"existing\" ? savedEntity : undefined);\n\n const updateStatus = (status: EntityStatus) => {\n setStatus(status);\n onStatusChange?.(status);\n };\n\n /**\n * The autosave due: what it writes, and the whole form it was taken from\n * — which is what validation judges.\n */\n const [valuesToBeSaved, setValuesToBeSaved] = useState<{ toSave: EntityValues<M>, values: M } | undefined>(undefined);\n useDebouncedCallback(valuesToBeSaved, () => {\n if (!valuesToBeSaved || !onSubmitProp) return;\n const pending = valuesToBeSaved;\n setIsSavingAutoSave(true);\n // An autosave is a save, and is held to what Save is held to. It\n // wrote every edit unchecked; a form that does not validate now shows\n // why, and writes nothing until it does.\n validateForSave(pending.values)\n .then((errors) => {\n if (Object.keys(errors).length > 0) {\n formex.validate();\n return;\n }\n return onSubmitProp(pending.toSave, formex);\n })\n .catch((e) => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked as a Save marks them;\n // an autosave has no submit to make them show, so it counts one.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n if (Object.keys(fieldErrors).length > 0) {\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n formex.setSubmitCount(formex.submitCount + 1);\n }\n })\n .finally(() => setIsSavingAutoSave(false));\n }, false, 2000);\n\n /**\n * The properties the record changed underneath an edit of the user's own,\n * keyed to the value they changed to — each one shown as \"updated\n * elsewhere\" while the form still holds something else. Filled by the\n * effect that follows the baseline, below.\n */\n const [underlyingChanges, setUnderlyingChanges] = useState<Record<string, unknown>>({});\n\n /**\n * Rules the stored record already broke, on fields this edit leaves alone —\n * shown, and not held against the save. Keyed like `formex.errors`.\n */\n const [predatingViolations, setPredatingViolations] = useState<Record<string, unknown>>({});\n\n const initialEntityId: string | number | undefined = useMemo(() => {\n if (status === \"new\" || status === \"copy\") {\n return undefined;\n } else {\n return entityIdProp;\n }\n }, [entityIdProp, status]);\n\n const [entityId, setEntityId] = useState<string | number | undefined>(initialEntityId);\n const [savingError, setSavingError] = useState<Error | undefined>();\n const [isSavingAutoSave, setIsSavingAutoSave] = useState<boolean>(false);\n const [discardDialogOpen, setDiscardDialogOpen] = useState<boolean>(false);\n\n const discard = useUndoableDiscard();\n\n const autoSave = collection.formAutoSave;\n\n // Use externally computed initial values if provided, otherwise compute from entity + collection\n const baseInitialValues = useMemo(() => {\n if (computedInitialValues !== undefined) {\n return computedInitialValues;\n }\n // Fallback: compute from entity/collection (requires authController from context)\n // In headless mode without computedInitialValues, use entity values or defaults\n if (status === \"copy\" && entity) {\n return getCopyValues(collection, entity.values ?? getDefaultValuesFor(collection.properties));\n }\n if (status === \"existing\" && entity) {\n return entity.values ?? getDefaultValuesFor(collection.properties);\n }\n return getDefaultValuesFor(collection.properties);\n }, [computedInitialValues, collection, status, entity]);\n\n const [localChangesCleared, setLocalChangesCleared] = useState<boolean>(false);\n\n const hasLocalChanges = hasLocalChangesProp !== undefined\n ? (hasLocalChangesProp && !localChangesCleared)\n : false;\n\n const onSubmit = (values: EntityValues<M>, formexController: FormexController<EntityValues<M>>) => {\n\n setSavingError(undefined);\n\n if (status === \"existing\") {\n if (!entity?.id) throw Error(\"Form misconfiguration when saving, no id for existing entity\");\n } else if (status !== \"new\" && status !== \"copy\") {\n throw Error(\"New FormType added, check EntityForm\");\n }\n\n if (!onSubmitProp) {\n console.warn(\"EntityForm: no onSubmit callback provided. Form submission has no effect.\");\n formexController.setSubmitting(false);\n return;\n }\n\n return Promise.resolve(save(values))\n ?.then((savedEntity) => {\n if (savedEntity) {\n formexController.resetForm({\n values: savedEntity.values || values,\n submitCount: 0,\n touched: {}\n });\n }\n })\n .finally(() => {\n formexController.setSubmitting(false);\n });\n };\n\n /**\n * What the form opens showing, when that is not what is stored — an edit\n * carried over from the side panel's \"open full screen\", or a draft\n * restored from the local-changes backup.\n *\n * The merge is deliberately *not* folded into the baseline. `mergeDeep`\n * used to produce a single `initialValues` that served as both, with a\n * `initialDirty: true` bolted on beside it to say what the baseline could\n * no longer show — and that flag survived exactly one render, because the\n * record's data arriving replaced the baseline and the form recomputed\n * dirty as false against a baseline that already contained the edit.\n *\n * Read once, at mount: this is a handoff, and re-reading it every render\n * tied the form to a cache that is cleared as soon as it has been consumed.\n */\n const initialModifiedValues = useRef(\n initialDirtyValues && Object.keys(initialDirtyValues).length > 0\n ? overlayEdit(baseInitialValues as Partial<M>, initialDirtyValues as Partial<M>)\n : undefined\n ).current;\n\n /**\n * Every key of the handed-over edit, marked touched. Read once, at mount,\n * like the edit itself: it was rebuilt on every render — a key-value map\n * of 1,000 entries cost ~60 ms per keystroke — by a spread that copied the\n * map once per key.\n */\n const [initialTouched] = useState<Record<string, boolean>>(() => {\n const touched: Record<string, boolean> = {};\n if (initialDirtyValues) {\n for (const key of flattenKeys(initialDirtyValues)) touched[key] = true;\n }\n return touched;\n });\n\n // A Save waits for a file still uploading: its path reaches the values\n // only when the upload ends. See `form_uploads.ts`.\n const [uploadTracker] = useState(createFormUploadTracker);\n\n const internalFormex = useCreateFormex<M>({\n initialValues: baseInitialValues as M,\n beforeSubmit: uploadTracker.wait,\n initialModifiedValues: initialModifiedValues as M | undefined,\n debugId: `EntityForm:${path}/${entityIdProp}`,\n initialTouched,\n onSubmit,\n onReset: () => {\n setUnderlyingChanges({});\n onResetProp?.();\n // The stored values — a reset returns the form to them, and by now\n // that is the baseline whether or not it was at mount.\n onValuesModified?.(false, baseInitialValues as M);\n },\n onValuesChangeDeferred: onValuesChangeDeferredProp,\n validation: (values) => validateForSave(values)\n });\n const formex: FormexController<M> = formexProp ?? internalFormex;\n\n /**\n * The errors that stop a save of `values`. Formex runs it on submit, and\n * the autosave runs it before each write.\n */\n async function validateForSave(values: M): Promise<Record<string, string>> {\n const errors = { ...await validationErrorsFor(values), ...unshownRequiredErrors() };\n if (status !== \"existing\" || !entity?.values || Object.keys(errors).length === 0) {\n setPredatingViolations({});\n return errors;\n }\n // A record stored before a rule existed still breaks it, and the\n // server — which judges only what is sent — would take an\n // unrelated edit. So a field the user did not change, that the\n // stored record already broke, is a warning and not a refusal. A\n // field they changed must be valid, and so must one their edit\n // made invalid: a rule that reads the edited value is the edit's.\n const edited = getChangedProperties<M>(values, entity.values as Partial<M>);\n const storedErrors = await validationErrorsFor(entity.values as M);\n const blocking: Record<string, string> = {};\n const predating: Record<string, string> = {};\n for (const [key, error] of Object.entries(errors)) {\n if (!(key in edited) && key in storedErrors) predating[key] = error;\n else blocking[key] = error;\n }\n setPredatingViolations(predating);\n return blocking;\n }\n\n // One form takes a shortcut: the one the focus is in, else the one\n // mounted last (the top panel). Registered once per mount, so the order\n // is the order the forms opened in. See `form_keyboard_scope.ts`.\n const keyboardScope = useRef<ReturnType<typeof registerKeyboardScope> | undefined>(undefined);\n useEffect(() => {\n const scope = registerKeyboardScope(() => formElementRef.current);\n keyboardScope.current = scope;\n return () => {\n scope.unregister();\n keyboardScope.current = undefined;\n };\n }, []);\n\n useEffect(() => {\n\n const handleKeyDown = (e: KeyboardEvent) => {\n // A layer above the form (a dialog, a menu) already acted on it.\n if (isKeyHandled(e)) return;\n if (!keyboardScope.current || !ownsKeystroke(keyboardScope.current, e)) return;\n const isUndo = (e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"z\";\n const isRedo =\n ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === \"z\") ||\n ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === \"y\");\n const isSave = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"s\";\n\n if (isSave && !disabled && formex.dirty) {\n e.preventDefault();\n formex.handleSubmit();\n } else if (isUndo && formex.canUndo) {\n e.preventDefault();\n formex.undo();\n } else if (isRedo && formex.canRedo) {\n e.preventDefault();\n formex.redo();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown);\n return () => window.removeEventListener(\"keydown\", handleKeyDown);\n\n }, [formex]);\n\n const afterSave = (updatedEntity: Entity<M>) => {\n setSavedEntity(updatedEntity);\n onResetProp?.();\n onValuesModified?.(false, updatedEntity.values);\n onRowChange?.({ row: rowOfEntity(updatedEntity, collection), id: String(updatedEntity.id) });\n updateStatus(\"existing\");\n setEntityId(updatedEntity.id);\n\n if (onSaved) {\n onSaved({\n row: rowOfEntity(updatedEntity, collection),\n id: String(updatedEntity.id),\n status,\n path,\n collection\n });\n }\n };\n\n // What the form opened with counts as saved: a New form nobody touched\n // has nothing to autosave. Seeded with `entity?.values`, which a new\n // record does not have, the first autosave wrote a record of defaults.\n const lastSavedValues = useRef<EntityValues<M> | undefined>(baseInitialValues as EntityValues<M>);\n const save = async (values: EntityValues<M>): Promise<Entity<M> | void> => {\n // The string transforms a property declares change what is written;\n // validation has already judged the transformed value.\n const writtenValues = applyValueTransforms(values, collection.properties);\n // An existing record sends only what changed; a new one or a copy\n // sends what it holds, less what the user could not have written.\n const valuesToSave = status === \"existing\"\n ? getChangedProperties<M>(writtenValues, entity?.values || {}) as EntityValues<M>\n : withoutUnwritableDefaults<M>(\n status === \"new\"\n ? withoutUnsetNulls(writtenValues, baseInitialValues as Partial<M>)\n : writtenValues,\n baseInitialValues as Partial<M>,\n collection.properties,\n formViewer(authController)\n ) as EntityValues<M>;\n\n if (status === \"existing\" && Object.keys(valuesToSave).length === 0 && entity) {\n return Promise.resolve(entity);\n }\n\n lastSavedValues.current = values;\n\n if (!onSubmitProp) {\n return;\n }\n\n const autoSaveEnabled = autoSave ?? false;\n\n if (autoSaveEnabled) {\n setValuesToBeSaved({ toSave: valuesToSave, values: values as M });\n return Promise.resolve();\n }\n\n return Promise.resolve(onSubmitProp(valuesToSave as M, formex))\n .then((result) => {\n if (!result) return;\n const saved = entityOfRow(result.row, result.id, path, collection) as Entity<M>;\n afterSave(saved);\n return saved;\n })\n .catch(e => {\n console.error(e);\n setSavingError(e);\n // The fields the server refused, marked where the user can\n // see them — not only the sentence in the footer.\n const fieldErrors = serverViolationErrors(e, Object.keys(collection.properties ?? {}));\n for (const [key, message] of Object.entries(fieldErrors)) formex.setFieldError(key, message);\n });\n };\n\n const disabled = formex.isSubmitting || Boolean(disabledProp);\n // The record as app code is handed it: the form's context, a Builder.\n const row = entity ? rowOfEntity(entity, collection) : undefined;\n\n const formContext: FormContext<M> = {\n setFieldValue: useCallback((key: string, value: unknown) => formex.setFieldValue(key, value), []),\n values: formex.values,\n collection,\n id: entityId,\n path,\n save,\n submit: formex.handleSubmit,\n formex,\n row,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving: formex.isSubmitting || isSavingAutoSave\n };\n\n /**\n * The context the fields get. Not `formContext`: that one is a new object\n * per render, and a field memoised on its own value would re-render for it\n * on every keystroke anywhere in the form.\n *\n * This one changes identity only with what a field may draw from it — the\n * record, its status, the form's `version` (a reset or re-seed) — and reads\n * `values`, `formex` and `save` through a ref, so a field that did not\n * re-render still sees the current ones from its callbacks (a storage path\n * builder, a markdown file name). A field that reads another field's value\n * *while rendering* has to re-render with it; `PropertyFieldBinding` keeps\n * those — custom `Field`s, `dynamicProps`, `conditions` — on that path.\n */\n const latestRef = useRef({ formex, save });\n latestRef.current = { formex, save };\n const isSaving = formex.isSubmitting || isSavingAutoSave;\n const fieldContext: FormContext<M> = useMemo(() => ({\n get values() {\n return latestRef.current.formex.values;\n },\n get formex() {\n return latestRef.current.formex;\n },\n setFieldValue: formContext.setFieldValue,\n save: (values: M) => latestRef.current.save(values),\n submit: () => latestRef.current.formex.handleSubmit(),\n collection,\n id: entityId,\n path,\n row,\n savingError,\n status,\n openEntityMode,\n disabled,\n isSaving\n // `formex.version` is a key, not an input: a reset or re-seed has to\n // hand the fields a new context even though nothing above reads it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [formContext.setFieldValue, collection, entityId, path, row, savingError, status, openEntityMode, disabled, isSaving, formex.version]);\n\n useEffect(() => {\n onFormContextReady?.(formContext);\n // `formex.version` only moves on `resetForm`, so these deps used to hand\n // the container one snapshot at mount and never another. That was\n // invisible while Save lived inside the form and read `formex` directly;\n // once the identity bar owned Save, its `dirty` was frozen false and the\n // button never enabled — for any field, not just the one that exposed\n // it. Custom entity views read `formContext.values` through the same\n // channel and were reading a stale copy too.\n //\n // Deps are the state *transitions* a container cares about, not\n // `formex.values`: re-publishing on every keystroke would re-render the\n // whole entity view per character.\n }, [\n formex.version, collection, entityId, path,\n formex.dirty, formex.isSubmitting, formex.submitCount, isSavingAutoSave\n ]);\n\n const actionsDisabled = disabled || formex.isSubmitting || (status === \"existing\" && !formex.dirty) || Boolean(disabledProp);\n\n // The record's title is resolved by the container that renders the identity\n // bar (see `useEntityDisplayTitle`), not here — the form no longer draws a\n // heading of its own.\n\n const modified = formex.dirty;\n\n useEffect(() => {\n if (!autoSave) {\n onValuesModified?.(modified, formex.values);\n }\n }, [formex.dirty]);\n\n // Default no-op unique field validator — always passes\n const defaultUniqueFieldValidator: CustomFieldValidator = useCallback(async () => true, []);\n\n const uniqueFieldValidator: CustomFieldValidator = useMemo(() => {\n if (uniqueFieldValidatorProp) {\n return uniqueFieldValidatorProp as CustomFieldValidator;\n }\n return defaultUniqueFieldValidator;\n }, [uniqueFieldValidatorProp, defaultUniqueFieldValidator]);\n\n const customizationController = useCustomizationController();\n const { t } = useTranslation();\n\n async function validationErrorsFor(values: M): Promise<Record<string, string>> {\n const properties = validationPropertiesFor(values);\n const result = await getEntitySchema(entityId, properties, uniqueFieldValidator).safeParseAsync(values);\n const errors: Record<string, string> = result.success ? {} : zodToFormErrors(result.error);\n // `validation.unique` asks the data source, so it runs here — on\n // submit — and only for values this edit changed that are otherwise\n // valid. It was built and threaded through, and never called.\n const notUnique = await uniqueValueErrors({\n properties,\n values,\n storedValues: status === \"existing\" ? entity?.values : undefined,\n entityId,\n errors,\n validator: uniqueFieldValidator\n });\n return { ...errors, ...notUnique };\n }\n\n /**\n * What the save is judged against: the properties as the form shows them\n * for these values — `dynamicProps` and `conditions` applied — and only\n * the ones the user can change. Built per call because both depend on the\n * values being judged.\n */\n function validationPropertiesFor(values: M) {\n const properties = resolvePropertiesForValidation<M>({\n properties: collection.properties,\n isNew: status === \"new\" || status === \"copy\",\n values,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n authController\n });\n // A form that shows some of the fields judges those: an error on one\n // it does not show would block the save with nothing to fix. A\n // layout's fields come and go (a tab), so it also judges every field\n // this edit changed or touched, mounted now or not: what it saves.\n const shown = shownFieldKeys();\n if (!shown) return properties;\n return propertiesOfFields(properties, customLayout !== undefined ? [...shown, ...editedFieldKeys(values)] : shown);\n }\n\n /** The top-level fields this edit changed from the baseline, or touched. */\n function editedFieldKeys(values: M): string[] {\n const baseline: Record<string, unknown> = baseInitialValues ?? {};\n const current: Record<string, unknown> = values;\n const changed = Object.keys(current).filter(key => !equal(current[key], baseline[key]));\n const touched = Object.entries(formex.touched)\n .filter(([, isTouched]) => isTouched)\n .map(([key]) => key.split(\"[\")[0]);\n return [...changed, ...touched];\n }\n\n useOnAutoSave(autoSave, formex, lastSavedValues, save);\n\n /**\n * The record changed while the form was open: someone else saved it, and\n * the listener delivered the new version as a new baseline.\n *\n * An unmodified form follows it whole — formex does that. A modified one\n * keeps the edit, and formex keeps *everything* it holds: a property the\n * user never changed would still show the old value, differ from the new\n * stored one, and be written back by the next save, reverting the other\n * change without a word.\n *\n * So each top-level property that changed underneath is judged on its own,\n * against the baseline the form last followed. One the user has not changed\n * follows the record. One the user has changed keeps the edit — that is\n * what a save writes — and is marked as updated elsewhere, so the overwrite\n * is not a surprise.\n */\n const followedBaseline = useRef(baseInitialValues);\n useEffect(() => {\n const previous: Record<string, unknown> = followedBaseline.current ?? {};\n const next: Record<string, unknown> = baseInitialValues ?? {};\n followedBaseline.current = baseInitialValues;\n if (previous === next) return;\n\n const current: Record<string, unknown> = formex.values;\n if (equal(previous, current)) return;\n\n const conflicts: Record<string, unknown> = {};\n const changedUnderneath = new Set([...Object.keys(previous), ...Object.keys(next)]);\n for (const key of changedUnderneath) {\n if (equal(previous[key], next[key])) {\n changedUnderneath.delete(key);\n } else if (equal(current[key], previous[key])) {\n formex.setFieldValue(key, next[key]);\n } else if (!equal(current[key], next[key])) {\n conflicts[key] = next[key];\n }\n }\n if (changedUnderneath.size === 0) return;\n\n setUnderlyingChanges(prev => {\n const updated = { ...prev };\n changedUnderneath.forEach(key => {\n if (key in conflicts) updated[key] = conflicts[key];\n else delete updated[key];\n });\n return updated;\n });\n }, [baseInitialValues]);\n\n const shownCollection = useMemo(\n () => fieldsProp ? collectionShowing(collection, fieldsProp) : collection,\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `fields` is an inline array at most call sites: its contents, not its identity\n [collection, fieldsProp?.join(\",\")]);\n const formFieldKeys = getFormFieldKeys(shownCollection);\n\n const layout = useMemo(() => resolveFormLayout({\n collection: shownCollection,\n fieldKeys: formFieldKeys,\n status\n }), [shownCollection, formFieldKeys.join(\",\"), status]);\n\n const formElementRef = useRef<HTMLFormElement>(null);\n // Measured, not a breakpoint: the rail holds fields the resolver moved\n // out of the column, so when it cannot be shown they have to come back.\n const railVisible = useRailVisible(formElementRef);\n const generatedFields = !Builder && customLayout === undefined;\n const showRail = generatedFields && layout.hasRail && railVisible && !compact;\n\n // Collapsed sections are per-section-key so a renamed title keeps its state,\n // and initial state comes from the config rather than being forced open.\n const [collapsedSections, setCollapsedSections] = useState<Set<string>>(\n () => new Set(layout.sections.filter(s => s.collapsed).map(s => s.key))\n );\n const toggleSection = useCallback((key: string) => {\n setCollapsedSections(prev => {\n const next = new Set(prev);\n if (next.has(key)) next.delete(key); else next.add(key);\n return next;\n });\n }, []);\n\n const errorKeys = useMemo(\n () => new Set(formex.submitCount > 0 ? Object.keys(formex.errors) : []),\n [formex.errors, formex.submitCount]\n );\n\n // Autofocus lands on the first field the user can actually type into. Tracked\n // across the whole layout rather than per section, so a collapsed leading\n // group does not steal it.\n const autoFocusKey = useMemo(() => {\n if (status !== \"new\" && status !== \"copy\") return undefined;\n if (!generatedFields) return undefined;\n const ordered = [...layout.sections.flatMap(s => s.fields), ...layout.sidebar];\n return ordered.find(field => {\n const property = collection.properties?.[field.key];\n return property ? !isFieldDisabled(field.key, property) : false;\n })?.key;\n }, [layout, collection, status, disabledProp, lockedPropertyKeys, generatedFields]);\n\n /**\n * Every rule that disables a field but a save in progress, which a field\n * reads from the form itself (see `FormFieldsContext`).\n */\n function isFieldDisabled(key: string, property: NonNullable<typeof collection.properties[string]>): boolean {\n const isNew = status === \"new\" || status === \"copy\";\n const isStringOrNumber = property.type === \"string\" || property.type === \"number\";\n const isIdAndAuto = isStringOrNumber && \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n return Boolean(\n disabledProp\n || isReadOnly(property)\n || isDisabled(property)\n || (!isNew && \"isId\" in property && Boolean(property.isId))\n || (isNew && isIdAndAuto)\n || (isNew && lockedPropertyKeys?.includes(key))\n );\n }\n\n // The fields a `<FormField>` has drawn, counted: one key can be drawn\n // twice. Read at validation time from the ref; the version re-renders the\n // form when a field comes or goes, for the create-time check below.\n const registeredFields = useRef(new Map<string, number>());\n const [registeredVersion, setRegisteredVersion] = useState(0);\n const registerField = useCallback((key: string) => {\n const registered = registeredFields.current;\n registered.set(key, (registered.get(key) ?? 0) + 1);\n setRegisteredVersion(v => v + 1);\n return () => {\n const count = (registered.get(key) ?? 1) - 1;\n if (count > 0) registered.set(key, count); else registered.delete(key);\n setRegisteredVersion(v => v + 1);\n };\n }, []);\n\n /**\n * The fields this form shows, when it shows some and not all: the ones a\n * `layout`'s `<FormField>`s draw, or the ones `fields` names. Undefined\n * for the generated form of every field, which judges them all.\n */\n function shownFieldKeys(): string[] | undefined {\n if (customLayout !== undefined) return [...registeredFields.current.keys()];\n if (fieldsProp) return layoutFieldKeys(layout);\n return undefined;\n }\n\n /**\n * What a new record needs that this form will not ask for: a required\n * field it does not show, opening empty — no default, no value handed in,\n * not filled by the server or the database (the validation properties\n * already relax those on create). Such a form can only fail to save, so\n * it says so when it opens.\n */\n const openingValues = (initialModifiedValues ?? baseInitialValues) as Partial<M>;\n const unshownRequired: { key: string, label: string }[] = useMemo(() => {\n if (status !== \"new\" && status !== \"copy\") return [];\n const shown = shownFieldKeys();\n if (!shown) return [];\n const shownSet = new Set(shown);\n const judged = resolvePropertiesForValidation<M>({\n properties: collection.properties,\n isNew: true,\n values: openingValues,\n previousValues: baseInitialValues as Partial<M>,\n path,\n entityId,\n propertyConfigs: customizationController.propertyConfigs,\n authController\n });\n return Object.entries(judged)\n .filter(([key, property]) => property.validation?.required\n && !shownSet.has(key)\n && !isGeneratedId(property)\n && isEmptyValue(openingValues[key]))\n .map(([key, property]) => ({ key, label: property.name ?? key }));\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `shownFieldKeys` reads the registered fields, which `registeredVersion` counts\n }, [status, customLayout === undefined, layout, registeredVersion, collection, openingValues, path, entityId, customizationController.propertyConfigs, authController]);\n\n function unshownRequiredErrors(): Record<string, string> {\n if (unshownRequired.length === 0) return {};\n const message = t(\"form_required_fields_not_shown\", { fields: unshownRequired.map(f => f.label).join(\", \") });\n return Object.fromEntries(unshownRequired.map(({ key }) => [key, message]));\n }\n\n /**\n * The field for a key: as the generated layout places it, when it holds\n * the key, else at the property's declared span.\n */\n const fieldFor = useCallback((key: string): ResolvedFormField | undefined => {\n const placed = [...layout.sections.flatMap(s => s.fields), ...layout.sidebar].find(f => f.key === key);\n if (placed) return placed;\n const property = collection.properties?.[key];\n if (property) return { key, span: property.admin?.span ?? 4, additional: false };\n if (collection.additionalFields?.some(f => f.key === key)) return { key, span: 4, additional: true };\n return undefined;\n }, [layout, collection]);\n\n // Read through a ref so the fields' context keeps its identity; its inputs\n // are among the context's dependencies all the same.\n const isFieldDisabledRef = useRef(isFieldDisabled);\n isFieldDisabledRef.current = isFieldDisabled;\n const stableIsFieldDisabled = useCallback(\n (key: string, property: CollectionProperty) => isFieldDisabledRef.current(key, property),\n []);\n\n const fieldsContext: FormFieldsContextValue = useMemo(() => ({\n collection: collection as AdminCollection<Record<string, unknown>>,\n path,\n entityId,\n entity: entity as Entity<Record<string, unknown>> | undefined,\n status,\n fieldContext: fieldContext as FormContext<Record<string, unknown>>,\n previousValues: baseInitialValues as Partial<Record<string, unknown>>,\n underlyingChanges,\n autoSave: Boolean(autoSave),\n autoFocusKey,\n fieldSize: compact ? \"medium\" : \"large\",\n isFieldDisabled: stableIsFieldDisabled,\n renderField: renderFormField,\n fieldFor,\n register: registerField\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `isFieldDisabled` reads `disabledProp` and `lockedPropertyKeys` through its ref\n }), [collection, path, entityId, entity, status, fieldContext, baseInitialValues, underlyingChanges, autoSave, autoFocusKey, compact, stableIsFieldDisabled, fieldFor, registerField, disabledProp, lockedPropertyKeys]);\n\n const domScope = domScopeFromId(useId());\n\n const formFields = () => {\n\n // Your own arrangement of `<FormField>`s, rendered inside the form so\n // they bind to it and an error scrolls to them.\n if (customLayout !== undefined) {\n // Spaced as the generated fields are, so `<FormField>`s laid out\n // as siblings do not touch; a layout in a container of its own is\n // one child, and keeps its own spacing.\n return <div className={cls(\"flex flex-col\", compact ? \"gap-4\" : \"gap-6\")}>{customLayout}</div>;\n }\n\n if (Builder) {\n // Its own boundary: a Builder is usually a lazy chunk, and without\n // one, loading it suspends the nearest boundary above the record\n // view — which takes the identity bar down with the form.\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Builder\n collection={collection}\n parentCollectionSlugs={parentCollectionSlugs}\n parentEntityIds={parentEntityIds}\n row={row}\n id={entity ? String(entity.id) : undefined}\n modifiedValues={formex.values}\n formContext={formContext}\n />\n </Suspense>;\n }\n\n const sections = showRail || !layout.sidebar.length\n ? layout.sections\n : [\n ...layout.sections,\n // Trailing, not leading. Beside the column these read as\n // peripheral; stacked above it they pushed the record's own name\n // below its status, which is the wrong thing to meet first.\n // Settings come after the content they apply to.\n {\n key: \"__rail\",\n title: \"Settings\",\n collapsible: false,\n collapsed: false,\n fields: layout.sidebar\n }\n ];\n\n return <>\n <FormSections\n sections={sections}\n collapsed={collapsedSections}\n onToggle={toggleSection}\n errorKeys={errorKeys}/>\n\n {/* Folded back with the rail's fields, and for the same reason. The\n rail renders only where it has been measured to fit, so on the\n split pane, the side panel and the dialog this block was dropped\n outright and the record's id was nowhere on screen but the\n truncated chip in the bar. */}\n {!showRail && !compact && layout.showRecordMeta && status === \"existing\" && entity && (\n <div className={cls(\"mt-8 pt-5 border-t max-w-sm\", defaultBorderMixin)}>\n <RecordMeta entity={entity as Entity<Record<string, unknown>>}/>\n </div>\n )}\n </>;\n };\n\n const formRef = useRef<HTMLDivElement>(null);\n\n const hasFormErrors = Object.keys(formex.errors).length > 0 && formex.submitCount > 0;\n\n const predatingViolationLines = useMemo(\n () => errorLines(predatingViolations, collection.properties),\n [predatingViolations, collection.properties]\n );\n\n const formView = <ErrorBoundary>\n <>\n {beforeFields}\n\n {/* The title, the `path/id` chip and the 72px gap under them used to\n live here — 219px above the first field, carrying nothing, and\n scrolling the record's identity away on the first wheel click.\n It is now in the persistent bar, where it stays put. */}\n\n {!entity?.values && initialStatus === \"existing\" &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mb-4 text-xs\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {children}\n\n {hasEntityId(initialEntityId) && !entity && initialStatus !== \"new\" && <Alert color={\"info\"} size={\"small\"}>\n {t(\"entity_does_not_exist\")}\n </Alert>}\n\n {hasFormErrors && <Alert color={\"error\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n {t(\"fix_errors_before_saving\")}\n </Alert>}\n\n {unshownRequired.length > 0 &&\n <Alert color={\"error\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n {t(\"form_required_fields_not_shown\", { fields: unshownRequired.map(f => f.label).join(\", \") })}\n </Alert>}\n\n {predatingViolationLines.length > 0 &&\n <Alert color={\"warning\"} size={\"small\"} outerClassName={\"w-full mt-2\"}>\n <Typography variant={\"caption\"} component={\"div\"}>\n {t(\"form_predating_rule_violations\")}\n </Typography>\n <ul className={\"list-disc pl-5 mt-1\"}>\n {predatingViolationLines.map(({ path: errorPath, label, message }) =>\n <li key={errorPath}><Typography variant={\"caption\"}>{`${label}: ${message}`}</Typography></li>)}\n </ul>\n </Alert>}\n\n {formContext && <>\n <div ref={formRef}>\n {formFields()}\n <ErrorFocus containerRef={formRef}/>\n </div>\n </>}\n\n {afterFields}\n\n <Dialog open={discardDialogOpen} onOpenChange={setDiscardDialogOpen} maxWidth={\"sm\"}>\n <DialogTitle>{status === \"existing\" ? \"Discard changes?\" : \"Clear form?\"}</DialogTitle>\n <DialogContent>\n <Typography>\n {status === \"existing\"\n ? \"All unsaved changes will be lost. \"\n : \"All entered values will be cleared. \"}\n You can bring them back with Undo (⌘Z / Ctrl+Z), or from\n the notification, for as long as this form stays open.\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button variant={\"text\"} onClick={() => setDiscardDialogOpen(false)}>\n Cancel\n </Button>\n <Button variant={\"filled\"} color={\"error\"} onClick={() => {\n setDiscardDialogOpen(false);\n discard(formex, status, baseInitialValues);\n }}>\n {status === \"existing\" ? \"Discard\" : \"Clear\"}\n </Button>\n </DialogActions>\n </Dialog>\n </>\n </ErrorBoundary>;\n\n useEffect(() => {\n if (hasEntityId(entityId) && onIdChange)\n onIdChange(entityId);\n }, [entityId, onIdChange]);\n\n if (!collection || !path) {\n throw Error(\"INTERNAL: Collection and path must be defined in form context\");\n }\n\n const EntityFormActionsRender = EntityFormActionsComponent as React.FC<EntityFormActionsProps>;\n\n const dialogActions = <EntityFormActionsRender\n collection={collection}\n path={path}\n entity={entity}\n savingError={savingError}\n formex={formex as FormexController<Record<string, unknown>>}\n disabled={actionsDisabled}\n status={status}\n pluginActions={pluginActionsProp ?? []}\n openEntityMode={openEntityMode}\n showDefaultActions={showDefaultActions}\n navigateBack={navigateBack}\n formContext={formContext as FormContext<Record<string, unknown>>}\n />;\n\n return (\n <Formex value={formex}>\n <FormUploadsContext.Provider value={uploadTracker}>\n <FormDomScopeContext.Provider value={domScope}>\n <FormFieldsContext.Provider value={fieldsContext}>\n <form\n ref={formElementRef}\n data-form-path={path}\n onSubmit={formex.handleSubmit}\n onReset={(e) => {\n e.preventDefault();\n if (formex.dirty) {\n setDiscardDialogOpen(true);\n } else {\n formex.resetForm({ values: baseInitialValues as M });\n }\n }}\n noValidate\n className={cls(\"@container/form flex-1 flex flex-col w-full min-h-0\", className)}>\n\n {/* The actions bar is a sibling of this row rather than absolutely\n positioned over it, so the scroll area ends where the bar\n begins. As an overlay it hid the last field, and the bottom\n padding that compensated was a guess at its height. */}\n <div className={\"flex-1 min-h-0 flex flex-row w-full\"}>\n\n {/* Main column. Its own container scope, so a field's span\n answers to the column it sits in rather than to the window —\n the same form renders at four very different widths. */}\n {/* `items-start`: the column is a flex item, so without it the cross-axis\n default stretches it to the scroller's height. Its content then\n overflows its own box and the bottom padding sits at the bottom of\n the *viewport* instead of after the last field — which is why the\n form appeared to have no padding however large `pb-*` grew. */}\n <div className={\"flex-1 min-w-0 overflow-y-auto flex justify-center items-start\"}>\n <div\n id={domScope}\n className={cls(\n // Two rules widen the column, and they answer to\n // different things on purpose. `@7xl/form` measures\n // the form itself: full screen on a laptop is ~1400px\n // of form, which after the 304px rail leaves room for\n // the wider column with real gutters either side — and\n // it stays 768 in the split pane and the side panel,\n // which never get that wide. `2xl` is the older\n // viewport rule, kept so a panel on a large monitor\n // does not get *narrower* than it is today.\n \"@container/col w-full max-w-3xl @7xl/form:max-w-4xl 2xl:max-w-4xl flex flex-col\",\n compact\n ? \"pt-3 pb-4 px-3\"\n : openEntityMode === \"dialog\"\n ? \"pt-5 pb-8 px-6 sm:px-8\"\n : \"pt-6 pb-12 px-5 sm:px-8\"\n )}>\n\n {manualApplyLocalChanges && hasLocalChanges && localChangesCacheKey &&\n <div className={\"flex justify-end mb-3\"}>\n <LocalChangesMenu<M>\n cacheKey={localChangesCacheKey}\n properties={collection.properties}\n cachedData={localChangesData as Partial<M>}\n formex={formex}\n onClearLocalChanges={() => {\n setLocalChangesCleared(true);\n onClearLocalChanges?.();\n }}\n />\n </div>}\n\n {formView}\n\n </div>\n </div>\n\n {showRail && <FormRail\n fields={layout.sidebar}\n showRecordMeta={layout.showRecordMeta && status === \"existing\"}\n entity={entity as Entity<Record<string, unknown>> | undefined}/>}\n </div>\n\n {dialogActions}\n\n </form>\n </FormFieldsContext.Provider>\n </FormDomScopeContext.Provider>\n </FormUploadsContext.Provider>\n\n </Formex>\n );\n}\n\n/** Every field a resolved layout places, in the column and in the rail. */\nfunction layoutFieldKeys(layout: ResolvedFormLayout): string[] {\n return [...layout.sections.flatMap(section => section.fields), ...layout.sidebar].map(field => field.key);\n}\n\n/** An id the data source or the database generates, which no form asks for. */\nfunction isGeneratedId(property: Property): boolean {\n return \"isId\" in property && typeof property.isId === \"string\" && property.isId !== \"manual\";\n}\n\nfunction isEmptyValue(value: unknown): boolean {\n return value === undefined || value === null || value === \"\"\n || (Array.isArray(value) && value.length === 0);\n}\n\nfunction useOnAutoSave<M extends Record<string, unknown>>(autoSave: undefined | boolean, formex: FormexController<M>, lastSavedValues: React.MutableRefObject<EntityValues<M> | undefined>, save: (values: EntityValues<M>) => Promise<Entity<M> | void>) {\n useEffect(() => {\n if (!autoSave) return;\n if (formex.values && !equal(formex.values, lastSavedValues.current)) {\n save(formex.values);\n }\n }, [autoSave, formex.values]);\n}\n\n/**\n * A nested error map — the shape `zodToFormErrors` builds — as one line per\n * failing field, labelled with the property's name.\n */\nfunction errorLines(\n errors: Record<string, unknown>,\n properties: Properties\n): { path: string; label: string; message: string }[] {\n const lines: { path: string; label: string; message: string }[] = [];\n const walk = (value: unknown, path: string[], label: string[], props: Properties | undefined) => {\n if (typeof value === \"string\") {\n lines.push({ path: path.join(\".\"), label: label.join(\" › \"), message: value });\n return;\n }\n if (!value || typeof value !== \"object\") return;\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const property = props?.[key] as Property | undefined;\n const childProps = property?.type === \"map\" ? property.properties as Properties | undefined : undefined;\n walk(child, [...path, key], [...label, property?.name ?? key], childProps);\n }\n };\n walk(errors, [], [], properties);\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,WAA8C,EAC1D,MACA,IAAI,cACJ,YACA,kBACA,YACA,SACA,KAAK,SACL,oBACA,oBACA,eACA,WACA,gBACA,aACA,iBAAiB,eACjB,QAAQ,YACR,UAAU,cACV,SACA,uBACA,iBACA,6BAA6B,mBAC7B,qBAAqB,MACrB,cAAc,kBACd,UACA,QAAQ,YACR,QAAQ,cACR,UAAU,OAEV,UAAU,cACV,wBAAwB,4BACxB,SAAS,aACT,sBAAsB,0BACtB,oBAEA,cACA,aAC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KAAK;IAAE,MAAM,KAAK,KAAK,GAAG;IAAG,OAAO,MAAM,KAAK,KAAK;IAAG,SAAS;GAAM,CAAC;GAC7E;EACJ;EACA,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU;EACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,GAAG;GACzE,MAAM,WAAW,QAAQ;GACzB,MAAM,aAAa,UAAU,SAAS,QAAQ,SAAS,aAAuC,KAAA;GAC9F,KAAK,OAAO,CAAC,GAAG,MAAM,GAAG,GAAG,CAAC,GAAG,OAAO,UAAU,QAAQ,GAAG,GAAG,UAAU;EAC7E;CACJ;CACA,KAAK,QAAQ,CAAC,GAAG,CAAC,GAAG,UAAU;CAC/B,OAAO;AACX"}
@@ -3,8 +3,8 @@ import { McpAppBridge } from "./bridge.js";
3
3
  import { type Screen } from "./payload.js";
4
4
  export { APPS_PROTOCOL_VERSION, McpAppBridge, isRecord } from "./bridge.js";
5
5
  export type { HostContext, ToolResult, DisplayMode } from "./bridge.js";
6
- export { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges } from "./tool_driver.js";
7
- export type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange } from "./tool_driver.js";
6
+ export { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite } from "./tool_driver.js";
7
+ export type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange, WriteFailure } from "./tool_driver.js";
8
8
  export { parseResult, actionsOf, filterOf } from "./payload.js";
9
9
  export type { Screen, Block } from "./payload.js";
10
10
  export interface McpViewOptions {
@@ -46,3 +46,9 @@ export declare function startMcpView(options: McpViewOptions): McpAppBridge;
46
46
  * the server's configs are the collections.
47
47
  */
48
48
  export declare function narrowCollections(own: AdminCollection[], sent: readonly AdminCollection[]): AdminCollection[];
49
+ /**
50
+ * A row's title, as the admin names the record: the collection's title
51
+ * property where the row carries a readable value for it. Nothing where it
52
+ * does not — an opaque id says no more than the caller's fallback.
53
+ */
54
+ export declare function rowTitle(collection: AdminCollection | undefined, id: string, row: Record<string, unknown> | undefined): string | undefined;
@@ -1,5 +1,5 @@
1
1
  import { McpAppBridge, isRecord } from "./bridge.js";
2
- import { createToolDriver, describeChanges } from "./tool_driver.js";
2
+ import { createToolDriver, describeChanges, describeFailedWrite } from "./tool_driver.js";
3
3
  import { findCollection, parseResult } from "./payload.js";
4
4
  import { describeAppError } from "./code_app.js";
5
5
  import { createViewStore } from "./store.js";
@@ -8,7 +8,7 @@ import { VIEW_STORAGE_SOURCE } from "./storage_source.js";
8
8
  import "react";
9
9
  import { jsx } from "react/jsx-runtime";
10
10
  import { Alert } from "@rebasepro/ui";
11
- import { setRebaseEmbedHost } from "@rebasepro/app";
11
+ import { getTitlePropertyKeyForValues, looksLikeIdentifierValue, setRebaseEmbedHost } from "@rebasepro/app";
12
12
  import { createRoot } from "react-dom/client";
13
13
  //#region src/mcp_view/index.tsx
14
14
  /**
@@ -48,6 +48,7 @@ function startMcpView(options) {
48
48
  /** What the app runs on, here: the tools, the person, the frame's storage and theme, and the screen to draw. */
49
49
  function embedHost(bridge, screen) {
50
50
  const pending = createViewStore(void 0);
51
+ const refused = createViewStore(void 0);
51
52
  const context = createViewStore(bridge.hostContext);
52
53
  bridge.watchHostContext((next) => context.set(next));
53
54
  const told = modelContext(bridge);
@@ -64,7 +65,12 @@ function embedHost(bridge, screen) {
64
65
  resolve(confirmed);
65
66
  }
66
67
  })),
67
- onChange: told.changes
68
+ onChange: told.changes,
69
+ rowLabel: (name, id, row) => rowTitle(findCollection(screen.collections, name), id, row),
70
+ onWriteFailed: (failure) => {
71
+ refused.set(failure);
72
+ told.writeFailed(failure);
73
+ }
68
74
  });
69
75
  const host = {
70
76
  dataDriver: tools.driver,
@@ -78,6 +84,7 @@ function embedHost(bridge, screen) {
78
84
  screen,
79
85
  hostContext: context,
80
86
  pendingPlan: pending,
87
+ writeFailure: refused,
81
88
  onAppError: told.appError
82
89
  })
83
90
  };
@@ -184,7 +191,11 @@ function viewerAuth(viewer) {
184
191
  function modelContext(bridge) {
185
192
  const state = {};
186
193
  const send = () => {
187
- const text = [state.changes, state.error].filter(Boolean).join("\n");
194
+ const text = [
195
+ state.changes,
196
+ state.refused,
197
+ state.error
198
+ ].filter(Boolean).join("\n");
188
199
  if (text) bridge.updateModelContext(text).catch(() => void 0);
189
200
  };
190
201
  return {
@@ -192,12 +203,28 @@ function modelContext(bridge) {
192
203
  state.changes = describeChanges(changes);
193
204
  send();
194
205
  },
206
+ writeFailed: (failure) => {
207
+ state.refused = `The app tried to ${describeFailedWrite(failure)}, and the server refused: ${failure.message}`;
208
+ send();
209
+ },
195
210
  appError: (error) => {
196
211
  state.error = describeAppError(error);
197
212
  send();
198
213
  }
199
214
  };
200
215
  }
216
+ /**
217
+ * A row's title, as the admin names the record: the collection's title
218
+ * property where the row carries a readable value for it. Nothing where it
219
+ * does not — an opaque id says no more than the caller's fallback.
220
+ */
221
+ function rowTitle(collection, id, row) {
222
+ if (!collection || !row) return void 0;
223
+ const key = getTitlePropertyKeyForValues(collection, row, id);
224
+ const value = key ? row[key] : void 0;
225
+ if (typeof value === "number") return String(value);
226
+ return typeof value === "string" && value.trim() !== "" && !looksLikeIdentifierValue(value) ? value : void 0;
227
+ }
201
228
  /** An error where the app would be, before it could start. */
202
229
  function showError(message) {
203
230
  createRoot(document.getElementById("root") ?? document.body.appendChild(document.createElement("div"))).render(/* @__PURE__ */ jsx("div", {
@@ -230,6 +257,6 @@ function installSubmitFix() {
230
257
  }, true);
231
258
  }
232
259
  //#endregion
233
- export { narrowCollections, startMcpView };
260
+ export { narrowCollections, rowTitle, startMcpView };
234
261
 
235
262
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/mcp_view/index.tsx"],"sourcesContent":["/**\n * `@rebasepro/cms/mcp-view`: a project's admin app, inside an MCP App view.\n *\n * A client like Claude shows what the show_* tools open (a collection, a\n * record, an app the model wrote) in a sandboxed frame next to the\n * conversation. This is what runs in that frame: it speaks the host's\n * protocol, reads and writes through the server's tools as the person, and\n * draws with the admin panel's own components — inside the project's own\n * admin app, so its custom views, entity views, fields, previews, actions,\n * plugins and slots are the ones drawn.\n *\n * ```ts\n * // the project's view entry (the Vite plugin generates it)\n * import { startMcpView } from \"@rebasepro/cms/mcp-view\";\n * startMcpView({ mountApp: () => import(\"./main\") });\n * ```\n *\n * The app mounts as it does on its own page; `<Rebase>`, `<RebaseCMS>`,\n * `<RebaseStudio>` and `<RebaseShell>` find the embed host this sets\n * (`setRebaseEmbedHost` in `@rebasepro/app`) and stand in what the frame\n * cannot give them: data through the tools, the person already signed in,\n * no routes, no network.\n *\n * @module\n */\nimport React from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { setRebaseEmbedHost, type RebaseEmbedHost } from \"@rebasepro/app\";\nimport type { AdminCollection, AuthController } from \"@rebasepro/cms-types\";\nimport type { SecurityRule, User } from \"@rebasepro/types\";\nimport { Alert } from \"@rebasepro/ui\";\nimport { McpAppBridge, type HostContext, type ToolResult } from \"./bridge\";\nimport { createToolDriver, describeChanges, type ToolDriver, type ViewChange } from \"./tool_driver\";\nimport { findCollection, parseResult, type Screen } from \"./payload\";\nimport { describeAppError, type AppError } from \"./code_app\";\nimport { McpScreen, type PendingPlan } from \"./screen\";\nimport { VIEW_STORAGE_SOURCE } from \"./storage_source\";\nimport { createViewStore } from \"./store\";\n\nexport { APPS_PROTOCOL_VERSION, McpAppBridge, isRecord } from \"./bridge\";\nimport { isRecord } from \"./bridge\";\nexport type { HostContext, ToolResult, DisplayMode } from \"./bridge\";\nexport { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges } from \"./tool_driver\";\nexport type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange } from \"./tool_driver\";\nexport { parseResult, actionsOf, filterOf } from \"./payload\";\nexport type { Screen, Block } from \"./payload\";\n\nexport interface McpViewOptions {\n /**\n * Mount the app, once the host is set: import the project's entry (which\n * renders its app as it would on its page), or render a default one into\n * `#root`. Given the screen the tool opened, for an app with no\n * collections of its own.\n */\n mountApp: (screen: Screen) => void | Promise<unknown>;\n /**\n * Draw a result from a server that predates the admin panel's views\n * (show_collection's columns only): the old table, where the view has it.\n */\n mountTable?: (bridge: McpAppBridge, container: HTMLElement) => void;\n /** Name and version the view gives the host. */\n appInfo?: { name: string; version: string };\n /** The channel to the host; a new one on this window's parent by default. */\n bridge?: McpAppBridge;\n}\n\n/**\n * Connect to the host, wait for the tool's result, set the embed host from\n * it, and mount the app.\n */\nexport function startMcpView(options: McpViewOptions): McpAppBridge {\n installSubmitFix();\n const bridge = options.bridge ?? new McpAppBridge();\n let started = false;\n\n bridge.ontoolresult = (result: ToolResult) => {\n if (started) return;\n started = true;\n const parsed = parseResult(result);\n if (parsed.kind === \"table\") {\n const container = document.getElementById(\"root\");\n if (container && options.mountTable) options.mountTable(bridge, container);\n else showError(\"This view cannot draw this result.\");\n return;\n }\n if (parsed.kind === \"error\") {\n showError(parsed.message);\n return;\n }\n setRebaseEmbedHost(embedHost(bridge, parsed.screen));\n Promise.resolve(options.mountApp(parsed.screen))\n .catch(error => showError(`The view could not start: ${error instanceof Error ? error.message : String(error)}`));\n };\n\n // The host's light or dark, on the class the UI kit's `dark:` variant reads.\n bridge.watchHostContext(context => {\n if (context.theme) document.documentElement.classList.toggle(\"dark\", context.theme === \"dark\");\n });\n\n void bridge.connect(options.appInfo ?? { name: \"rebase\", version: \"0.3.0\" });\n return bridge;\n}\n\n/** What the app runs on, here: the tools, the person, the frame's storage and theme, and the screen to draw. */\nfunction embedHost(bridge: McpAppBridge, screen: Screen): RebaseEmbedHost {\n const pending = createViewStore<PendingPlan | undefined>(undefined);\n const context = createViewStore<HostContext>(bridge.hostContext);\n bridge.watchHostContext(next => context.set(next));\n\n const told = modelContext(bridge);\n const tools: ToolDriver = createToolDriver({\n callTool: (name, args) => bridge.callTool(name, args),\n actions: screen.actions,\n ...(screen.firstPage && { seed: screen.firstPage }),\n ...(screen.seeds && { seeds: screen.seeds }),\n // A collection by whichever name it was read or written under: its\n // data path (the tools' name, the model's) or its slug (the admin's).\n collection: name => findCollection(screen.collections, name),\n confirm: plan => new Promise<boolean>(resolve => pending.set({\n plan,\n answer: confirmed => {\n pending.set(undefined);\n resolve(confirmed);\n }\n })),\n onChange: told.changes\n });\n\n const host: RebaseEmbedHost = {\n dataDriver: tools.driver,\n // Code can write without a click, so the row hooks ask the person\n // before each write; a save made with the admin's own controls goes\n // as on any screen. A courtesy, not the boundary: every call is the\n // server's tool as the person, under their RLS and granted scopes.\n rowHooksDriver: tools.confirmingDriver,\n authController: viewerAuth(screen.viewer),\n storageSource: VIEW_STORAGE_SOURCE,\n mode: bridge.hostContext.theme === \"dark\" ? \"dark\" : \"light\",\n narrowCollections: collections => narrowCollections(collections, screen.collections),\n renderCms: () => (\n <McpScreen\n bridge={bridge}\n screen={screen}\n hostContext={context}\n pendingPlan={pending}\n onAppError={told.appError}\n />\n )\n };\n // The theme follows the host's.\n bridge.watchHostContext(next => {\n const mode = next.theme === \"dark\" ? \"dark\" : \"light\";\n if (mode !== host.mode) {\n host.mode = mode;\n setRebaseEmbedHost({ ...host });\n }\n });\n return host;\n}\n\n/**\n * The app's collections as this person may see them here: the project's own\n * configs — with their components — narrowed as the server narrowed the ones\n * it sent (`McpViewPayload` in the server's `mcp/mcp-view.ts`). A field the\n * server left out is left out; one it made read-only is read-only; its\n * security rules (the project's, and the one closing what the connection was\n * not granted) are the ones checked. A collection the server sent nothing\n * for is shown with every change closed: this screen did not ask for it.\n *\n * Where the app has no collections of its own (the view without a project),\n * the server's configs are the collections.\n */\nexport function narrowCollections(own: AdminCollection[], sent: readonly AdminCollection[]): AdminCollection[] {\n if (own.length === 0) return [...sent];\n const bySlug = new Map(sent.map(collection => [collection.slug, collection]));\n return own.map((collection): AdminCollection => {\n const narrowed = bySlug.get(collection.slug);\n if (!narrowed) {\n return { ...collection, securityRules: [...(collection.securityRules ?? []), CLOSED] };\n }\n const copy = { ...collection };\n return Object.assign(copy, {\n properties: narrowProperties(collection.properties, narrowed.properties),\n securityRules: narrowed.securityRules ?? collection.securityRules\n });\n });\n}\n\n/** The fields the server sent, with its read-only marks; the project's own config for each. */\nfunction narrowProperties<P extends Record<string, unknown>>(own: P, sent: Record<string, unknown>): P {\n const narrowed = { ...own };\n for (const key of Object.keys(narrowed)) {\n const sentProperty = sent[key];\n if (!sentProperty) {\n delete narrowed[key];\n continue;\n }\n const property = narrowed[key];\n if (isRecord(sentProperty) && isRecord(sentProperty.admin) && sentProperty.admin.readOnly === true && isRecord(property)) {\n Object.assign(narrowed, { [key]: { ...property, admin: { ...(isRecord(property.admin) ? property.admin : {}), readOnly: true } } });\n }\n }\n return narrowed;\n}\n\n/** A restrictive rule no account passes, closing every change. */\nconst CLOSED: SecurityRule = {\n name: \"mcp_view_not_opened\",\n mode: \"restrictive\",\n operations: [\"insert\", \"update\", \"delete\"],\n roles: [\"__mcp_view_not_opened__\"]\n};\n\n/**\n * The person the server drew the screen for, as the admin panel asks about\n * them: the security rules it evaluates before offering an action read\n * `uid` and `roles`. Signing out means nothing here — the host holds the\n * connection.\n */\nfunction viewerAuth(viewer: Screen[\"viewer\"]): AuthController {\n const user: User = {\n uid: viewer.uid,\n displayName: null,\n email: null,\n photoURL: null,\n providerId: \"mcp\",\n isAnonymous: false,\n roles: viewer.roles\n };\n return {\n user,\n initialLoading: false,\n authLoading: false,\n loginSkipped: true,\n storageEnabled: false,\n signOut: async () => undefined,\n getAuthToken: async () => \"\",\n extra: undefined,\n setExtra: () => undefined\n };\n}\n\n/**\n * What the model is told, sent with the person's next message: the changes\n * they made here, and an app's failure. Each update replaces the last, so\n * both go every time.\n */\nfunction modelContext(bridge: McpAppBridge) {\n const state: { changes?: string; error?: string } = {};\n const send = () => {\n const text = [state.changes, state.error].filter(Boolean).join(\"\\n\");\n if (text) void bridge.updateModelContext(text).catch(() => undefined);\n };\n return {\n changes: (changes: readonly ViewChange[]) => {\n state.changes = describeChanges(changes);\n send();\n },\n appError: (error: AppError) => {\n state.error = describeAppError(error);\n send();\n }\n };\n}\n\n/** An error where the app would be, before it could start. */\nfunction showError(message: string): void {\n const container = document.getElementById(\"root\") ?? document.body.appendChild(document.createElement(\"div\"));\n createRoot(container).render(<div className=\"p-4\"><Alert color=\"error\" size=\"small\">{message}</Alert></div>);\n}\n\n/**\n * A host may sandbox the view without `allow-forms`, and then a form's submit\n * button submits nothing: the browser drops the submission before the form's\n * `submit` event — the admin panel's record form saves on that event. The\n * click still happens, so it is turned into the event itself, after the click\n * has finished (a button's own handler may say which save it was).\n */\nfunction installSubmitFix(): void {\n document.addEventListener(\"click\", (event) => {\n const button = event.target instanceof Element ? event.target.closest(\"button[type=submit]\") : null;\n if (!(button instanceof HTMLButtonElement) || !button.form || button.disabled) return;\n event.preventDefault();\n const form = button.form;\n setTimeout(() => form.dispatchEvent(new SubmitEvent(\"submit\", { bubbles: true, cancelable: true, submitter: button })));\n }, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsEA,SAAgB,aAAa,SAAuC;CAChE,iBAAiB;CACjB,MAAM,SAAS,QAAQ,UAAU,IAAI,aAAa;CAClD,IAAI,UAAU;CAEd,OAAO,gBAAgB,WAAuB;EAC1C,IAAI,SAAS;EACb,UAAU;EACV,MAAM,SAAS,YAAY,MAAM;EACjC,IAAI,OAAO,SAAS,SAAS;GACzB,MAAM,YAAY,SAAS,eAAe,MAAM;GAChD,IAAI,aAAa,QAAQ,YAAY,QAAQ,WAAW,QAAQ,SAAS;QACpE,UAAU,oCAAoC;GACnD;EACJ;EACA,IAAI,OAAO,SAAS,SAAS;GACzB,UAAU,OAAO,OAAO;GACxB;EACJ;EACA,mBAAmB,UAAU,QAAQ,OAAO,MAAM,CAAC;EACnD,QAAQ,QAAQ,QAAQ,SAAS,OAAO,MAAM,CAAC,CAAC,CAC3C,OAAM,UAAS,UAAU,6BAA6B,iBAAiB,QAAQ,MAAM,UAA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,UAAU;GAAE,SAAS;GAAM,YAAY;GAAM,WAAW;EAAO,CAAC,CAAC,CAAC;CAC1H,GAAG,IAAI;AACX"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/mcp_view/index.tsx"],"sourcesContent":["/**\n * `@rebasepro/cms/mcp-view`: a project's admin app, inside an MCP App view.\n *\n * A client like Claude shows what the show_* tools open (a collection, a\n * record, an app the model wrote) in a sandboxed frame next to the\n * conversation. This is what runs in that frame: it speaks the host's\n * protocol, reads and writes through the server's tools as the person, and\n * draws with the admin panel's own components — inside the project's own\n * admin app, so its custom views, entity views, fields, previews, actions,\n * plugins and slots are the ones drawn.\n *\n * ```ts\n * // the project's view entry (the Vite plugin generates it)\n * import { startMcpView } from \"@rebasepro/cms/mcp-view\";\n * startMcpView({ mountApp: () => import(\"./main\") });\n * ```\n *\n * The app mounts as it does on its own page; `<Rebase>`, `<RebaseCMS>`,\n * `<RebaseStudio>` and `<RebaseShell>` find the embed host this sets\n * (`setRebaseEmbedHost` in `@rebasepro/app`) and stand in what the frame\n * cannot give them: data through the tools, the person already signed in,\n * no routes, no network.\n *\n * @module\n */\nimport React from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { getTitlePropertyKeyForValues, looksLikeIdentifierValue, setRebaseEmbedHost, type RebaseEmbedHost } from \"@rebasepro/app\";\nimport type { AdminCollection, AuthController } from \"@rebasepro/cms-types\";\nimport type { SecurityRule, User } from \"@rebasepro/types\";\nimport { Alert } from \"@rebasepro/ui\";\nimport { McpAppBridge, type HostContext, type ToolResult } from \"./bridge\";\nimport { createToolDriver, describeChanges, describeFailedWrite, type ToolDriver, type ViewChange, type WriteFailure } from \"./tool_driver\";\nimport { findCollection, parseResult, type Screen } from \"./payload\";\nimport { describeAppError, type AppError } from \"./code_app\";\nimport { McpScreen, type PendingPlan } from \"./screen\";\nimport { VIEW_STORAGE_SOURCE } from \"./storage_source\";\nimport { createViewStore } from \"./store\";\n\nexport { APPS_PROTOCOL_VERSION, McpAppBridge, isRecord } from \"./bridge\";\nimport { isRecord } from \"./bridge\";\nexport type { HostContext, ToolResult, DisplayMode } from \"./bridge\";\nexport { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite } from \"./tool_driver\";\nexport type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange, WriteFailure } from \"./tool_driver\";\nexport { parseResult, actionsOf, filterOf } from \"./payload\";\nexport type { Screen, Block } from \"./payload\";\n\nexport interface McpViewOptions {\n /**\n * Mount the app, once the host is set: import the project's entry (which\n * renders its app as it would on its page), or render a default one into\n * `#root`. Given the screen the tool opened, for an app with no\n * collections of its own.\n */\n mountApp: (screen: Screen) => void | Promise<unknown>;\n /**\n * Draw a result from a server that predates the admin panel's views\n * (show_collection's columns only): the old table, where the view has it.\n */\n mountTable?: (bridge: McpAppBridge, container: HTMLElement) => void;\n /** Name and version the view gives the host. */\n appInfo?: { name: string; version: string };\n /** The channel to the host; a new one on this window's parent by default. */\n bridge?: McpAppBridge;\n}\n\n/**\n * Connect to the host, wait for the tool's result, set the embed host from\n * it, and mount the app.\n */\nexport function startMcpView(options: McpViewOptions): McpAppBridge {\n installSubmitFix();\n const bridge = options.bridge ?? new McpAppBridge();\n let started = false;\n\n bridge.ontoolresult = (result: ToolResult) => {\n if (started) return;\n started = true;\n const parsed = parseResult(result);\n if (parsed.kind === \"table\") {\n const container = document.getElementById(\"root\");\n if (container && options.mountTable) options.mountTable(bridge, container);\n else showError(\"This view cannot draw this result.\");\n return;\n }\n if (parsed.kind === \"error\") {\n showError(parsed.message);\n return;\n }\n setRebaseEmbedHost(embedHost(bridge, parsed.screen));\n Promise.resolve(options.mountApp(parsed.screen))\n .catch(error => showError(`The view could not start: ${error instanceof Error ? error.message : String(error)}`));\n };\n\n // The host's light or dark, on the class the UI kit's `dark:` variant reads.\n bridge.watchHostContext(context => {\n if (context.theme) document.documentElement.classList.toggle(\"dark\", context.theme === \"dark\");\n });\n\n void bridge.connect(options.appInfo ?? { name: \"rebase\", version: \"0.3.0\" });\n return bridge;\n}\n\n/** What the app runs on, here: the tools, the person, the frame's storage and theme, and the screen to draw. */\nfunction embedHost(bridge: McpAppBridge, screen: Screen): RebaseEmbedHost {\n const pending = createViewStore<PendingPlan | undefined>(undefined);\n const refused = createViewStore<WriteFailure | undefined>(undefined);\n const context = createViewStore<HostContext>(bridge.hostContext);\n bridge.watchHostContext(next => context.set(next));\n\n const told = modelContext(bridge);\n const tools: ToolDriver = createToolDriver({\n callTool: (name, args) => bridge.callTool(name, args),\n actions: screen.actions,\n ...(screen.firstPage && { seed: screen.firstPage }),\n ...(screen.seeds && { seeds: screen.seeds }),\n // A collection by whichever name it was read or written under: its\n // data path (the tools' name, the model's) or its slug (the admin's).\n collection: name => findCollection(screen.collections, name),\n confirm: plan => new Promise<boolean>(resolve => pending.set({\n plan,\n answer: confirmed => {\n pending.set(undefined);\n resolve(confirmed);\n }\n })),\n onChange: told.changes,\n rowLabel: (name, id, row) => rowTitle(findCollection(screen.collections, name), id, row),\n onWriteFailed: failure => {\n refused.set(failure);\n told.writeFailed(failure);\n }\n });\n\n const host: RebaseEmbedHost = {\n dataDriver: tools.driver,\n // Code can write without a click, so the row hooks ask the person\n // before each write; a save made with the admin's own controls goes\n // as on any screen. A courtesy, not the boundary: every call is the\n // server's tool as the person, under their RLS and granted scopes.\n rowHooksDriver: tools.confirmingDriver,\n authController: viewerAuth(screen.viewer),\n storageSource: VIEW_STORAGE_SOURCE,\n mode: bridge.hostContext.theme === \"dark\" ? \"dark\" : \"light\",\n narrowCollections: collections => narrowCollections(collections, screen.collections),\n renderCms: () => (\n <McpScreen\n bridge={bridge}\n screen={screen}\n hostContext={context}\n pendingPlan={pending}\n writeFailure={refused}\n onAppError={told.appError}\n />\n )\n };\n // The theme follows the host's.\n bridge.watchHostContext(next => {\n const mode = next.theme === \"dark\" ? \"dark\" : \"light\";\n if (mode !== host.mode) {\n host.mode = mode;\n setRebaseEmbedHost({ ...host });\n }\n });\n return host;\n}\n\n/**\n * The app's collections as this person may see them here: the project's own\n * configs — with their components — narrowed as the server narrowed the ones\n * it sent (`McpViewPayload` in the server's `mcp/mcp-view.ts`). A field the\n * server left out is left out; one it made read-only is read-only; its\n * security rules (the project's, and the one closing what the connection was\n * not granted) are the ones checked. A collection the server sent nothing\n * for is shown with every change closed: this screen did not ask for it.\n *\n * Where the app has no collections of its own (the view without a project),\n * the server's configs are the collections.\n */\nexport function narrowCollections(own: AdminCollection[], sent: readonly AdminCollection[]): AdminCollection[] {\n if (own.length === 0) return [...sent];\n const bySlug = new Map(sent.map(collection => [collection.slug, collection]));\n return own.map((collection): AdminCollection => {\n const narrowed = bySlug.get(collection.slug);\n if (!narrowed) {\n return { ...collection, securityRules: [...(collection.securityRules ?? []), CLOSED] };\n }\n const copy = { ...collection };\n return Object.assign(copy, {\n properties: narrowProperties(collection.properties, narrowed.properties),\n securityRules: narrowed.securityRules ?? collection.securityRules\n });\n });\n}\n\n/** The fields the server sent, with its read-only marks; the project's own config for each. */\nfunction narrowProperties<P extends Record<string, unknown>>(own: P, sent: Record<string, unknown>): P {\n const narrowed = { ...own };\n for (const key of Object.keys(narrowed)) {\n const sentProperty = sent[key];\n if (!sentProperty) {\n delete narrowed[key];\n continue;\n }\n const property = narrowed[key];\n if (isRecord(sentProperty) && isRecord(sentProperty.admin) && sentProperty.admin.readOnly === true && isRecord(property)) {\n Object.assign(narrowed, { [key]: { ...property, admin: { ...(isRecord(property.admin) ? property.admin : {}), readOnly: true } } });\n }\n }\n return narrowed;\n}\n\n/** A restrictive rule no account passes, closing every change. */\nconst CLOSED: SecurityRule = {\n name: \"mcp_view_not_opened\",\n mode: \"restrictive\",\n operations: [\"insert\", \"update\", \"delete\"],\n roles: [\"__mcp_view_not_opened__\"]\n};\n\n/**\n * The person the server drew the screen for, as the admin panel asks about\n * them: the security rules it evaluates before offering an action read\n * `uid` and `roles`. Signing out means nothing here — the host holds the\n * connection.\n */\nfunction viewerAuth(viewer: Screen[\"viewer\"]): AuthController {\n const user: User = {\n uid: viewer.uid,\n displayName: null,\n email: null,\n photoURL: null,\n providerId: \"mcp\",\n isAnonymous: false,\n roles: viewer.roles\n };\n return {\n user,\n initialLoading: false,\n authLoading: false,\n loginSkipped: true,\n storageEnabled: false,\n signOut: async () => undefined,\n getAuthToken: async () => \"\",\n extra: undefined,\n setExtra: () => undefined\n };\n}\n\n/**\n * What the model is told, sent with the person's next message: the changes\n * they made here, and an app's failure. Each update replaces the last, so\n * both go every time.\n */\nfunction modelContext(bridge: McpAppBridge) {\n const state: { changes?: string; refused?: string; error?: string } = {};\n const send = () => {\n const text = [state.changes, state.refused, state.error].filter(Boolean).join(\"\\n\");\n if (text) void bridge.updateModelContext(text).catch(() => undefined);\n };\n return {\n changes: (changes: readonly ViewChange[]) => {\n state.changes = describeChanges(changes);\n send();\n },\n writeFailed: (failure: WriteFailure) => {\n state.refused = `The app tried to ${describeFailedWrite(failure)}, and the server refused: ${failure.message}`;\n send();\n },\n appError: (error: AppError) => {\n state.error = describeAppError(error);\n send();\n }\n };\n}\n\n/**\n * A row's title, as the admin names the record: the collection's title\n * property where the row carries a readable value for it. Nothing where it\n * does not — an opaque id says no more than the caller's fallback.\n */\nexport function rowTitle(collection: AdminCollection | undefined, id: string, row: Record<string, unknown> | undefined): string | undefined {\n if (!collection || !row) return undefined;\n const key = getTitlePropertyKeyForValues(collection, row, id);\n const value = key ? row[key] : undefined;\n if (typeof value === \"number\") return String(value);\n return typeof value === \"string\" && value.trim() !== \"\" && !looksLikeIdentifierValue(value) ? value : undefined;\n}\n\n/** An error where the app would be, before it could start. */\nfunction showError(message: string): void {\n const container = document.getElementById(\"root\") ?? document.body.appendChild(document.createElement(\"div\"));\n createRoot(container).render(<div className=\"p-4\"><Alert color=\"error\" size=\"small\">{message}</Alert></div>);\n}\n\n/**\n * A host may sandbox the view without `allow-forms`, and then a form's submit\n * button submits nothing: the browser drops the submission before the form's\n * `submit` event — the admin panel's record form saves on that event. The\n * click still happens, so it is turned into the event itself, after the click\n * has finished (a button's own handler may say which save it was).\n */\nfunction installSubmitFix(): void {\n document.addEventListener(\"click\", (event) => {\n const button = event.target instanceof Element ? event.target.closest(\"button[type=submit]\") : null;\n if (!(button instanceof HTMLButtonElement) || !button.form || button.disabled) return;\n event.preventDefault();\n const form = button.form;\n setTimeout(() => form.dispatchEvent(new SubmitEvent(\"submit\", { bubbles: true, cancelable: true, submitter: button })));\n }, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsEA,SAAgB,aAAa,SAAuC;CAChE,iBAAiB;CACjB,MAAM,SAAS,QAAQ,UAAU,IAAI,aAAa;CAClD,IAAI,UAAU;CAEd,OAAO,gBAAgB,WAAuB;EAC1C,IAAI,SAAS;EACb,UAAU;EACV,MAAM,SAAS,YAAY,MAAM;EACjC,IAAI,OAAO,SAAS,SAAS;GACzB,MAAM,YAAY,SAAS,eAAe,MAAM;GAChD,IAAI,aAAa,QAAQ,YAAY,QAAQ,WAAW,QAAQ,SAAS;QACpE,UAAU,oCAAoC;GACnD;EACJ;EACA,IAAI,OAAO,SAAS,SAAS;GACzB,UAAU,OAAO,OAAO;GACxB;EACJ;EACA,mBAAmB,UAAU,QAAQ,OAAO,MAAM,CAAC;EACnD,QAAQ,QAAQ,QAAQ,SAAS,OAAO,MAAM,CAAC,CAAC,CAC3C,OAAM,UAAS,UAAU,6BAA6B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,CAAC;CACxH;CAGA,OAAO,kBAAiB,YAAW;EAC/B,IAAI,QAAQ,OAAO,SAAS,gBAAgB,UAAU,OAAO,QAAQ,QAAQ,UAAU,MAAM;CACjG,CAAC;CAED,OAAY,QAAQ,QAAQ,WAAW;EAAE,MAAM;EAAU,SAAS;CAAQ,CAAC;CAC3E,OAAO;AACX;;AAGA,SAAS,UAAU,QAAsB,QAAiC;CACtE,MAAM,UAAU,gBAAyC,KAAA,CAAS;CAClE,MAAM,UAAU,gBAA0C,KAAA,CAAS;CACnE,MAAM,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/G;;;;;;;;AASA,SAAS,mBAAyB;CAC9B,SAAS,iBAAiB,UAAU,UAAU;EAC1C,MAAM,SAAS,MAAM,kBAAkB,UAAU,MAAM,OAAO,QAAQ,qBAAqB,IAAI;EAC/F,IAAI,EAAE,kBAAkB,sBAAsB,CAAC,OAAO,QAAQ,OAAO,UAAU;EAC/E,MAAM,eAAe;EACrB,MAAM,OAAO,OAAO;EACpB,iBAAiB,KAAK,cAAc,IAAI,YAAY,UAAU;GAAE,SAAS;GAAM,YAAY;GAAM,WAAW;EAAO,CAAC,CAAC,CAAC;CAC1H,GAAG,IAAI;AACX"}
@@ -1,6 +1,6 @@
1
1
  import React from "react";
2
2
  import type { HostContext, McpAppBridge } from "./bridge.js";
3
- import type { WritePlan } from "./tool_driver.js";
3
+ import { type WriteFailure, type WritePlan } from "./tool_driver.js";
4
4
  import { type Screen } from "./payload.js";
5
5
  import { type AppError } from "./code_app.js";
6
6
  import { type ViewStore } from "./store.js";
@@ -16,6 +16,8 @@ export interface McpScreenProps {
16
16
  hostContext: ViewStore<HostContext>;
17
17
  /** The write plan to confirm, as it changes. */
18
18
  pendingPlan: ViewStore<PendingPlan | undefined>;
19
+ /** The last write the server refused, as it changes: shown to the person, once each. */
20
+ writeFailure?: ViewStore<WriteFailure | undefined>;
19
21
  onAppError: (error: AppError) => void;
20
22
  }
21
23
  /**
@@ -25,4 +27,4 @@ export interface McpScreenProps {
25
27
  * collections, custom views, entity views, fields and actions are the ones
26
28
  * drawn.
27
29
  */
28
- export declare function McpScreen({ bridge, screen, hostContext, pendingPlan, onAppError }: McpScreenProps): React.JSX.Element;
30
+ export declare function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, onAppError }: McpScreenProps): React.JSX.Element;
@@ -1,11 +1,12 @@
1
1
  import { useCollectionRegistryController } from "../hooks/navigation/contexts/CollectionRegistryContext.js";
2
2
  import { CollectionPanel } from "../components/CollectionPanel.js";
3
3
  import { RecordForm } from "../components/RecordForm.js";
4
+ import { describeFailedWrite } from "./tool_driver.js";
4
5
  import { filterOf, orderOf } from "./payload.js";
5
6
  import { AppCollections } from "./app_modules.js";
6
7
  import { AppErrorBoundary, loadApp } from "./code_app.js";
7
- import { useViewStore } from "./store.js";
8
- import { useEffect, useMemo, useRef, useState } from "react";
8
+ import { createViewStore, useViewStore } from "./store.js";
9
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
9
10
  import { jsx, jsxs } from "react/jsx-runtime";
10
11
  import { Alert, Button, Card, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Maximize2Icon, Tooltip, Typography, cls, iconSize } from "@rebasepro/ui";
11
12
  //#region src/mcp_view/screen.tsx
@@ -24,10 +25,11 @@ var INLINE_MAX_HEIGHT = 640;
24
25
  * collections, custom views, entity views, fields and actions are the ones
25
26
  * drawn.
26
27
  */
27
- function McpScreen({ bridge, screen, hostContext, pendingPlan, onAppError }) {
28
+ function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, onAppError }) {
28
29
  const rootRef = useRef(null);
29
30
  const context = useViewStore(hostContext);
30
31
  const pending = useViewStore(pendingPlan);
32
+ const [refused, dismissRefused] = useRefusedWrite(writeFailure);
31
33
  const registry = useCollectionRegistryController();
32
34
  const fullscreen = context.displayMode === "fullscreen";
33
35
  const canExpand = !fullscreen && context.availableDisplayModes?.includes("fullscreen") === true;
@@ -94,6 +96,13 @@ function McpScreen({ bridge, screen, hostContext, pendingPlan, onAppError }) {
94
96
  })
95
97
  })]
96
98
  }),
99
+ refused && /* @__PURE__ */ jsx(Alert, {
100
+ color: "error",
101
+ size: "small",
102
+ outerClassName: "sticky top-0 z-10",
103
+ onDismiss: dismissRefused,
104
+ children: `Could not ${describeFailedWrite(refused)}: ${refused.message}`
105
+ }),
97
106
  body,
98
107
  /* @__PURE__ */ jsxs(Dialog, {
99
108
  open: pending !== void 0,
@@ -217,6 +226,19 @@ function AppView({ block, onError }) {
217
226
  })
218
227
  });
219
228
  }
229
+ /**
230
+ * The last write the server refused, until the person dismisses it: an app's
231
+ * code can drop the rejection, and a button the app drew shows nothing of its
232
+ * own (the admin's own controls show theirs). Shown in the screen, not as a
233
+ * snackbar, which the sandboxed frame left off its edge.
234
+ */
235
+ function useRefusedWrite(store) {
236
+ const failure = useViewStore(store ?? NO_FAILURES);
237
+ const [dismissed, setDismissed] = useState(void 0);
238
+ const dismiss = useCallback(() => setDismissed(failure), [failure]);
239
+ return [failure !== dismissed ? failure : void 0, dismiss];
240
+ }
241
+ var NO_FAILURES = createViewStore(void 0);
220
242
  //#endregion
221
243
  export { McpScreen };
222
244
 
@@ -1 +1 @@
1
- {"version":3,"file":"screen.js","names":[],"sources":["../../src/mcp_view/screen.tsx"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport {\n Alert,\n Button,\n Card,\n CircularProgress,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n IconButton,\n Maximize2Icon,\n Tooltip,\n Typography,\n cls,\n iconSize\n} from \"@rebasepro/ui\";\nimport { CollectionPanel } from \"../components/CollectionPanel\";\nimport { RecordForm } from \"../components/RecordForm\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport type { HostContext, McpAppBridge } from \"./bridge\";\nimport type { WritePlan } from \"./tool_driver\";\nimport { filterOf, orderOf, type AppBlock, type CollectionBlock, type RecordBlock, type Screen } from \"./payload\";\nimport { AppErrorBoundary, loadApp, type AppError } from \"./code_app\";\nimport { AppCollections } from \"./app_modules\";\nimport { useViewStore, type ViewStore } from \"./store\";\n\n/**\n * The tallest the screen is in the conversation; past it, a collection\n * scrolls inside its own block, and anything else inside the screen. A\n * record's form and the confirmation of a save open over the frame, centred\n * in it: in a frame as tall as everything on the screen they would open where\n * the person is not looking.\n */\nconst INLINE_MAX_HEIGHT = 640;\n\n/** A write's plan waiting for the person's answer. */\nexport interface PendingPlan {\n plan: WritePlan;\n answer: (confirmed: boolean) => void;\n}\n\nexport interface McpScreenProps {\n bridge: McpAppBridge;\n screen: Screen;\n /** The host's context, as it changes. */\n hostContext: ViewStore<HostContext>;\n /** The write plan to confirm, as it changes. */\n pendingPlan: ViewStore<PendingPlan | undefined>;\n onAppError: (error: AppError) => void;\n}\n\n/**\n * What the embedded app's shell draws (`renderCms` of the embed host): the\n * one block the tool opened — a collection, a record, or an app the model\n * wrote — inside the providers the app's own `<RebaseShell>` set up, so its\n * collections, custom views, entity views, fields and actions are the ones\n * drawn.\n */\nexport function McpScreen({ bridge, screen, hostContext, pendingPlan, onAppError }: McpScreenProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n const context = useViewStore(hostContext);\n const pending = useViewStore(pendingPlan);\n const registry = useCollectionRegistryController();\n const fullscreen = context.displayMode === \"fullscreen\";\n const canExpand = !fullscreen && context.availableDisplayModes?.includes(\"fullscreen\") === true;\n const block = screen.blocks[0];\n\n // The host sizes the frame to the document, which it cannot measure\n // across the sandbox.\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n const measure = () => {\n const html = document.documentElement;\n const previous = html.style.height;\n html.style.height = \"max-content\";\n bridge.sizeChanged(Math.ceil(html.getBoundingClientRect().height));\n html.style.height = previous;\n };\n const observer = new ResizeObserver(measure);\n observer.observe(root);\n measure();\n return () => observer.disconnect();\n }, [bridge]);\n\n const collectionOf = (name: string): AdminCollection | undefined => registry.getCollection(name);\n const heading = screen.title ?? (block.type === \"app\" ? undefined : blockTitle(block, collectionOf(block.collection)));\n\n let body: React.ReactNode;\n if (!registry.initialised && !registry.collections?.length) {\n body = <CircularProgress size=\"smallest\"/>;\n } else if (block.type === \"app\") {\n body = <AppView block={block} onError={onAppError}/>;\n } else {\n const collection = collectionOf(block.collection);\n body = !collection\n ? <Alert color=\"error\" size=\"small\">The collection &quot;{block.collection}&quot; is not in this view.</Alert>\n : block.type === \"collection\"\n ? <CollectionView block={block} collection={collection}/>\n : <RecordView block={block} collection={collection}/>;\n }\n\n return (\n <div ref={rootRef}\n className={cls(\"flex flex-col gap-4 p-4 w-full min-w-0 bg-surface-sheet overflow-y-auto\", fullscreen && \"h-screen\")}\n style={fullscreen ? undefined : { maxHeight: INLINE_MAX_HEIGHT }}>\n {(heading || canExpand) && (\n <div className=\"flex items-center justify-between gap-3 min-h-8\">\n <Typography variant=\"subtitle2\" noWrap>{heading}</Typography>\n {canExpand && (\n <Tooltip title=\"Expand\">\n <IconButton\n size=\"small\"\n aria-label=\"Expand\"\n onClick={() => void bridge.requestDisplayMode(\"fullscreen\").catch(() => undefined)}\n >\n <Maximize2Icon size={iconSize.smallest}/>\n </IconButton>\n </Tooltip>\n )}\n </div>\n )}\n {body}\n <Dialog open={pending !== undefined} onOpenChange={open => !open && pending?.answer(false)} maxWidth=\"sm\">\n <DialogTitle variant=\"subtitle1\">Confirm this change</DialogTitle>\n <DialogContent className=\"flex flex-col gap-2\">\n <Typography variant=\"body2\">{pending?.plan.summary}</Typography>\n {pending?.plan.effects?.map(effect => (\n <Typography key={effect} variant=\"body2\" color=\"secondary\">{effect}</Typography>\n ))}\n {pending?.plan.reversible && (\n <Typography variant=\"caption\" color=\"secondary\">Undo: {pending.plan.reversible}</Typography>\n )}\n </DialogContent>\n <DialogActions>\n <Button variant=\"text\" color=\"neutral\" onClick={() => pending?.answer(false)}>Cancel</Button>\n <Button variant=\"filled\" color=\"primary\" onClick={() => pending?.answer(true)}>Save</Button>\n </DialogActions>\n </Dialog>\n </div>\n );\n}\n\nfunction blockTitle(block: CollectionBlock | RecordBlock, collection: AdminCollection | undefined): string {\n if (block.type === \"record\") {\n const name = collection?.singularName ?? collection?.name ?? block.collection;\n return block.id === undefined ? `New ${name.toLowerCase()}` : name;\n }\n return collection?.name ?? block.collection;\n}\n\n/**\n * show_collection: the admin panel's collection view, where a row opens its\n * form over the screen. It sizes to its rows, up to what the screen leaves\n * it — inline, the screen's height cap; full screen, the window — and then\n * scrolls inside.\n */\nfunction CollectionView({ block, collection }: {\n block: CollectionBlock;\n collection: AdminCollection;\n}) {\n const overrides = useMemo<Partial<AdminCollection>>(() => {\n // The model's filter, as one the person can clear.\n const where = filterOf(block.where);\n return {\n ...(where && { defaultFilter: where }),\n ...(block.limit !== undefined && { pagination: block.limit })\n };\n }, [block.where, block.limit]);\n const sort = orderOf(block.orderBy);\n\n return (\n <CollectionPanel\n collection={collection.slug}\n title={false}\n className=\"flex-1 rounded-xl overflow-hidden\"\n {...(block.view && { viewMode: block.view })}\n {...(sort && { orderBy: sort })}\n collectionOverrides={overrides}\n />\n );\n}\n\n/** show_record: the admin panel's form, for a row or a new one. */\nfunction RecordView({ block, collection }: { block: RecordBlock; collection: AdminCollection }) {\n // A new row's form becomes that row's once it is saved.\n const [created, setCreated] = useState<string | number>();\n const id = block.id ?? created;\n return (\n <Card className=\"min-w-0 overflow-hidden\">\n <RecordForm\n key={String(id ?? \"new\")}\n collection={collection}\n id={id}\n {...(id === undefined && block.values && { defaultValues: block.values })}\n onSaved={params => {\n if (id === undefined) setCreated(params.id);\n }}\n />\n </Card>\n );\n}\n\n/**\n * show_app: the app the model wrote, held to the collections it was opened\n * with, and its failure shown in its place.\n */\nfunction AppView({ block, onError }: {\n block: AppBlock;\n onError: (error: AppError) => void;\n}) {\n const loaded = useMemo(() => loadApp(block.code), [block.code]);\n\n // A module that failed as it loaded is told once.\n useEffect(() => {\n if (loaded.error) onError(loaded.error);\n }, [loaded, onError]);\n\n const failure = (error: AppError) => (\n <Alert color=\"error\" size=\"small\">\n The app failed{error.line ? ` at line ${error.line}` : \"\"}: {error.message}\n </Alert>\n );\n if (!loaded.Component) return failure(loaded.error ?? { message: \"The app did not load.\" });\n const { Component } = loaded;\n return (\n <AppErrorBoundary lineOffset={loaded.lineOffset} onError={onError} fallback={failure}>\n <AppCollections names={block.collections}>\n <Component/>\n </AppCollections>\n </AppErrorBoundary>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmCA,IAAM,oBAAoB;;;;;;;;AAyB1B,SAAgB,UAAU,EAAE,QAAQ,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Z,IAAI,OAAO,OAAO,QAAQ,OAAO,KAAK;CAC1C,GAAG,CAAC,QAAQ,OAAO,CAAC;CAEpB,MAAM,WAAW,UACb,qBAAC,OAAD;EAAO,OAAM;EAAQ,MAAK;YAA1B;GAAkC;GACf,MAAM,OAAO,YAAY,MAAM,SAAS;GAAG;GAAG,MAAM;EAChE;;CAEX,IAAI,CAAC,OAAO,WAAW,OAAO,QAAQ,OAAO,SAAS,EAAE,SAAS,wBAAwB,CAAC;CAC1F,MAAM,EAAE,cAAc;CACtB,OACI,oBAAC,kBAAD;EAAkB,YAAY,OAAO;EAAqB;EAAS,UAAU;YACzE,oBAAC,gBAAD;GAAgB,OAAO,MAAM;aACzB,oBAAC,WAAD,CAAW,CAAA;EACC,CAAA;CACF,CAAA;AAE1B"}
1
+ {"version":3,"file":"screen.js","names":[],"sources":["../../src/mcp_view/screen.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport {\n Alert,\n Button,\n Card,\n CircularProgress,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n IconButton,\n Maximize2Icon,\n Tooltip,\n Typography,\n cls,\n iconSize\n} from \"@rebasepro/ui\";\nimport { CollectionPanel } from \"../components/CollectionPanel\";\nimport { RecordForm } from \"../components/RecordForm\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport type { HostContext, McpAppBridge } from \"./bridge\";\nimport { describeFailedWrite, type WriteFailure, type WritePlan } from \"./tool_driver\";\nimport { filterOf, orderOf, type AppBlock, type CollectionBlock, type RecordBlock, type Screen } from \"./payload\";\nimport { AppErrorBoundary, loadApp, type AppError } from \"./code_app\";\nimport { AppCollections } from \"./app_modules\";\nimport { createViewStore, useViewStore, type ViewStore } from \"./store\";\n\n/**\n * The tallest the screen is in the conversation; past it, a collection\n * scrolls inside its own block, and anything else inside the screen. A\n * record's form and the confirmation of a save open over the frame, centred\n * in it: in a frame as tall as everything on the screen they would open where\n * the person is not looking.\n */\nconst INLINE_MAX_HEIGHT = 640;\n\n/** A write's plan waiting for the person's answer. */\nexport interface PendingPlan {\n plan: WritePlan;\n answer: (confirmed: boolean) => void;\n}\n\nexport interface McpScreenProps {\n bridge: McpAppBridge;\n screen: Screen;\n /** The host's context, as it changes. */\n hostContext: ViewStore<HostContext>;\n /** The write plan to confirm, as it changes. */\n pendingPlan: ViewStore<PendingPlan | undefined>;\n /** The last write the server refused, as it changes: shown to the person, once each. */\n writeFailure?: ViewStore<WriteFailure | undefined>;\n onAppError: (error: AppError) => void;\n}\n\n/**\n * What the embedded app's shell draws (`renderCms` of the embed host): the\n * one block the tool opened — a collection, a record, or an app the model\n * wrote — inside the providers the app's own `<RebaseShell>` set up, so its\n * collections, custom views, entity views, fields and actions are the ones\n * drawn.\n */\nexport function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, onAppError }: McpScreenProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n const context = useViewStore(hostContext);\n const pending = useViewStore(pendingPlan);\n const [refused, dismissRefused] = useRefusedWrite(writeFailure);\n const registry = useCollectionRegistryController();\n const fullscreen = context.displayMode === \"fullscreen\";\n const canExpand = !fullscreen && context.availableDisplayModes?.includes(\"fullscreen\") === true;\n const block = screen.blocks[0];\n\n // The host sizes the frame to the document, which it cannot measure\n // across the sandbox.\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n const measure = () => {\n const html = document.documentElement;\n const previous = html.style.height;\n html.style.height = \"max-content\";\n bridge.sizeChanged(Math.ceil(html.getBoundingClientRect().height));\n html.style.height = previous;\n };\n const observer = new ResizeObserver(measure);\n observer.observe(root);\n measure();\n return () => observer.disconnect();\n }, [bridge]);\n\n const collectionOf = (name: string): AdminCollection | undefined => registry.getCollection(name);\n const heading = screen.title ?? (block.type === \"app\" ? undefined : blockTitle(block, collectionOf(block.collection)));\n\n let body: React.ReactNode;\n if (!registry.initialised && !registry.collections?.length) {\n body = <CircularProgress size=\"smallest\"/>;\n } else if (block.type === \"app\") {\n body = <AppView block={block} onError={onAppError}/>;\n } else {\n const collection = collectionOf(block.collection);\n body = !collection\n ? <Alert color=\"error\" size=\"small\">The collection &quot;{block.collection}&quot; is not in this view.</Alert>\n : block.type === \"collection\"\n ? <CollectionView block={block} collection={collection}/>\n : <RecordView block={block} collection={collection}/>;\n }\n\n return (\n <div ref={rootRef}\n className={cls(\"flex flex-col gap-4 p-4 w-full min-w-0 bg-surface-sheet overflow-y-auto\", fullscreen && \"h-screen\")}\n style={fullscreen ? undefined : { maxHeight: INLINE_MAX_HEIGHT }}>\n {(heading || canExpand) && (\n <div className=\"flex items-center justify-between gap-3 min-h-8\">\n <Typography variant=\"subtitle2\" noWrap>{heading}</Typography>\n {canExpand && (\n <Tooltip title=\"Expand\">\n <IconButton\n size=\"small\"\n aria-label=\"Expand\"\n onClick={() => void bridge.requestDisplayMode(\"fullscreen\").catch(() => undefined)}\n >\n <Maximize2Icon size={iconSize.smallest}/>\n </IconButton>\n </Tooltip>\n )}\n </div>\n )}\n {refused && (\n // Sticky: the inline frame scrolls inside, and the button that\n // wrote may be far below its top.\n <Alert color=\"error\" size=\"small\" outerClassName=\"sticky top-0 z-10\" onDismiss={dismissRefused}>\n {`Could not ${describeFailedWrite(refused)}: ${refused.message}`}\n </Alert>\n )}\n {body}\n <Dialog open={pending !== undefined} onOpenChange={open => !open && pending?.answer(false)} maxWidth=\"sm\">\n <DialogTitle variant=\"subtitle1\">Confirm this change</DialogTitle>\n <DialogContent className=\"flex flex-col gap-2\">\n <Typography variant=\"body2\">{pending?.plan.summary}</Typography>\n {pending?.plan.effects?.map(effect => (\n <Typography key={effect} variant=\"body2\" color=\"secondary\">{effect}</Typography>\n ))}\n {pending?.plan.reversible && (\n <Typography variant=\"caption\" color=\"secondary\">Undo: {pending.plan.reversible}</Typography>\n )}\n </DialogContent>\n <DialogActions>\n <Button variant=\"text\" color=\"neutral\" onClick={() => pending?.answer(false)}>Cancel</Button>\n <Button variant=\"filled\" color=\"primary\" onClick={() => pending?.answer(true)}>Save</Button>\n </DialogActions>\n </Dialog>\n </div>\n );\n}\n\nfunction blockTitle(block: CollectionBlock | RecordBlock, collection: AdminCollection | undefined): string {\n if (block.type === \"record\") {\n const name = collection?.singularName ?? collection?.name ?? block.collection;\n return block.id === undefined ? `New ${name.toLowerCase()}` : name;\n }\n return collection?.name ?? block.collection;\n}\n\n/**\n * show_collection: the admin panel's collection view, where a row opens its\n * form over the screen. It sizes to its rows, up to what the screen leaves\n * it — inline, the screen's height cap; full screen, the window — and then\n * scrolls inside.\n */\nfunction CollectionView({ block, collection }: {\n block: CollectionBlock;\n collection: AdminCollection;\n}) {\n const overrides = useMemo<Partial<AdminCollection>>(() => {\n // The model's filter, as one the person can clear.\n const where = filterOf(block.where);\n return {\n ...(where && { defaultFilter: where }),\n ...(block.limit !== undefined && { pagination: block.limit })\n };\n }, [block.where, block.limit]);\n const sort = orderOf(block.orderBy);\n\n return (\n <CollectionPanel\n collection={collection.slug}\n title={false}\n className=\"flex-1 rounded-xl overflow-hidden\"\n {...(block.view && { viewMode: block.view })}\n {...(sort && { orderBy: sort })}\n collectionOverrides={overrides}\n />\n );\n}\n\n/** show_record: the admin panel's form, for a row or a new one. */\nfunction RecordView({ block, collection }: { block: RecordBlock; collection: AdminCollection }) {\n // A new row's form becomes that row's once it is saved.\n const [created, setCreated] = useState<string | number>();\n const id = block.id ?? created;\n return (\n <Card className=\"min-w-0 overflow-hidden\">\n <RecordForm\n key={String(id ?? \"new\")}\n collection={collection}\n id={id}\n {...(id === undefined && block.values && { defaultValues: block.values })}\n onSaved={params => {\n if (id === undefined) setCreated(params.id);\n }}\n />\n </Card>\n );\n}\n\n/**\n * show_app: the app the model wrote, held to the collections it was opened\n * with, and its failure shown in its place.\n */\nfunction AppView({ block, onError }: {\n block: AppBlock;\n onError: (error: AppError) => void;\n}) {\n const loaded = useMemo(() => loadApp(block.code), [block.code]);\n\n // A module that failed as it loaded is told once.\n useEffect(() => {\n if (loaded.error) onError(loaded.error);\n }, [loaded, onError]);\n\n const failure = (error: AppError) => (\n <Alert color=\"error\" size=\"small\">\n The app failed{error.line ? ` at line ${error.line}` : \"\"}: {error.message}\n </Alert>\n );\n if (!loaded.Component) return failure(loaded.error ?? { message: \"The app did not load.\" });\n const { Component } = loaded;\n return (\n <AppErrorBoundary lineOffset={loaded.lineOffset} onError={onError} fallback={failure}>\n <AppCollections names={block.collections}>\n <Component/>\n </AppCollections>\n </AppErrorBoundary>\n );\n}\n\n/**\n * The last write the server refused, until the person dismisses it: an app's\n * code can drop the rejection, and a button the app drew shows nothing of its\n * own (the admin's own controls show theirs). Shown in the screen, not as a\n * snackbar, which the sandboxed frame left off its edge.\n */\nfunction useRefusedWrite(store: ViewStore<WriteFailure | undefined> | undefined): [WriteFailure | undefined, () => void] {\n const failure = useViewStore(store ?? NO_FAILURES);\n const [dismissed, setDismissed] = useState<WriteFailure | undefined>(undefined);\n const dismiss = useCallback(() => setDismissed(failure), [failure]);\n return [failure !== dismissed ? failure : undefined, dismiss];\n}\n\nconst NO_FAILURES = createViewStore<WriteFailure | undefined>(undefined);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,IAAM,oBAAoB;;;;;;;;AA2B1B,SAAgB,UAAU,EAAE,QAAQ,QAAQ,aAAa,aAAa,cAAc,cAA8B;CAC9G,MAAM,UAAU,OAAuB,IAAI;CAC3C,MAAM,UAAU,aAAa,WAAW;CACxC,MAAM,UAAU,aAAa,WAAW;CACxC,MAAM,CAAC,SAAS,kBAAkB,gBAAgB,YAAY;CAC9D,MAAM,WAAW,gCAAgC;CACjD,MAAM,aAAa,QAAQ,gBAAgB;CAC3C,MAAM,YAAY,CAAC,cAAc,QAAQ,uBAAuB,SAAS,YAAY,MAAM;CAC3F,MAAM,QAAQ,OAAO,OAAO;CAI5B,gBAAgB;EACZ,MAAM,OAAO,QAAQ;EACrB,IAAI,CAAC,MAAM;EACX,MAAM,gBAAgB;GAClB,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AAC,OAAO,WAAW,OAAO,QAAQ,OAAO,SAAS,EAAE,SAAS,wBAAwB,CAAC;CAC1F,MAAM,EAAE,cAAc;CACtB,OACI,oBAAC,kBAAD;EAAkB,YAAY,OAAO;EAAqB;EAAS,UAAU;YACzE,oBAAC,gBAAD;GAAgB,OAAO,MAAM;aACzB,oBAAC,WAAD,CAAW,CAAA;EACC,CAAA;CACF,CAAA;AAE1B;;;;;;;AAQA,SAAS,gBAAgB,OAAgG;CACrH,MAAM,UAAU,aAAa,SAAS,WAAW;CACjD,MAAM,CAAC,WAAW,gBAAgB,SAAmC,KAAA,CAAS;CAC9E,MAAM,UAAU,kBAAkB,aAAa,OAAO,GAAG,CAAC,OAAO,CAAC;CAClE,OAAO,CAAC,YAAY,YAAY,UAAU,KAAA,GAAW,OAAO;AAChE;AAEA,IAAM,cAAc,gBAA0C,KAAA,CAAS"}
@@ -69,8 +69,18 @@ export interface ViewChange {
69
69
  action: "created" | "updated" | "deleted";
70
70
  collection: string;
71
71
  id: string;
72
+ /** The row as the person knows it — its title — where the driver can tell; see {@link ToolDriverOptions.rowLabel}. */
73
+ label?: string;
72
74
  fields?: string[];
73
75
  }
76
+ /** A write the server refused: what was tried, on which row, and the server's words. */
77
+ export interface WriteFailure {
78
+ action: "create" | "update" | "delete";
79
+ collection: string;
80
+ /** The row, as {@link ToolDriverOptions.rowLabel} names it; absent for a create. */
81
+ row?: string;
82
+ message: string;
83
+ }
74
84
  /** The calls the driver makes: the bridge's `callTool`, as a function so a test can stand in for the host. */
75
85
  export type CallTool = (name: string, args: Record<string, unknown>) => Promise<ToolResult>;
76
86
  /**
@@ -105,6 +115,19 @@ export interface ToolDriverOptions {
105
115
  seeds?: SeedPage[];
106
116
  /** Every change made through this driver, in order, after each one. */
107
117
  onChange?: (changes: readonly ViewChange[]) => void;
118
+ /**
119
+ * How a row is named to the person — in a write's confirmation, in a
120
+ * refusal — given the row where the driver has read it: its title, say.
121
+ * Without it, or where it says nothing, `row <id>`.
122
+ */
123
+ rowLabel?: (collection: string, id: string, row: Record<string, unknown> | undefined) => string | undefined;
124
+ /**
125
+ * A write through {@link ToolDriver.confirmingDriver} that the server
126
+ * refused. App code can drop the rejection it gets; this is how the
127
+ * person and the model still learn of it. A write the person declined is
128
+ * not one.
129
+ */
130
+ onWriteFailed?: (failure: WriteFailure) => void;
108
131
  /**
109
132
  * The collection a name the tools take names — its slug or its data
110
133
  * path: an app names collections as the model wrote them, the admin
@@ -132,4 +155,6 @@ export declare class SaveCancelledError extends Error {
132
155
  export declare function createToolDriver(options: ToolDriverOptions): ToolDriver;
133
156
  export declare function textOf(result: ToolResult): string | undefined;
134
157
  /** What the model is told the person changed here, sent with their next message. */
158
+ /** "update ORD-2026-0081 in orders", "create a row in orders". */
159
+ export declare function describeFailedWrite(failure: WriteFailure): string;
135
160
  export declare function describeChanges(changes: readonly ViewChange[]): string;
@@ -93,6 +93,7 @@ function createToolDriver(options) {
93
93
  const seededAt = Date.now();
94
94
  const changes = [];
95
95
  const rows = /* @__PURE__ */ new Map();
96
+ const counting = /* @__PURE__ */ new Map();
96
97
  const queued = /* @__PURE__ */ new Map();
97
98
  let readsQueued = false;
98
99
  const call = async (action, args) => {
@@ -123,6 +124,7 @@ function createToolDriver(options) {
123
124
  */
124
125
  const changed = (change) => {
125
126
  seeds = [];
127
+ counting.clear();
126
128
  const key = canonical(change.collection);
127
129
  for (const row of rows.keys()) if (canonical(row.slice(0, row.lastIndexOf("/"))) === key) rows.delete(row);
128
130
  changes.push(change);
@@ -304,8 +306,8 @@ function createToolDriver(options) {
304
306
  const where = options.filter ? wireFilter(options.filter, void 0) : void 0;
305
307
  const answer = await call(actions.aggregate, {
306
308
  collection: collectionArg(path),
307
- select: options.aggregates.map((aggregate) => `${aggregate.fn}(${aggregate.field ?? ""})`),
308
- ...options.groupBy && options.groupBy.length > 0 && { groupBy: options.groupBy },
309
+ select: options.aggregates.map((aggregate) => aggregate.fn === "percentile" ? `${aggregate.fn}(${aggregate.field ?? ""},${aggregate.p})` : `${aggregate.fn}(${aggregate.field ?? ""})`),
310
+ ...options.groupBy && options.groupBy.length > 0 && { groupBy: options.groupBy.map((group) => typeof group === "string" ? group : `${group.transform}(${group.field})`) },
309
311
  ...where && Object.keys(where).length > 0 && { where },
310
312
  ...options.searchString && { searchString: options.searchString },
311
313
  ...options.orderBy && options.orderBy.length > 0 && { orderBy: options.orderBy },
@@ -333,24 +335,30 @@ function createToolDriver(options) {
333
335
  });
334
336
  const row = isRecord(saved) ? saved : { ...data };
335
337
  const id = String(row.id ?? props.id ?? "");
338
+ const label = options.rowLabel?.(collection, id, row);
336
339
  changed({
337
340
  action: creating ? "created" : "updated",
338
341
  collection,
339
342
  id,
343
+ ...label && { label },
340
344
  fields: Object.keys(data)
341
345
  });
342
346
  return row;
343
347
  },
344
348
  async delete(props) {
345
349
  const collection = collectionArg(props.row.path);
350
+ const id = String(props.row.id);
351
+ const cached = await rows.get(`${collection}/${id}`)?.read.catch(() => void 0);
352
+ const label = options.rowLabel?.(collection, id, cached ?? void 0);
346
353
  await write(actions.delete, {
347
354
  collection,
348
- id: String(props.row.id)
355
+ id
349
356
  });
350
357
  changed({
351
358
  action: "deleted",
352
359
  collection,
353
- id: String(props.row.id)
360
+ id,
361
+ ...label && { label }
354
362
  });
355
363
  },
356
364
  async count(props) {
@@ -362,12 +370,20 @@ function createToolDriver(options) {
362
370
  ]);
363
371
  const seeded = takeSeedCount(collection, args);
364
372
  if (seeded !== void 0) return seeded;
365
- const answer = await call(actions.count, {
373
+ const key = `${canonical(collection)}|${readKey(args)}`;
374
+ const inFlight = counting.get(key);
375
+ if (inFlight) return inFlight;
376
+ const counted = call(actions.count, {
366
377
  collection,
367
378
  ...args
379
+ }).then((answer) => {
380
+ if (isRecord(answer) && typeof answer.count === "number") return answer.count;
381
+ throw new Error("The count returned no number.");
382
+ }).finally(() => {
383
+ if (counting.get(key) === counted) counting.delete(key);
368
384
  });
369
- if (isRecord(answer) && typeof answer.count === "number") return answer.count;
370
- throw new Error("The count returned no number.");
385
+ counting.set(key, counted);
386
+ return counted;
371
387
  },
372
388
  async checkUniqueField() {
373
389
  return true;
@@ -377,6 +393,23 @@ function createToolDriver(options) {
377
393
  const confirmFirst = async (action, plan) => {
378
394
  if (!action.plans && !await confirm(plan)) throw new SaveCancelledError();
379
395
  };
396
+ /** A row as the person knows it: its title where it has been read, else `row <id>`. */
397
+ const labelOf = async (collection, id) => {
398
+ const row = await rows.get(`${collection}/${id}`)?.read.catch(() => void 0);
399
+ return options.rowLabel?.(collection, id, row ?? void 0) || `row ${id}`;
400
+ };
401
+ /** A refused write, told; the rejection still reaches the caller. */
402
+ const reported = async (failure, write) => {
403
+ try {
404
+ return await write();
405
+ } catch (error) {
406
+ if (!(error instanceof SaveCancelledError)) options.onWriteFailed?.({
407
+ ...failure,
408
+ message: error instanceof Error ? error.message : String(error)
409
+ });
410
+ throw error;
411
+ }
412
+ };
380
413
  return {
381
414
  driver,
382
415
  confirmingDriver: {
@@ -384,13 +417,23 @@ function createToolDriver(options) {
384
417
  async save(props) {
385
418
  const collection = collectionArg(props.path);
386
419
  const creating = props.status !== "existing";
387
- await confirmFirst(creating ? actions.create : actions.update, creating ? { summary: `Create a row in ${collection}.` } : { summary: `Change ${Object.keys(wireValues(props, collection)).join(", ")} on row ${String(props.id)} of ${collection}.` });
388
- return driver.save(props);
420
+ const row = creating ? void 0 : await labelOf(collection, String(props.id));
421
+ await confirmFirst(creating ? actions.create : actions.update, creating ? { summary: `Create a row in ${collection}.` } : { summary: `Change ${Object.keys(wireValues(props, collection)).join(", ")} on ${row} of ${collection}.` });
422
+ return reported({
423
+ action: creating ? "create" : "update",
424
+ collection,
425
+ ...row && { row }
426
+ }, () => driver.save(props));
389
427
  },
390
428
  async delete(props) {
391
429
  const collection = collectionArg(props.row.path);
392
- await confirmFirst(actions.delete, { summary: `Delete row ${String(props.row.id)} of ${collection}.` });
393
- return driver.delete(props);
430
+ const row = await labelOf(collection, String(props.row.id));
431
+ await confirmFirst(actions.delete, { summary: `Delete ${row} of ${collection}.` });
432
+ return reported({
433
+ action: "delete",
434
+ collection,
435
+ row
436
+ }, () => driver.delete(props));
394
437
  }
395
438
  }
396
439
  };
@@ -518,10 +561,15 @@ function textOf(result) {
518
561
  return result.content?.find((block) => typeof block.text === "string")?.text;
519
562
  }
520
563
  /** What the model is told the person changed here, sent with their next message. */
564
+ /** "update ORD-2026-0081 in orders", "create a row in orders". */
565
+ function describeFailedWrite(failure) {
566
+ return failure.action === "create" ? `create a row in ${failure.collection}` : `${failure.action} ${failure.row ?? "a row"} in ${failure.collection}`;
567
+ }
521
568
  function describeChanges(changes) {
522
- return `In the Rebase view, the user saved these changes: ${changes.map((change) => change.action === "updated" ? `updated ${change.fields?.join(", ") || "fields"} on row ${change.id} of ${change.collection}` : `${change.action} row ${change.id} of ${change.collection}`).join("; ")}. Rows you read before them may be out of date.`;
569
+ const rowOf = (change) => change.label ? `${change.label} (row ${change.id})` : `row ${change.id}`;
570
+ return `In the Rebase view, the user saved these changes: ${changes.map((change) => change.action === "updated" ? `updated ${change.fields?.join(", ") || "fields"} on ${rowOf(change)} of ${change.collection}` : `${change.action} ${rowOf(change)} of ${change.collection}`).join("; ")}. Rows you read before them may be out of date.`;
523
571
  }
524
572
  //#endregion
525
- export { DEFAULT_ACTIONS, SaveCancelledError, createToolDriver, describeChanges, textOf };
573
+ export { DEFAULT_ACTIONS, SaveCancelledError, createToolDriver, describeChanges, describeFailedWrite, textOf };
526
574
 
527
575
  //# sourceMappingURL=tool_driver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool_driver.js","names":[],"sources":["../../src/mcp_view/tool_driver.ts"],"sourcesContent":["/**\n * The admin panel's data layer, over the MCP tools of the server that served\n * this view.\n *\n * `<Rebase>` reads and writes through a `DataDriver`; this one turns each read\n * and write into a `tools/call` the host relays to the server — the same\n * tools, the same person, the same RLS as the model's own calls. Rows go and\n * come in the REST shape those tools speak (dates as ISO text, a belongsTo as\n * its foreign key); `<Rebase>` turns them into the admin panel's view model\n * and back, as it does for any driver.\n *\n * An app's row hooks (`useRows`, `useAggregate`, …) read the same driver\n * through the flat data layer (`buildRebaseData`), which keeps the wire's\n * rows and takes aggregates from `restFetchService`: here, the aggregate tool.\n *\n * A write the server answers with a plan (the hosted connector's two-step\n * `write`) is held: the person is shown the plan and the write is sent again\n * with its token only if they confirm. The row hooks write through\n * `confirmingDriver`, which asks the person before any other write too: code\n * can write without a click, while a save made with the admin's own controls\n * was the person's click. Either way the admin panel sees one save that took\n * a moment longer, or one that failed with \"Not saved\".\n *\n * The driver does not subscribe (no `listenCollection`/`listenOne`): every\n * write it makes comes through `<Rebase>`'s data layers, which say so on the\n * `<Rebase>`'s change signal, and each view of the collection reads again on\n * it. It learns of no change it did not make — the host relays no other\n * tool's calls — so it has nothing to announce either\n * (`subscribeToExternalChanges`).\n */\nimport {\n DEFAULT_DATA_SOURCE_KEY,\n type CollectionConfig,\n type DataDriver,\n type DeleteProps,\n type FetchCollectionProps,\n type FetchOneProps,\n type RestFetchService,\n type SaveProps\n} from \"@rebasepro/types\";\nimport {\n buildCompositeId,\n fieldKeyForColumn,\n getDeclaredPrimaryKeys,\n resolveCollectionRelations,\n resolvePrimaryKeys,\n type PrimaryKeyInfo\n} from \"@rebasepro/common\";\nimport { toWireRow } from \"@rebasepro/app\";\nimport { isRecord, type ToolResult } from \"./bridge\";\n\n/** A tool the view calls, and the arguments it always sends to it. */\nexport interface ToolAction {\n tool: string;\n arguments: Record<string, unknown>;\n /**\n * The tool answers a plan before it changes anything (the hosted\n * connector's `write`), so the person confirms there. Not set, a change\n * the row hooks make is confirmed in the view before it is sent.\n */\n plans?: boolean;\n}\n\n/**\n * The tools the view reads and writes with. The server that served it may\n * name its own (`actions` in a show_* result): the hosted Rebase connector\n * reads with `query` and writes with `write`, each with the project. Absent,\n * they are an app's own `/mcp` tools.\n */\nexport interface ViewActions {\n page: ToolAction;\n get: ToolAction;\n count: ToolAction;\n create: ToolAction;\n update: ToolAction;\n delete: ToolAction;\n /** `count`/`sum`/`avg`/`min`/`max` over the matching rows, grouped or not, as REST's `select` and `groupBy`. */\n aggregate: ToolAction;\n}\n\nexport const DEFAULT_ACTIONS: ViewActions = {\n page: { tool: \"query_collection\", arguments: {} },\n get: { tool: \"get_document\", arguments: {} },\n count: { tool: \"count_documents\", arguments: {} },\n create: { tool: \"create_document\", arguments: {} },\n update: { tool: \"update_document\", arguments: {} },\n delete: { tool: \"delete_document\", arguments: {} },\n aggregate: { tool: \"aggregate_documents\", arguments: {} }\n};\n\n/** What a write's first call answered instead of running: what it will do, for the person to confirm. */\nexport interface WritePlan {\n summary: string;\n effects?: string[];\n reversible?: string;\n}\n\n/** One change the person made here, as the model is told about it. */\nexport interface ViewChange {\n action: \"created\" | \"updated\" | \"deleted\";\n collection: string;\n id: string;\n fields?: string[];\n}\n\n/** The calls the driver makes: the bridge's `callTool`, as a function so a test can stand in for the host. */\nexport type CallTool = (name: string, args: Record<string, unknown>) => Promise<ToolResult>;\n\n/**\n * A page a result already carries: the rows the server read — for the model\n * (show_collection), or ahead of an app's first render (show_app) — and the\n * arguments it read them with.\n */\nexport interface SeedPage {\n collection: string;\n /** As the read tools take them: `where`, `orderBy`, `searchString`, `limit`, `offset`. */\n args: Record<string, unknown>;\n rows: Record<string, unknown>[];\n /** How many rows the read's filter matches, where the server counted them: answers that count, once. */\n total?: number;\n}\n\nexport interface ToolDriverOptions {\n callTool: CallTool;\n actions: ViewActions;\n /** Show the person a write's plan; true when they confirm it. */\n confirm: (plan: WritePlan) => Promise<boolean>;\n /**\n * A page already read: served once in place of the read tool's call, to\n * a read asking for exactly it, and dropped by any write or once it is\n * older than the driver's read cache keeps a row.\n */\n seed?: SeedPage;\n /**\n * Pages read ahead of an app's first render, one per collection it\n * names: each served once as {@link seed} is, its rows answering a read\n * by key, and its `total` the count of the collection's rows.\n */\n seeds?: SeedPage[];\n /** Every change made through this driver, in order, after each one. */\n onChange?: (changes: readonly ViewChange[]) => void;\n /**\n * The collection a name the tools take names — its slug or its data\n * path: an app names collections as the model wrote them, the admin\n * panel by slug. A write's values are sent by its config (a date-only\n * column as its day, a belongsTo under its foreign key), and drop what\n * was read of it under either name.\n */\n collection?: (name: string) => CollectionConfig | undefined;\n}\n\ntype Row = Record<string, unknown>;\n\nexport interface ToolDriver {\n /** For `<Rebase>`: the admin panel's reads and saves. */\n driver: DataDriver;\n /**\n * The same driver, asking the person before each write the tool does not\n * plan itself: for the row hooks (`useRowWrites`), since code can write\n * without a click. A declined write rejects with {@link SaveCancelledError}\n * and nothing is sent.\n */\n confirmingDriver: DataDriver;\n}\n\n/** A row asked for by key, waiting on its batch's page. */\ninterface QueuedRead {\n resolve: (row: Record<string, unknown> | undefined) => void;\n reject: (error: unknown) => void;\n}\n\n/** A save the person declined at the plan. The form shows it as the save's error. */\nexport class SaveCancelledError extends Error {\n constructor() {\n super(\"Not saved: the change was not confirmed.\");\n this.name = \"SaveCancelledError\";\n }\n}\n\n/** The ceiling every read tool takes for `limit` (`MAX_LIST_LIMIT`). */\nconst MAX_LIMIT = 1000;\n\n/**\n * How long a row read, or the seeded page, answers in place of the server.\n * Long enough for one render's relation previews and concurrent reads to\n * share a call, and for a row the person picks off the page they are looking\n * at to open with none; short enough that a row the model changed with its\n * own tools — which takes the person's message and the model's turn — is\n * read afresh when it is refreshed or opened again.\n */\nconst READ_TTL_MS = 30_000;\n\nexport function createToolDriver(options: ToolDriverOptions): ToolDriver {\n const { callTool, actions, confirm, onChange } = options;\n const configOf = options.collection ?? (() => undefined);\n const canonical = (collection: string) => configOf(collection)?.slug ?? collection;\n // Each seed answers its page once and its count once.\n let seeds = [...(options.seed ? [options.seed] : []), ...(options.seeds ?? [])]\n .map(page => ({ page, pageTaken: false, countTaken: page.total === undefined }));\n const seededAt = Date.now();\n const changes: ViewChange[] = [];\n // A table draws each row's relations by reading the related row, so a\n // page of orders asks for the same customer many times over. Each read is\n // a round trip through the host: one per row is shared until a write, or\n // until it is older than `READ_TTL_MS`, since the model can change a row\n // with its own tools and this driver never hears of it.\n const rows = new Map<string, { read: Promise<Record<string, unknown> | undefined>; at: number }>();\n // The rows asked for by key in this tick and not yet read, by collection:\n // each collection's are read by one page call (`readQueued`).\n const queued = new Map<string, { key: PrimaryKeyInfo; reads: Map<string, QueuedRead> }>();\n let readsQueued = false;\n\n const call = async (action: ToolAction, args: Record<string, unknown>): Promise<unknown> => {\n const result = await callTool(action.tool, { ...action.arguments, ...args });\n if (result.isError) throw new Error(textOf(result) ?? \"The server refused this call.\");\n return result.structuredContent ?? parseText(result);\n };\n\n /** A write, through its plan where the server asks for one. */\n const write = async (action: ToolAction, args: Record<string, unknown>): Promise<unknown> => {\n const first = await call(action, args);\n const plan = planOf(first);\n if (!plan) return first;\n if (!await confirm(plan.plan)) throw new SaveCancelledError();\n const second = await call(action, { ...args, confirm: plan.token });\n if (planOf(second)) throw new Error(\"The server asked for confirmation again; nothing was saved.\");\n return second;\n };\n\n /**\n * What a write changed: what was read of its collection is dropped (the\n * seeded page, the rows), and the model is told. The views read again on\n * `<Rebase>`'s change signal, which the write's data layer emits.\n */\n const changed = (change: ViewChange) => {\n // Every seed, not only this collection's: a page carries the related\n // rows it includes, and a write to those changes it too.\n seeds = [];\n const key = canonical(change.collection);\n for (const row of rows.keys()) if (canonical(row.slice(0, row.lastIndexOf(\"/\"))) === key) rows.delete(row);\n changes.push(change);\n onChange?.(changes);\n };\n\n /** A save's values as the write tools take them, by the collection's config where it is known. */\n const wireValues = (props: SaveProps, collection: string): Record<string, unknown> => {\n const defined = Object.fromEntries(Object.entries(props.values).filter(([, value]) => value !== undefined));\n return toWireRow(defined, props.collection ?? configOf(collection) ?? NO_CONFIG, { included: false });\n };\n\n /**\n * A page's rows into the row cache, keyed as {@link fetchOne} asks for\n * them: the row a view lists is the row its record opens with, and a row\n * an app was just shown opens with no call of its own. By the\n * collection's key where its config is known, by `id` otherwise; a write\n * to the collection drops them, as it drops every row read. Not a page\n * that lists deleted rows: `get` answers none for those.\n */\n const remember = (collection: string, page: Row[], config?: FetchCollectionProps[\"collection\"]) => {\n const keys = config ? getDeclaredPrimaryKeys(config) : [];\n for (const row of page) {\n const id = keys.length > 1 ? buildCompositeId(row, keys) : row[keys[0]?.fieldName ?? \"id\"];\n if (typeof id !== \"string\" && typeof id !== \"number\") continue;\n rows.set(`${collection}/${String(id)}`, { read: Promise.resolve(row), at: Date.now() });\n }\n };\n // A seeded row opens with no call of its own — a record form, a detail,\n // a relation's title — even where no read asks for the page it came in.\n for (const { page } of seeds) remember(page.collection, page.rows, configOf(page.collection));\n\n /**\n * The seeded page, once, to a read asking for exactly it — or for more\n * of the same rows where the seed already holds every one: a view asks\n * one row past its page to learn whether there are more, and a page\n * shorter than its limit has answered that.\n */\n const takeSeed = (collection: string, args: Record<string, unknown>): Row[] | undefined => {\n if (Date.now() - seededAt > READ_TTL_MS) seeds = [];\n const seed = seeds.find(candidate => !candidate.pageTaken\n && canonical(candidate.page.collection) === canonical(collection) && readKey(candidate.page.args) === readKey(args));\n if (!seed) return undefined;\n const seedLimit = limitOf(seed.page.args);\n const readLimit = limitOf(args);\n const complete = seedLimit === undefined || seed.page.rows.length < seedLimit;\n const answers = readLimit === seedLimit || (complete && (readLimit === undefined || seedLimit === undefined || readLimit > seedLimit));\n if (!answers) return undefined;\n seed.pageTaken = true;\n return seed.page.rows;\n };\n\n /** The count a seed's `total` answers — the collection's rows, unfiltered — once. */\n const takeSeedCount = (collection: string, args: Record<string, unknown>): number | undefined => {\n if (Date.now() - seededAt > READ_TTL_MS) seeds = [];\n if (args.where !== undefined || args.searchString !== undefined || args.deleted !== undefined) return undefined;\n const seed = seeds.find(candidate => !candidate.countTaken && canonical(candidate.page.collection) === canonical(collection)\n && candidate.page.args.where === undefined && candidate.page.args.searchString === undefined);\n if (!seed || seed.page.total === undefined) return undefined;\n seed.countTaken = true;\n return seed.page.total;\n };\n\n const fetchCollection = async (props: FetchCollectionProps): Promise<Record<string, unknown>[]> => {\n const collection = collectionArg(props.path);\n const args = readArgs(props);\n let found = takeSeed(collection, args);\n if (!found) {\n const page = await call(actions.page, { collection, ...args });\n if (!isRecord(page) || !Array.isArray(page.data)) throw new Error(\"The read returned no rows.\");\n found = page.data.filter(isRecord);\n }\n if (!props.withDeleted) remember(collection, found, props.collection);\n return found;\n };\n\n /**\n * The rows asked for by key in one tick, read together: one page call per\n * collection, `where <key> in [ids]`, however many relation previews a\n * render draws — as the admin's `useBatchedFetch` reads them, chunked at\n * the read tools' ceiling. A row the page does not carry is absent or not\n * visible to the person: one answer for both, as the get tool gives.\n */\n const readQueued = () => {\n readsQueued = false;\n const batches = [...queued];\n queued.clear();\n for (const [collection, { key, reads }] of batches) {\n const ids = [...reads.keys()];\n for (let i = 0; i < ids.length; i += MAX_LIMIT) {\n const chunk = ids.slice(i, i + MAX_LIMIT);\n const values = chunk.map(id => key.type === \"number\" && id.trim() !== \"\" && !Number.isNaN(Number(id)) ? Number(id) : id);\n call(actions.page, { collection, where: { [key.fieldName]: [\"in\", values] }, limit: chunk.length })\n .then(page => {\n if (!isRecord(page) || !Array.isArray(page.data)) throw new Error(\"The read returned no rows.\");\n const byId = new Map(page.data.filter(isRecord).map(row => [String(row[key.fieldName]), row]));\n for (const id of chunk) reads.get(id)?.resolve(byId.get(id));\n })\n .catch((error: unknown) => {\n for (const id of chunk) reads.get(id)?.reject(error);\n });\n }\n }\n };\n\n const readByKey = (collection: string, id: string, key: PrimaryKeyInfo): Promise<Row | undefined> =>\n new Promise((resolve, reject) => {\n let batch = queued.get(collection);\n if (!batch) {\n batch = { key, reads: new Map() };\n queued.set(collection, batch);\n }\n batch.reads.set(id, { resolve, reject });\n if (!readsQueued) {\n readsQueued = true;\n queueMicrotask(readQueued);\n }\n });\n\n /** A row of a collection with no single key column to put an `in` on, or none known: by the get tool. */\n const readById = (collection: string, id: string): Promise<Row | undefined> =>\n call(actions.get, { collection, id })\n .then(row => isRecord(row) ? row : undefined)\n .catch((error: unknown) => {\n // One answer for \"absent\" and \"not visible to you\", by design.\n if (error instanceof Error && /^No row with id/.test(error.message)) return undefined;\n throw error;\n });\n\n /**\n * A row: by the page tool wherever its collection has one key column — a\n * lone row as well as a crowd of previews. One rule, so a row is read the\n * same way however many are drawn beside it; and the page tool is the one\n * every server names (a hosted result may name no `get`), whose answer\n * for an absent row is an empty page rather than an error told apart by\n * its text.\n */\n const fetchOne = (props: FetchOneProps): Promise<Record<string, unknown> | undefined> => {\n const collection = collectionArg(props.path);\n const key = `${collection}/${String(props.id)}`;\n const cached = rows.get(key);\n if (cached && Date.now() - cached.at <= READ_TTL_MS) return cached.read;\n const config = props.collection ?? configOf(collection);\n const keys = config ? resolvePrimaryKeys(config) : [];\n const read: Promise<Row | undefined> = (keys.length === 1\n ? readByKey(collection, String(props.id), keys[0])\n : readById(collection, String(props.id)))\n .catch((error: unknown) => {\n if (rows.get(key)?.read === read) rows.delete(key);\n throw error;\n });\n rows.set(key, { read, at: Date.now() });\n return read;\n };\n\n /**\n * The flat data layer's reads: the same tools and the same rows as the\n * admin panel's, and the aggregate tool.\n */\n const restFetchService: RestFetchService = {\n fetchCollectionForRest(path, options = {}) {\n refuseUnsupported(options);\n return fetchCollection({\n path,\n ...(options.filter && { filter: options.filter }),\n ...(options.orderBy !== undefined && { orderBy: options.orderBy }),\n ...(options.order && { order: options.order }),\n ...(options.limit !== undefined && { limit: options.limit }),\n ...(options.offset !== undefined && { offset: options.offset }),\n ...(options.searchString && { searchString: options.searchString }),\n ...(options.withDeleted !== undefined && { withDeleted: options.withDeleted })\n });\n },\n async fetchOneForRest(path, id) {\n return await fetchOne({ path, id }) ?? null;\n },\n async aggregate(path, options) {\n refuseUnsupported(options);\n const where = options.filter ? wireFilter(options.filter, undefined) : undefined;\n const answer = await call(actions.aggregate, {\n collection: collectionArg(path),\n select: options.aggregates.map(aggregate => `${aggregate.fn}(${aggregate.field ?? \"\"})`),\n ...(options.groupBy && options.groupBy.length > 0 && { groupBy: options.groupBy }),\n ...(where && Object.keys(where).length > 0 && { where }),\n ...(options.searchString && { searchString: options.searchString }),\n ...(options.orderBy && options.orderBy.length > 0 && { orderBy: options.orderBy }),\n ...(options.limit !== undefined && { limit: Math.min(options.limit, MAX_LIMIT) }),\n ...(options.offset && { offset: options.offset }),\n ...(options.withDeleted && { deleted: options.withDeleted === \"only\" ? \"only\" : \"include\" })\n });\n if (!isRecord(answer) || !Array.isArray(answer.data)) throw new Error(\"The aggregate returned no rows.\");\n return answer.data.filter(isRecord);\n }\n };\n\n const driver: DataDriver = {\n key: DEFAULT_DATA_SOURCE_KEY,\n initialised: true,\n\n fetchCollection,\n fetchOne,\n restFetchService,\n\n async save(props: SaveProps): Promise<Record<string, unknown>> {\n const collection = collectionArg(props.path);\n const data = wireValues(props, collection);\n const creating = props.status !== \"existing\";\n const action = creating ? actions.create : actions.update;\n const saved = creating\n ? await write(action, { collection, data, ...(props.id !== undefined && { id: String(props.id) }) })\n : await write(action, { collection, id: String(props.id), data });\n const row = isRecord(saved) ? saved : { ...data };\n const id = String(row.id ?? props.id ?? \"\");\n changed({ action: creating ? \"created\" : \"updated\", collection, id, fields: Object.keys(data) });\n return row;\n },\n\n async delete(props: DeleteProps): Promise<void> {\n const collection = collectionArg(props.row.path);\n await write(actions.delete, { collection, id: String(props.row.id) });\n changed({ action: \"deleted\", collection, id: String(props.row.id) });\n },\n\n async count(props: FetchCollectionProps): Promise<number> {\n const collection = collectionArg(props.path);\n const args = pickRead(readArgs(props), [\"where\", \"searchString\", \"deleted\"]);\n const seeded = takeSeedCount(collection, args);\n if (seeded !== undefined) return seeded;\n const answer = await call(actions.count, { collection, ...args });\n if (isRecord(answer) && typeof answer.count === \"number\") return answer.count;\n throw new Error(\"The count returned no number.\");\n },\n\n // The server checks a unique field when the row is written; a check\n // here would be one more round trip through the host for each keystroke.\n async checkUniqueField(): Promise<boolean> {\n return true;\n }\n };\n\n /** The person's yes before a write the tool does not plan; their no rejects, and nothing is sent. */\n const confirmFirst = async (action: ToolAction, plan: WritePlan): Promise<void> => {\n if (!action.plans && !await confirm(plan)) throw new SaveCancelledError();\n };\n\n const confirmingDriver: DataDriver = {\n ...driver,\n async save(props: SaveProps): Promise<Record<string, unknown>> {\n const collection = collectionArg(props.path);\n const creating = props.status !== \"existing\";\n await confirmFirst(creating ? actions.create : actions.update, creating\n ? { summary: `Create a row in ${collection}.` }\n : { summary: `Change ${Object.keys(wireValues(props, collection)).join(\", \")} on row ${String(props.id)} of ${collection}.` });\n return driver.save(props);\n },\n async delete(props: DeleteProps): Promise<void> {\n const collection = collectionArg(props.row.path);\n await confirmFirst(actions.delete, { summary: `Delete row ${String(props.row.id)} of ${collection}.` });\n return driver.delete(props);\n }\n };\n\n return { driver, confirmingDriver };\n}\n\n/**\n * The collection a driver path names. The views open top-level collections\n * only; a subcollection path has no tool to read it.\n */\nfunction collectionArg(path: string): string {\n if (path.includes(\"/\")) throw new Error(`\"${path}\" is a subcollection, which this view cannot open.`);\n return path;\n}\n\n/** A read's arguments, as the read tools take them. */\nfunction readArgs(props: FetchCollectionProps): Record<string, unknown> {\n const where = props.filter ? wireFilter(props.filter, props.collection) : undefined;\n const orderBy = wireOrderBy(props, props.collection);\n return {\n ...(where && Object.keys(where).length > 0 && { where }),\n ...(orderBy && { orderBy }),\n ...(props.searchString && { searchString: props.searchString }),\n ...(props.limit !== undefined && { limit: Math.min(props.limit, MAX_LIMIT) }),\n ...(props.offset && { offset: props.offset }),\n ...(props.withDeleted !== undefined && props.withDeleted !== false && {\n deleted: props.withDeleted === \"only\" ? \"only\" : \"include\"\n })\n };\n}\n\n/** What the read tools cannot express, refused rather than read wider than asked. */\nfunction refuseUnsupported(options: { logical?: unknown; vectorSearch?: unknown }): void {\n if (options.logical) throw new Error(\"This view's tools cannot filter by an or()/and() group.\");\n if (options.vectorSearch) throw new Error(\"This view's tools cannot run a vector search.\");\n}\n\n/**\n * Which rows a read asks for, as one comparable string: the same rows however\n * the read was written — a sort as `\"field:desc\"` or `[[\"field\", \"desc\"]]`, a\n * filter's fields in any order, no offset or offset 0. How many is\n * {@link limitOf}'s.\n */\nfunction readKey(args: Record<string, unknown>): string {\n const where = isRecord(args.where) ? args.where : {};\n return JSON.stringify([\n Object.keys(where).sort().map(key => [key, where[key]]),\n sortOf(args.orderBy),\n typeof args.searchString === \"string\" ? args.searchString : \"\",\n typeof args.offset === \"number\" ? args.offset : 0,\n typeof args.deleted === \"string\" ? args.deleted : null\n ]);\n}\n\nfunction limitOf(args: Record<string, unknown>): number | undefined {\n return typeof args.limit === \"number\" ? args.limit : undefined;\n}\n\nfunction sortOf(orderBy: unknown): unknown[] {\n if (typeof orderBy === \"string\" && orderBy !== \"\") {\n const [field, direction] = orderBy.split(\":\");\n return [[field, direction === \"desc\" ? \"desc\" : \"asc\"]];\n }\n if (!Array.isArray(orderBy) || orderBy.length === 0) return [];\n const entries: unknown[] = Array.isArray(orderBy[0]) ? orderBy : [orderBy];\n return entries.map(entry => Array.isArray(entry) ? [entry[0], entry[1] === \"desc\" ? \"desc\" : \"asc\"] : entry);\n}\n\nfunction pickRead(args: Record<string, unknown>, names: readonly string[]): Record<string, unknown> {\n return Object.fromEntries(Object.entries(args).filter(([name]) => names.includes(name)));\n}\n\n/**\n * The admin panel's filter as the read tools' `where`: a belongsTo is\n * filtered by its foreign key there, and a value is the wire's — a relation\n * its id, a date its ISO text.\n */\nfunction wireFilter(filter: Record<string, unknown>, collection: CollectionConfig | undefined): Record<string, unknown> {\n const keys = foreignKeys(collection);\n const where: Record<string, unknown> = {};\n for (const [key, condition] of Object.entries(filter)) {\n if (condition === undefined) continue;\n // A condition is `[op, value]`, each part converted as a row's value is.\n where[keys.get(key) ?? key] = toWireRow({ condition }, NO_CONFIG).condition;\n }\n return where;\n}\n\n/** No properties, so {@link toWireRow} converts each value by what it is: a relation to its id, a date to ISO text. */\nconst NO_CONFIG: CollectionConfig = { slug: \"\", name: \"\", properties: {} };\n\nfunction wireOrderBy(props: FetchCollectionProps, collection: CollectionConfig | undefined): string | unknown[] | undefined {\n const keys = foreignKeys(collection);\n if (typeof props.orderBy === \"string\") {\n const field = keys.get(props.orderBy) ?? props.orderBy;\n return props.order ? `${field}:${props.order}` : field;\n }\n if (Array.isArray(props.orderBy) && props.orderBy.length > 0) {\n return props.orderBy.map(entry => Array.isArray(entry) && typeof entry[0] === \"string\"\n ? [keys.get(entry[0]) ?? entry[0], ...entry.slice(1)]\n : entry);\n }\n return undefined;\n}\n\n/** A collection's belongsTo relations, by name → the foreign key its rows carry. */\nfunction foreignKeys(collection: CollectionConfig | undefined): Map<string, string> {\n const keys = new Map<string, string>();\n if (!collection) return keys;\n try {\n for (const [name, relation] of Object.entries(resolveCollectionRelations(collection))) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n keys.set(name, fieldKeyForColumn(collection, relation.localKey));\n }\n }\n } catch {\n // A relation whose target is not in this view: no key to rename.\n }\n return keys;\n}\n\n/** A write's plan and token, where its first call answered one (the server's `confirmation.ts`). */\nfunction planOf(answer: unknown): { token: string; plan: WritePlan } | undefined {\n if (!isRecord(answer) || answer.status !== \"confirmation_required\" || typeof answer.confirm !== \"string\") return undefined;\n const plan = isRecord(answer.plan) ? answer.plan : {};\n return {\n token: answer.confirm,\n plan: {\n summary: typeof plan.summary === \"string\" ? plan.summary : \"Save this change?\",\n ...(Array.isArray(plan.effects) && { effects: plan.effects.filter((line): line is string => typeof line === \"string\") }),\n ...(typeof plan.reversible === \"string\" && { reversible: plan.reversible })\n }\n };\n}\n\n/** A result with no `structuredContent`: its text, as JSON where it is JSON. */\nfunction parseText(result: ToolResult): unknown {\n const text = textOf(result);\n if (text === undefined) return undefined;\n // The server fences rows as untrusted data; the JSON is inside the fence.\n const start = text.indexOf(\"{\");\n const end = text.lastIndexOf(\"}\");\n if (start < 0 || end < start) return undefined;\n try {\n return JSON.parse(text.slice(start, end + 1));\n } catch {\n return undefined;\n }\n}\n\nexport function textOf(result: ToolResult): string | undefined {\n return result.content?.find(block => typeof block.text === \"string\")?.text;\n}\n\n/** What the model is told the person changed here, sent with their next message. */\nexport function describeChanges(changes: readonly ViewChange[]): string {\n const lines = changes.map(change => change.action === \"updated\"\n ? `updated ${change.fields?.join(\", \") || \"fields\"} on row ${change.id} of ${change.collection}`\n : `${change.action} row ${change.id} of ${change.collection}`);\n return `In the Rebase view, the user saved these changes: ${lines.join(\"; \")}. `\n + \"Rows you read before them may be out of date.\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,IAAa,kBAA+B;CACxC,MAAM;EAAE,MAAM;EAAoB,WAAW,CAAC;CAAE;CAChD,KAAK;EAAE,MAAM;EAAgB,WAAW,CAAC;CAAE;CAC3C,OAAO;EAAE,MAAM;EAAmB,WAAW,CAAC;CAAE;CAChD,QAAQ;EAAE,MAAM;EAAmB,WAAW,CAAC;CAAE;CACjD,QAAQ;EAAE,MAAM;EAAmB,WAAW,CAAC;CAAE;CACjD,QAAQ;EAAE,MAAM;EAAmB,WAAW,CAAC;CAAE;CACjD,WAAW;EAAE,MAAM;EAAuB,WAAW,CAAC;CAAE;AAC5D;;AAoFA,IAAa,qBAAb,cAAwC,MAAM;CAC1C,cAAc;EACV,MAAM,0CAA0C;EAChD,KAAK,OAAO;CAChB;AACJ;;AAGA,IAAM,YAAY;;;;;;;;;AAUlB,IAAM,cAAc;AAEpB,SAAgB,iBAAiB,SAAwC;CACrE,MAAM,EAAE,UAAU,SAAS,SAAS,aAAa;CACjD,MAAM,WAAW,QAAQ,qBAAqB,KAAA;CAC9C,MAAM,aAAa,eAAuB,SAAS,UAAU,CAAC,EAAE,QAAQ;CAExE,IAAI,QAAQ,CAAC,GAAI,QAAQ,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,GAAI,GAAI,QAAQ,SAAS,CAAC,CAAE,CAAC,CAC1E,KAAI,UAAS;EAAE;EAAM,WAAW;EAAO,YAAY,KAAK,UAAU,KAAA;CAAU,EAAE;CACnF,MAAM,WAAW,KAAK,IAAI;CAC1B,MAAM,UAAwB,CAAC;CAM/B,MAAM,uBAAO,IAAI,I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AO,OAAO,CAAC;CACpD,OAAO;EACH,OAAO,OAAO;EACd,MAAM;GACF,SAAS,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU;GAC3D,GAAI,MAAM,QAAQ,KAAK,OAAO,KAAK,EAAE,SAAS,KAAK,QAAQ,QAAQ,SAAyB,OAAO,SAAS,QAAQ,EAAE;GACtH,GAAI,OAAO,KAAK,eAAe,YAAY,EAAE,YAAY,KAAK,WAAW;EAC7E;CACJ;AACJ;;AAGA,SAAS,UAAU,QAA6B;CAC5C,MAAM,OAAO,OAAO,MAAM;CAC1B,IAAI,SAAS,KAAA,GAAW,OAAO,KAAA;CAE/B,MAAM,QAAQ,KAAK,QAAQ,GAAG;CAC9B,MAAM,MAAM,KAAK,YAAY,GAAG;CAChC,IAAI,QAAQ,KAAK,MAAM,OAAO,OAAO,KAAA;CACrC,IAAI;EACA,OAAO,KAAK,MAAM,KAAK,MAAM,OAAO,MAAM,CAAC,CAAC;CAChD,QAAQ;EACJ;CACJ;AACJ;AAEA,SAAgB,OAAO,QAAwC;CAC3D,OAAO,OAAO,SAAS,MAAK,UAAS,OAAO,MAAM,SAAS,QAAQ,CAAC,EAAE;AAC1E;;AAGA,SAAgB,gBAAgB,SAAwC;CAIpE,OAAO,qDAHO,QAAQ,KAAI,WAAU,OAAO,WAAW,YAChD,WAAW,OAAO,QAAQ,KAAK,IAAI,KAAK,SAAS,UAAU,OAAO,GAAG,MAAM,OAAO,eAClF,GAAG,OAAO,OAAO,OAAO,OAAO,GAAG,MAAM,OAAO,YACO,CAAA,CAAM,KAAK,IAAI,EAAE;AAEjF"}
1
+ {"version":3,"file":"tool_driver.js","names":[],"sources":["../../src/mcp_view/tool_driver.ts"],"sourcesContent":["/**\n * The admin panel's data layer, over the MCP tools of the server that served\n * this view.\n *\n * `<Rebase>` reads and writes through a `DataDriver`; this one turns each read\n * and write into a `tools/call` the host relays to the server — the same\n * tools, the same person, the same RLS as the model's own calls. Rows go and\n * come in the REST shape those tools speak (dates as ISO text, a belongsTo as\n * its foreign key); `<Rebase>` turns them into the admin panel's view model\n * and back, as it does for any driver.\n *\n * An app's row hooks (`useRows`, `useAggregate`, …) read the same driver\n * through the flat data layer (`buildRebaseData`), which keeps the wire's\n * rows and takes aggregates from `restFetchService`: here, the aggregate tool.\n *\n * A write the server answers with a plan (the hosted connector's two-step\n * `write`) is held: the person is shown the plan and the write is sent again\n * with its token only if they confirm. The row hooks write through\n * `confirmingDriver`, which asks the person before any other write too: code\n * can write without a click, while a save made with the admin's own controls\n * was the person's click. Either way the admin panel sees one save that took\n * a moment longer, or one that failed with \"Not saved\".\n *\n * The driver does not subscribe (no `listenCollection`/`listenOne`): every\n * write it makes comes through `<Rebase>`'s data layers, which say so on the\n * `<Rebase>`'s change signal, and each view of the collection reads again on\n * it. It learns of no change it did not make — the host relays no other\n * tool's calls — so it has nothing to announce either\n * (`subscribeToExternalChanges`).\n */\nimport {\n DEFAULT_DATA_SOURCE_KEY,\n type CollectionConfig,\n type DataDriver,\n type DeleteProps,\n type FetchCollectionProps,\n type FetchOneProps,\n type RestFetchService,\n type SaveProps\n} from \"@rebasepro/types\";\nimport {\n buildCompositeId,\n fieldKeyForColumn,\n getDeclaredPrimaryKeys,\n resolveCollectionRelations,\n resolvePrimaryKeys,\n type PrimaryKeyInfo\n} from \"@rebasepro/common\";\nimport { toWireRow } from \"@rebasepro/app\";\nimport { isRecord, type ToolResult } from \"./bridge\";\n\n/** A tool the view calls, and the arguments it always sends to it. */\nexport interface ToolAction {\n tool: string;\n arguments: Record<string, unknown>;\n /**\n * The tool answers a plan before it changes anything (the hosted\n * connector's `write`), so the person confirms there. Not set, a change\n * the row hooks make is confirmed in the view before it is sent.\n */\n plans?: boolean;\n}\n\n/**\n * The tools the view reads and writes with. The server that served it may\n * name its own (`actions` in a show_* result): the hosted Rebase connector\n * reads with `query` and writes with `write`, each with the project. Absent,\n * they are an app's own `/mcp` tools.\n */\nexport interface ViewActions {\n page: ToolAction;\n get: ToolAction;\n count: ToolAction;\n create: ToolAction;\n update: ToolAction;\n delete: ToolAction;\n /** `count`/`sum`/`avg`/`min`/`max` over the matching rows, grouped or not, as REST's `select` and `groupBy`. */\n aggregate: ToolAction;\n}\n\nexport const DEFAULT_ACTIONS: ViewActions = {\n page: { tool: \"query_collection\", arguments: {} },\n get: { tool: \"get_document\", arguments: {} },\n count: { tool: \"count_documents\", arguments: {} },\n create: { tool: \"create_document\", arguments: {} },\n update: { tool: \"update_document\", arguments: {} },\n delete: { tool: \"delete_document\", arguments: {} },\n aggregate: { tool: \"aggregate_documents\", arguments: {} }\n};\n\n/** What a write's first call answered instead of running: what it will do, for the person to confirm. */\nexport interface WritePlan {\n summary: string;\n effects?: string[];\n reversible?: string;\n}\n\n/** One change the person made here, as the model is told about it. */\nexport interface ViewChange {\n action: \"created\" | \"updated\" | \"deleted\";\n collection: string;\n id: string;\n /** The row as the person knows it — its title — where the driver can tell; see {@link ToolDriverOptions.rowLabel}. */\n label?: string;\n fields?: string[];\n}\n\n/** A write the server refused: what was tried, on which row, and the server's words. */\nexport interface WriteFailure {\n action: \"create\" | \"update\" | \"delete\";\n collection: string;\n /** The row, as {@link ToolDriverOptions.rowLabel} names it; absent for a create. */\n row?: string;\n message: string;\n}\n\n/** The calls the driver makes: the bridge's `callTool`, as a function so a test can stand in for the host. */\nexport type CallTool = (name: string, args: Record<string, unknown>) => Promise<ToolResult>;\n\n/**\n * A page a result already carries: the rows the server read — for the model\n * (show_collection), or ahead of an app's first render (show_app) — and the\n * arguments it read them with.\n */\nexport interface SeedPage {\n collection: string;\n /** As the read tools take them: `where`, `orderBy`, `searchString`, `limit`, `offset`. */\n args: Record<string, unknown>;\n rows: Record<string, unknown>[];\n /** How many rows the read's filter matches, where the server counted them: answers that count, once. */\n total?: number;\n}\n\nexport interface ToolDriverOptions {\n callTool: CallTool;\n actions: ViewActions;\n /** Show the person a write's plan; true when they confirm it. */\n confirm: (plan: WritePlan) => Promise<boolean>;\n /**\n * A page already read: served once in place of the read tool's call, to\n * a read asking for exactly it, and dropped by any write or once it is\n * older than the driver's read cache keeps a row.\n */\n seed?: SeedPage;\n /**\n * Pages read ahead of an app's first render, one per collection it\n * names: each served once as {@link seed} is, its rows answering a read\n * by key, and its `total` the count of the collection's rows.\n */\n seeds?: SeedPage[];\n /** Every change made through this driver, in order, after each one. */\n onChange?: (changes: readonly ViewChange[]) => void;\n /**\n * How a row is named to the person — in a write's confirmation, in a\n * refusal — given the row where the driver has read it: its title, say.\n * Without it, or where it says nothing, `row <id>`.\n */\n rowLabel?: (collection: string, id: string, row: Record<string, unknown> | undefined) => string | undefined;\n /**\n * A write through {@link ToolDriver.confirmingDriver} that the server\n * refused. App code can drop the rejection it gets; this is how the\n * person and the model still learn of it. A write the person declined is\n * not one.\n */\n onWriteFailed?: (failure: WriteFailure) => void;\n /**\n * The collection a name the tools take names — its slug or its data\n * path: an app names collections as the model wrote them, the admin\n * panel by slug. A write's values are sent by its config (a date-only\n * column as its day, a belongsTo under its foreign key), and drop what\n * was read of it under either name.\n */\n collection?: (name: string) => CollectionConfig | undefined;\n}\n\ntype Row = Record<string, unknown>;\n\nexport interface ToolDriver {\n /** For `<Rebase>`: the admin panel's reads and saves. */\n driver: DataDriver;\n /**\n * The same driver, asking the person before each write the tool does not\n * plan itself: for the row hooks (`useRowWrites`), since code can write\n * without a click. A declined write rejects with {@link SaveCancelledError}\n * and nothing is sent.\n */\n confirmingDriver: DataDriver;\n}\n\n/** A row asked for by key, waiting on its batch's page. */\ninterface QueuedRead {\n resolve: (row: Record<string, unknown> | undefined) => void;\n reject: (error: unknown) => void;\n}\n\n/** A save the person declined at the plan. The form shows it as the save's error. */\nexport class SaveCancelledError extends Error {\n constructor() {\n super(\"Not saved: the change was not confirmed.\");\n this.name = \"SaveCancelledError\";\n }\n}\n\n/** The ceiling every read tool takes for `limit` (`MAX_LIST_LIMIT`). */\nconst MAX_LIMIT = 1000;\n\n/**\n * How long a row read, or the seeded page, answers in place of the server.\n * Long enough for one render's relation previews and concurrent reads to\n * share a call, and for a row the person picks off the page they are looking\n * at to open with none; short enough that a row the model changed with its\n * own tools — which takes the person's message and the model's turn — is\n * read afresh when it is refreshed or opened again.\n */\nconst READ_TTL_MS = 30_000;\n\nexport function createToolDriver(options: ToolDriverOptions): ToolDriver {\n const { callTool, actions, confirm, onChange } = options;\n const configOf = options.collection ?? (() => undefined);\n const canonical = (collection: string) => configOf(collection)?.slug ?? collection;\n // Each seed answers its page once and its count once.\n let seeds = [...(options.seed ? [options.seed] : []), ...(options.seeds ?? [])]\n .map(page => ({ page, pageTaken: false, countTaken: page.total === undefined }));\n const seededAt = Date.now();\n const changes: ViewChange[] = [];\n // A table draws each row's relations by reading the related row, so a\n // page of orders asks for the same customer many times over. Each read is\n // a round trip through the host: one per row is shared until a write, or\n // until it is older than `READ_TTL_MS`, since the model can change a row\n // with its own tools and this driver never hears of it.\n const rows = new Map<string, { read: Promise<Record<string, unknown> | undefined>; at: number }>();\n // The counts asked for and not yet answered, by what they count.\n const counting = new Map<string, Promise<number>>();\n // The rows asked for by key in this tick and not yet read, by collection:\n // each collection's are read by one page call (`readQueued`).\n const queued = new Map<string, { key: PrimaryKeyInfo; reads: Map<string, QueuedRead> }>();\n let readsQueued = false;\n\n const call = async (action: ToolAction, args: Record<string, unknown>): Promise<unknown> => {\n const result = await callTool(action.tool, { ...action.arguments, ...args });\n if (result.isError) throw new Error(textOf(result) ?? \"The server refused this call.\");\n return result.structuredContent ?? parseText(result);\n };\n\n /** A write, through its plan where the server asks for one. */\n const write = async (action: ToolAction, args: Record<string, unknown>): Promise<unknown> => {\n const first = await call(action, args);\n const plan = planOf(first);\n if (!plan) return first;\n if (!await confirm(plan.plan)) throw new SaveCancelledError();\n const second = await call(action, { ...args, confirm: plan.token });\n if (planOf(second)) throw new Error(\"The server asked for confirmation again; nothing was saved.\");\n return second;\n };\n\n /**\n * What a write changed: what was read of its collection is dropped (the\n * seeded page, the rows), and the model is told. The views read again on\n * `<Rebase>`'s change signal, which the write's data layer emits.\n */\n const changed = (change: ViewChange) => {\n // Every seed, not only this collection's: a page carries the related\n // rows it includes, and a write to those changes it too.\n seeds = [];\n // A count asked before the write answers for before it; the views'\n // refresh asks again.\n counting.clear();\n const key = canonical(change.collection);\n for (const row of rows.keys()) if (canonical(row.slice(0, row.lastIndexOf(\"/\"))) === key) rows.delete(row);\n changes.push(change);\n onChange?.(changes);\n };\n\n /** A save's values as the write tools take them, by the collection's config where it is known. */\n const wireValues = (props: SaveProps, collection: string): Record<string, unknown> => {\n const defined = Object.fromEntries(Object.entries(props.values).filter(([, value]) => value !== undefined));\n return toWireRow(defined, props.collection ?? configOf(collection) ?? NO_CONFIG, { included: false });\n };\n\n /**\n * A page's rows into the row cache, keyed as {@link fetchOne} asks for\n * them: the row a view lists is the row its record opens with, and a row\n * an app was just shown opens with no call of its own. By the\n * collection's key where its config is known, by `id` otherwise; a write\n * to the collection drops them, as it drops every row read. Not a page\n * that lists deleted rows: `get` answers none for those.\n */\n const remember = (collection: string, page: Row[], config?: FetchCollectionProps[\"collection\"]) => {\n const keys = config ? getDeclaredPrimaryKeys(config) : [];\n for (const row of page) {\n const id = keys.length > 1 ? buildCompositeId(row, keys) : row[keys[0]?.fieldName ?? \"id\"];\n if (typeof id !== \"string\" && typeof id !== \"number\") continue;\n rows.set(`${collection}/${String(id)}`, { read: Promise.resolve(row), at: Date.now() });\n }\n };\n // A seeded row opens with no call of its own — a record form, a detail,\n // a relation's title — even where no read asks for the page it came in.\n for (const { page } of seeds) remember(page.collection, page.rows, configOf(page.collection));\n\n /**\n * The seeded page, once, to a read asking for exactly it — or for more\n * of the same rows where the seed already holds every one: a view asks\n * one row past its page to learn whether there are more, and a page\n * shorter than its limit has answered that.\n */\n const takeSeed = (collection: string, args: Record<string, unknown>): Row[] | undefined => {\n if (Date.now() - seededAt > READ_TTL_MS) seeds = [];\n const seed = seeds.find(candidate => !candidate.pageTaken\n && canonical(candidate.page.collection) === canonical(collection) && readKey(candidate.page.args) === readKey(args));\n if (!seed) return undefined;\n const seedLimit = limitOf(seed.page.args);\n const readLimit = limitOf(args);\n const complete = seedLimit === undefined || seed.page.rows.length < seedLimit;\n const answers = readLimit === seedLimit || (complete && (readLimit === undefined || seedLimit === undefined || readLimit > seedLimit));\n if (!answers) return undefined;\n seed.pageTaken = true;\n return seed.page.rows;\n };\n\n /** The count a seed's `total` answers — the collection's rows, unfiltered — once. */\n const takeSeedCount = (collection: string, args: Record<string, unknown>): number | undefined => {\n if (Date.now() - seededAt > READ_TTL_MS) seeds = [];\n if (args.where !== undefined || args.searchString !== undefined || args.deleted !== undefined) return undefined;\n const seed = seeds.find(candidate => !candidate.countTaken && canonical(candidate.page.collection) === canonical(collection)\n && candidate.page.args.where === undefined && candidate.page.args.searchString === undefined);\n if (!seed || seed.page.total === undefined) return undefined;\n seed.countTaken = true;\n return seed.page.total;\n };\n\n const fetchCollection = async (props: FetchCollectionProps): Promise<Record<string, unknown>[]> => {\n const collection = collectionArg(props.path);\n const args = readArgs(props);\n let found = takeSeed(collection, args);\n if (!found) {\n const page = await call(actions.page, { collection, ...args });\n if (!isRecord(page) || !Array.isArray(page.data)) throw new Error(\"The read returned no rows.\");\n found = page.data.filter(isRecord);\n }\n if (!props.withDeleted) remember(collection, found, props.collection);\n return found;\n };\n\n /**\n * The rows asked for by key in one tick, read together: one page call per\n * collection, `where <key> in [ids]`, however many relation previews a\n * render draws — as the admin's `useBatchedFetch` reads them, chunked at\n * the read tools' ceiling. A row the page does not carry is absent or not\n * visible to the person: one answer for both, as the get tool gives.\n */\n const readQueued = () => {\n readsQueued = false;\n const batches = [...queued];\n queued.clear();\n for (const [collection, { key, reads }] of batches) {\n const ids = [...reads.keys()];\n for (let i = 0; i < ids.length; i += MAX_LIMIT) {\n const chunk = ids.slice(i, i + MAX_LIMIT);\n const values = chunk.map(id => key.type === \"number\" && id.trim() !== \"\" && !Number.isNaN(Number(id)) ? Number(id) : id);\n call(actions.page, { collection, where: { [key.fieldName]: [\"in\", values] }, limit: chunk.length })\n .then(page => {\n if (!isRecord(page) || !Array.isArray(page.data)) throw new Error(\"The read returned no rows.\");\n const byId = new Map(page.data.filter(isRecord).map(row => [String(row[key.fieldName]), row]));\n for (const id of chunk) reads.get(id)?.resolve(byId.get(id));\n })\n .catch((error: unknown) => {\n for (const id of chunk) reads.get(id)?.reject(error);\n });\n }\n }\n };\n\n const readByKey = (collection: string, id: string, key: PrimaryKeyInfo): Promise<Row | undefined> =>\n new Promise((resolve, reject) => {\n let batch = queued.get(collection);\n if (!batch) {\n batch = { key, reads: new Map() };\n queued.set(collection, batch);\n }\n batch.reads.set(id, { resolve, reject });\n if (!readsQueued) {\n readsQueued = true;\n queueMicrotask(readQueued);\n }\n });\n\n /** A row of a collection with no single key column to put an `in` on, or none known: by the get tool. */\n const readById = (collection: string, id: string): Promise<Row | undefined> =>\n call(actions.get, { collection, id })\n .then(row => isRecord(row) ? row : undefined)\n .catch((error: unknown) => {\n // One answer for \"absent\" and \"not visible to you\", by design.\n if (error instanceof Error && /^No row with id/.test(error.message)) return undefined;\n throw error;\n });\n\n /**\n * A row: by the page tool wherever its collection has one key column — a\n * lone row as well as a crowd of previews. One rule, so a row is read the\n * same way however many are drawn beside it; and the page tool is the one\n * every server names (a hosted result may name no `get`), whose answer\n * for an absent row is an empty page rather than an error told apart by\n * its text.\n */\n const fetchOne = (props: FetchOneProps): Promise<Record<string, unknown> | undefined> => {\n const collection = collectionArg(props.path);\n const key = `${collection}/${String(props.id)}`;\n const cached = rows.get(key);\n if (cached && Date.now() - cached.at <= READ_TTL_MS) return cached.read;\n const config = props.collection ?? configOf(collection);\n const keys = config ? resolvePrimaryKeys(config) : [];\n const read: Promise<Row | undefined> = (keys.length === 1\n ? readByKey(collection, String(props.id), keys[0])\n : readById(collection, String(props.id)))\n .catch((error: unknown) => {\n if (rows.get(key)?.read === read) rows.delete(key);\n throw error;\n });\n rows.set(key, { read, at: Date.now() });\n return read;\n };\n\n /**\n * The flat data layer's reads: the same tools and the same rows as the\n * admin panel's, and the aggregate tool.\n */\n const restFetchService: RestFetchService = {\n fetchCollectionForRest(path, options = {}) {\n refuseUnsupported(options);\n return fetchCollection({\n path,\n ...(options.filter && { filter: options.filter }),\n ...(options.orderBy !== undefined && { orderBy: options.orderBy }),\n ...(options.order && { order: options.order }),\n ...(options.limit !== undefined && { limit: options.limit }),\n ...(options.offset !== undefined && { offset: options.offset }),\n ...(options.searchString && { searchString: options.searchString }),\n ...(options.withDeleted !== undefined && { withDeleted: options.withDeleted })\n });\n },\n async fetchOneForRest(path, id) {\n return await fetchOne({ path, id }) ?? null;\n },\n async aggregate(path, options) {\n refuseUnsupported(options);\n const where = options.filter ? wireFilter(options.filter, undefined) : undefined;\n const answer = await call(actions.aggregate, {\n collection: collectionArg(path),\n select: options.aggregates.map(aggregate => aggregate.fn === \"percentile\"\n ? `${aggregate.fn}(${aggregate.field ?? \"\"},${aggregate.p})`\n : `${aggregate.fn}(${aggregate.field ?? \"\"})`),\n ...(options.groupBy && options.groupBy.length > 0 && {\n groupBy: options.groupBy.map(group => typeof group === \"string\" ? group : `${group.transform}(${group.field})`)\n }),\n ...(where && Object.keys(where).length > 0 && { where }),\n ...(options.searchString && { searchString: options.searchString }),\n ...(options.orderBy && options.orderBy.length > 0 && { orderBy: options.orderBy }),\n ...(options.limit !== undefined && { limit: Math.min(options.limit, MAX_LIMIT) }),\n ...(options.offset && { offset: options.offset }),\n ...(options.withDeleted && { deleted: options.withDeleted === \"only\" ? \"only\" : \"include\" })\n });\n if (!isRecord(answer) || !Array.isArray(answer.data)) throw new Error(\"The aggregate returned no rows.\");\n return answer.data.filter(isRecord);\n }\n };\n\n const driver: DataDriver = {\n key: DEFAULT_DATA_SOURCE_KEY,\n initialised: true,\n\n fetchCollection,\n fetchOne,\n restFetchService,\n\n async save(props: SaveProps): Promise<Record<string, unknown>> {\n const collection = collectionArg(props.path);\n const data = wireValues(props, collection);\n const creating = props.status !== \"existing\";\n const action = creating ? actions.create : actions.update;\n const saved = creating\n ? await write(action, { collection, data, ...(props.id !== undefined && { id: String(props.id) }) })\n : await write(action, { collection, id: String(props.id), data });\n const row = isRecord(saved) ? saved : { ...data };\n const id = String(row.id ?? props.id ?? \"\");\n const label = options.rowLabel?.(collection, id, row);\n changed({ action: creating ? \"created\" : \"updated\", collection, id, ...(label && { label }), fields: Object.keys(data) });\n return row;\n },\n\n async delete(props: DeleteProps): Promise<void> {\n const collection = collectionArg(props.row.path);\n const id = String(props.row.id);\n // Named before the write: it drops what was read of the collection.\n const cached = await rows.get(`${collection}/${id}`)?.read.catch(() => undefined);\n const label = options.rowLabel?.(collection, id, cached ?? undefined);\n await write(actions.delete, { collection, id });\n changed({ action: \"deleted\", collection, id, ...(label && { label }) });\n },\n\n async count(props: FetchCollectionProps): Promise<number> {\n const collection = collectionArg(props.path);\n const args = pickRead(readArgs(props), [\"where\", \"searchString\", \"deleted\"]);\n const seeded = takeSeedCount(collection, args);\n if (seeded !== undefined) return seeded;\n // One call for the same count asked twice at once — a KPI tile and\n // the panel listing the same rows, on one render.\n const key = `${canonical(collection)}|${readKey(args)}`;\n const inFlight = counting.get(key);\n if (inFlight) return inFlight;\n const counted: Promise<number> = call(actions.count, { collection, ...args }).then((answer) => {\n if (isRecord(answer) && typeof answer.count === \"number\") return answer.count;\n throw new Error(\"The count returned no number.\");\n }).finally(() => {\n // Only its own entry: a write may have cleared it, and a new count taken its place.\n if (counting.get(key) === counted) counting.delete(key);\n });\n counting.set(key, counted);\n return counted;\n },\n\n // The server checks a unique field when the row is written; a check\n // here would be one more round trip through the host for each keystroke.\n async checkUniqueField(): Promise<boolean> {\n return true;\n }\n };\n\n /** The person's yes before a write the tool does not plan; their no rejects, and nothing is sent. */\n const confirmFirst = async (action: ToolAction, plan: WritePlan): Promise<void> => {\n if (!action.plans && !await confirm(plan)) throw new SaveCancelledError();\n };\n\n /** A row as the person knows it: its title where it has been read, else `row <id>`. */\n const labelOf = async (collection: string, id: string): Promise<string> => {\n const row = await rows.get(`${collection}/${id}`)?.read.catch(() => undefined);\n return options.rowLabel?.(collection, id, row ?? undefined) || `row ${id}`;\n };\n\n /** A refused write, told; the rejection still reaches the caller. */\n const reported = async <T, >(failure: Omit<WriteFailure, \"message\">, write: () => Promise<T>): Promise<T> => {\n try {\n return await write();\n } catch (error) {\n if (!(error instanceof SaveCancelledError)) {\n options.onWriteFailed?.({ ...failure, message: error instanceof Error ? error.message : String(error) });\n }\n throw error;\n }\n };\n\n const confirmingDriver: DataDriver = {\n ...driver,\n async save(props: SaveProps): Promise<Record<string, unknown>> {\n const collection = collectionArg(props.path);\n const creating = props.status !== \"existing\";\n const row = creating ? undefined : await labelOf(collection, String(props.id));\n await confirmFirst(creating ? actions.create : actions.update, creating\n ? { summary: `Create a row in ${collection}.` }\n : { summary: `Change ${Object.keys(wireValues(props, collection)).join(\", \")} on ${row} of ${collection}.` });\n return reported({ action: creating ? \"create\" : \"update\", collection, ...(row && { row }) }, () => driver.save(props));\n },\n async delete(props: DeleteProps): Promise<void> {\n const collection = collectionArg(props.row.path);\n const row = await labelOf(collection, String(props.row.id));\n await confirmFirst(actions.delete, { summary: `Delete ${row} of ${collection}.` });\n return reported({ action: \"delete\", collection, row }, () => driver.delete(props));\n }\n };\n\n return { driver, confirmingDriver };\n}\n\n/**\n * The collection a driver path names. The views open top-level collections\n * only; a subcollection path has no tool to read it.\n */\nfunction collectionArg(path: string): string {\n if (path.includes(\"/\")) throw new Error(`\"${path}\" is a subcollection, which this view cannot open.`);\n return path;\n}\n\n/** A read's arguments, as the read tools take them. */\nfunction readArgs(props: FetchCollectionProps): Record<string, unknown> {\n const where = props.filter ? wireFilter(props.filter, props.collection) : undefined;\n const orderBy = wireOrderBy(props, props.collection);\n return {\n ...(where && Object.keys(where).length > 0 && { where }),\n ...(orderBy && { orderBy }),\n ...(props.searchString && { searchString: props.searchString }),\n ...(props.limit !== undefined && { limit: Math.min(props.limit, MAX_LIMIT) }),\n ...(props.offset && { offset: props.offset }),\n ...(props.withDeleted !== undefined && props.withDeleted !== false && {\n deleted: props.withDeleted === \"only\" ? \"only\" : \"include\"\n })\n };\n}\n\n/** What the read tools cannot express, refused rather than read wider than asked. */\nfunction refuseUnsupported(options: { logical?: unknown; vectorSearch?: unknown }): void {\n if (options.logical) throw new Error(\"This view's tools cannot filter by an or()/and() group.\");\n if (options.vectorSearch) throw new Error(\"This view's tools cannot run a vector search.\");\n}\n\n/**\n * Which rows a read asks for, as one comparable string: the same rows however\n * the read was written — a sort as `\"field:desc\"` or `[[\"field\", \"desc\"]]`, a\n * filter's fields in any order, no offset or offset 0. How many is\n * {@link limitOf}'s.\n */\nfunction readKey(args: Record<string, unknown>): string {\n const where = isRecord(args.where) ? args.where : {};\n return JSON.stringify([\n Object.keys(where).sort().map(key => [key, where[key]]),\n sortOf(args.orderBy),\n typeof args.searchString === \"string\" ? args.searchString : \"\",\n typeof args.offset === \"number\" ? args.offset : 0,\n typeof args.deleted === \"string\" ? args.deleted : null\n ]);\n}\n\nfunction limitOf(args: Record<string, unknown>): number | undefined {\n return typeof args.limit === \"number\" ? args.limit : undefined;\n}\n\nfunction sortOf(orderBy: unknown): unknown[] {\n if (typeof orderBy === \"string\" && orderBy !== \"\") {\n const [field, direction] = orderBy.split(\":\");\n return [[field, direction === \"desc\" ? \"desc\" : \"asc\"]];\n }\n if (!Array.isArray(orderBy) || orderBy.length === 0) return [];\n const entries: unknown[] = Array.isArray(orderBy[0]) ? orderBy : [orderBy];\n return entries.map(entry => Array.isArray(entry) ? [entry[0], entry[1] === \"desc\" ? \"desc\" : \"asc\"] : entry);\n}\n\nfunction pickRead(args: Record<string, unknown>, names: readonly string[]): Record<string, unknown> {\n return Object.fromEntries(Object.entries(args).filter(([name]) => names.includes(name)));\n}\n\n/**\n * The admin panel's filter as the read tools' `where`: a belongsTo is\n * filtered by its foreign key there, and a value is the wire's — a relation\n * its id, a date its ISO text.\n */\nfunction wireFilter(filter: Record<string, unknown>, collection: CollectionConfig | undefined): Record<string, unknown> {\n const keys = foreignKeys(collection);\n const where: Record<string, unknown> = {};\n for (const [key, condition] of Object.entries(filter)) {\n if (condition === undefined) continue;\n // A condition is `[op, value]`, each part converted as a row's value is.\n where[keys.get(key) ?? key] = toWireRow({ condition }, NO_CONFIG).condition;\n }\n return where;\n}\n\n/** No properties, so {@link toWireRow} converts each value by what it is: a relation to its id, a date to ISO text. */\nconst NO_CONFIG: CollectionConfig = { slug: \"\", name: \"\", properties: {} };\n\nfunction wireOrderBy(props: FetchCollectionProps, collection: CollectionConfig | undefined): string | unknown[] | undefined {\n const keys = foreignKeys(collection);\n if (typeof props.orderBy === \"string\") {\n const field = keys.get(props.orderBy) ?? props.orderBy;\n return props.order ? `${field}:${props.order}` : field;\n }\n if (Array.isArray(props.orderBy) && props.orderBy.length > 0) {\n return props.orderBy.map(entry => Array.isArray(entry) && typeof entry[0] === \"string\"\n ? [keys.get(entry[0]) ?? entry[0], ...entry.slice(1)]\n : entry);\n }\n return undefined;\n}\n\n/** A collection's belongsTo relations, by name → the foreign key its rows carry. */\nfunction foreignKeys(collection: CollectionConfig | undefined): Map<string, string> {\n const keys = new Map<string, string>();\n if (!collection) return keys;\n try {\n for (const [name, relation] of Object.entries(resolveCollectionRelations(collection))) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n keys.set(name, fieldKeyForColumn(collection, relation.localKey));\n }\n }\n } catch {\n // A relation whose target is not in this view: no key to rename.\n }\n return keys;\n}\n\n/** A write's plan and token, where its first call answered one (the server's `confirmation.ts`). */\nfunction planOf(answer: unknown): { token: string; plan: WritePlan } | undefined {\n if (!isRecord(answer) || answer.status !== \"confirmation_required\" || typeof answer.confirm !== \"string\") return undefined;\n const plan = isRecord(answer.plan) ? answer.plan : {};\n return {\n token: answer.confirm,\n plan: {\n summary: typeof plan.summary === \"string\" ? plan.summary : \"Save this change?\",\n ...(Array.isArray(plan.effects) && { effects: plan.effects.filter((line): line is string => typeof line === \"string\") }),\n ...(typeof plan.reversible === \"string\" && { reversible: plan.reversible })\n }\n };\n}\n\n/** A result with no `structuredContent`: its text, as JSON where it is JSON. */\nfunction parseText(result: ToolResult): unknown {\n const text = textOf(result);\n if (text === undefined) return undefined;\n // The server fences rows as untrusted data; the JSON is inside the fence.\n const start = text.indexOf(\"{\");\n const end = text.lastIndexOf(\"}\");\n if (start < 0 || end < start) return undefined;\n try {\n return JSON.parse(text.slice(start, end + 1));\n } catch {\n return undefined;\n }\n}\n\nexport function textOf(result: ToolResult): string | undefined {\n return result.content?.find(block => typeof block.text === \"string\")?.text;\n}\n\n/** What the model is told the person changed here, sent with their next message. */\n/** \"update ORD-2026-0081 in orders\", \"create a row in orders\". */\nexport function describeFailedWrite(failure: WriteFailure): string {\n return failure.action === \"create\"\n ? `create a row in ${failure.collection}`\n : `${failure.action} ${failure.row ?? \"a row\"} in ${failure.collection}`;\n}\n\nexport function describeChanges(changes: readonly ViewChange[]): string {\n const rowOf = (change: ViewChange) => change.label ? `${change.label} (row ${change.id})` : `row ${change.id}`;\n const lines = changes.map(change => change.action === \"updated\"\n ? `updated ${change.fields?.join(\", \") || \"fields\"} on ${rowOf(change)} of ${change.collection}`\n : `${change.action} ${rowOf(change)} of ${change.collection}`);\n return `In the Rebase view, the user saved these changes: ${lines.join(\"; \")}. `\n + \"Rows you read before them may be out of date.\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,IAAa,kBAA+B;CACxC,MAAM;EAAE,MAAM;EAAoB,WAAW,CAAC;CAAE;CAChD,KAAK;EAAE,MAAM;EAAgB,WAAW,CAAC;CAAE;CAC3C,OAAO;EAAE,MAAM;EAAmB,WAAW,CAAC;CAAE;CAChD,QAAQ;EAAE,MAAM;EAAmB,WAAW,CAAC;CAAE;CACjD,QAAQ;EAAE,MAAM;EAAmB,WAAW,CAAC;CAAE;CACjD,QAAQ;EAAE,MAAM;EAAmB,WAAW,CAAC;CAAE;CACjD,WAAW;EAAE,MAAM;EAAuB,WAAW,CAAC;CAAE;AAC5D;;AA4GA,IAAa,qBAAb,cAA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,MAAM,MAAM,KAAK,YAAY,GAAG;CAChC,IAAI,QAAQ,KAAK,MAAM,OAAO,OAAO,KAAA;CACrC,IAAI;EACA,OAAO,KAAK,MAAM,KAAK,MAAM,OAAO,MAAM,CAAC,CAAC;CAChD,QAAQ;EACJ;CACJ;AACJ;AAEA,SAAgB,OAAO,QAAwC;CAC3D,OAAO,OAAO,SAAS,MAAK,UAAS,OAAO,MAAM,SAAS,QAAQ,CAAC,EAAE;AAC1E;;;AAIA,SAAgB,oBAAoB,SAA+B;CAC/D,OAAO,QAAQ,WAAW,WACpB,mBAAmB,QAAQ,eAC3B,GAAG,QAAQ,OAAO,GAAG,QAAQ,OAAO,QAAQ,MAAM,QAAQ;AACpE;AAEA,SAAgB,gBAAgB,SAAwC;CACpE,MAAM,SAAS,WAAuB,OAAO,QAAQ,GAAG,OAAO,MAAM,QAAQ,OAAO,GAAG,KAAK,OAAO,OAAO;CAI1G,OAAO,qDAHO,QAAQ,KAAI,WAAU,OAAO,WAAW,YAChD,WAAW,OAAO,QAAQ,KAAK,IAAI,KAAK,SAAS,MAAM,MAAM,MAAM,EAAE,MAAM,OAAO,eAClF,GAAG,OAAO,OAAO,GAAG,MAAM,MAAM,EAAE,MAAM,OAAO,YACO,CAAA,CAAM,KAAK,IAAI,EAAE;AAEjF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rebasepro/cms",
3
- "version": "0.29.0-canary.g0e3a0e7",
3
+ "version": "0.29.1",
4
4
  "description": "Rebase CMS — content management views, forms, and routing",
5
5
  "keywords": [
6
6
  "rebase",
@@ -99,14 +99,14 @@
99
99
  "react-use-measure": "^2.1.7",
100
100
  "read-excel-file": "^9.3.10",
101
101
  "zod": "^4.4.3",
102
- "@rebasepro/app": "0.29.0-canary.g0e3a0e7",
103
- "@rebasepro/forms": "0.29.0-canary.g0e3a0e7",
104
- "@rebasepro/common": "0.29.0-canary.g0e3a0e7",
105
- "@rebasepro/cms-types": "0.29.0-canary.g0e3a0e7",
106
- "@rebasepro/inference": "0.29.0-canary.g0e3a0e7",
107
- "@rebasepro/types": "0.29.0-canary.g0e3a0e7",
108
- "@rebasepro/utils": "0.29.0-canary.g0e3a0e7",
109
- "@rebasepro/ui": "0.29.0-canary.g0e3a0e7"
102
+ "@rebasepro/app": "0.29.1",
103
+ "@rebasepro/common": "0.29.1",
104
+ "@rebasepro/cms-types": "0.29.1",
105
+ "@rebasepro/forms": "0.29.1",
106
+ "@rebasepro/inference": "0.29.1",
107
+ "@rebasepro/types": "0.29.1",
108
+ "@rebasepro/utils": "0.29.1",
109
+ "@rebasepro/ui": "0.29.1"
110
110
  },
111
111
  "peerDependencies": {
112
112
  "react": "^19.2.7",