diff --git a/.changeset/36498-custom-package-arrangement.md b/.changeset/36498-custom-package-arrangement.md new file mode 100644 index 00000000000..95d5d52d62e --- /dev/null +++ b/.changeset/36498-custom-package-arrangement.md @@ -0,0 +1,44 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': minor +'@objectstack/metadata-protocol': minor +'@objectstack/cli': minor +'@objectstack/cloud-connection': minor +'@objectstack/lint': minor +'@object-ui/app-shell': minor +'@object-ui/plugin-detail': minor +--- + +feat(spec): a base's paired `.custom` package declares an installed object's whole field-group and tab arrangement (`fieldGroups`, `relatedLists` on its object extension) + +Clause-②: yes (widening) +Metadata-protocol: added + +The record page is arranged in three layers. The package that owns an object declares its `fieldGroups` and `relatedLists`; a package that extends it places what it brings with `place`; and now the environment, in the base's paired `.custom` package, may declare the whole arrangement over both: + +```ts +objectExtensions: [{ + extend: 'crm_lead', + fields: { region__c: { type: 'text', label: 'Region' } }, + // The whole field arrangement: the two groups swapped, `status` moved. + fieldGroups: [ + { key: 'contact', label: 'Contact', fields: ['email', 'phone', 'status'] }, + { key: 'basic', label: 'Basics', fields: ['name', 'company', 'region__c'] }, + ], + // The whole tab list: events before tasks, the notes tab hidden. + relatedLists: ['crm_event', 'crm_task', { list: 'crm_note', hidden: true }], +}], +``` + +- **Two new keys on an object extension, written only by a `.custom` package.** `fieldGroups` takes the shape an object's `fieldGroups` takes and may list any field the object has, whoever declares it; a group's `relatedList` may place any body table. `relatedLists` takes an object's entry shape (a bare name, the three built-in tab names, or `{ list, label?, columns? }`) plus `hidden`. +- **Each key replaces, whole.** The registry applies it last: the owner's arrangement, then every extension's `place`, then the `.custom` key in place of the result. Nothing is merged entry by entry. A key the extension does not write keeps the owner's arrangement with the placements, so writing only `relatedLists` leaves the field groups as they were. +- **A field the arrangement does not list is not dropped.** It shows after the last group, whichever group its owner or another extension had put it in. A group that lists `fields` shows exactly its list. +- **A tab the arrangement does not name still shows, after the listed ones.** This is the reverse of an object's own `relatedLists`, where leaving a list out hides it. Hiding is written: `{ list: 'crm_note', hidden: true }` hides that list's tab, whichever package brings it. `hidden` is accepted only here; an object's own `relatedLists` refuses it and says where it belongs. A list the owner hides by leaving it out of its own `relatedLists` stays hidden until the arrangement names it. The built-in tabs keep their own rules and are not hidden here. +- **A package that is not a `.custom` package writing either key is refused**, once at each door: saving or publishing the extension, `os validate` and `os build`, and installing the package (`VALIDATION_ERROR`; 400 at save and publish, 422 at install). Each refusal names the key, the object and the package and prescribes `place`. An extension that reaches the registry past those doors is not applied, and the boot log says so. Within one extension, a `place` entry beside the arrangement key that would replace it is refused at parse. +- **Only the object's own pair is served.** The pair is the `.custom` package of the App the object belongs to: for an object a module of an App owns, the App's pair. A `.custom` package an earlier version created for the module itself is still read while it is installed; where both write a key, the App's pair is served. The choice is by role, never by load order. What any other `.custom` package writes under these keys is not refused at the doors; the registry does not apply it, alone or beside the pair, and the boot log names the package and the object. +- **One merge, every reader.** The record page, the forms, the preview and Studio read the served object, so they show one arrangement. Removing a key, or uninstalling or disabling the `.custom` package, serves the owner's arrangement with the placements again. +- **Served reads say what the reader cannot derive.** Where a `.custom` package writes `relatedLists`, the served object carries the read decoration `_relatedListsArrangement` (`{ packageId, hidden, unlisted }`): the lists the environment hides, and whether an unlisted list shows. The record page's tab reader and the default page synthesis read it; with no decoration served they answer exactly as before. A reader's own tab order (kept per user) is still laid over this list, and a tab the environment hides is not offered to them. +- **A group the arrangement brings is a translation anchor.** `os validate`'s translation-reference rule reads an extension's `fieldGroups` too, so a bundle's `_sections` key for a group the `.custom` arrangement declares is not reported as naming nothing. +- **`hidden` on a field is not a display property a `fieldPatches` entry may set.** A hidden field is also left out of the search index and out of a form's required check, so the display whitelist is not widened. To keep a vendor field off the record page and the forms, list it in a group whose `visibleWhen` is false. That is presentation only, not access control: the field stays readable and writable through the API. Do not use it for a `required` field that has no default: the create form no longer shows the field while the save still requires it, so the form cannot be submitted. + +What to check in an app: nothing changes until a `.custom` package writes one of the two keys. A package other than a `.custom` one that wrote `fieldGroups` or `relatedLists` on an extension was refused at parse. It is now refused by the save, publish, install, `os validate` and `os build` doors, with the same prescription. Where none of those doors judges it (for example a code-defined stack that boots without `os validate` or `os build`, or a stack that names no package id), the key is not applied and the boot log names it, where the parse refused it before. diff --git a/content/docs/data-modeling/object-extensions.mdx b/content/docs/data-modeling/object-extensions.mdx index f4959d49b12..e01ed6a4bb4 100644 --- a/content/docs/data-modeling/object-extensions.mdx +++ b/content/docs/data-modeling/object-extensions.mdx @@ -70,6 +70,7 @@ check that spelling first. | `pluralLabel` | Same as `label`. | | `description` | Same as `label`. | | `place` | **Applied once, after every extension's fields are merged.** Says where the fields, groups and child lists this extension brings go on the target — [below](#placing-what-you-bring). | +| `fieldGroups`, `relatedLists` | **Only in a base's paired `.custom` package. Each replaces, whole.** The complete field arrangement and the complete tab list of the target, applied last — [below](#arranging-the-whole-record-page). In any other package they are refused, and `place` is the key to use. | | `priority` | Not merged — it *orders* the merge. `0`–`999`, default `200`. | Added fields are ordinary fields, so everything on the @@ -78,17 +79,19 @@ Added fields are ordinary fields, so everything on the ### What an extension may **not** contribute -The merge carries the nine keys above and nothing else. These five are not +The merge carries the keys above and nothing else. The first three below are not "unsupported yet" — there is no slot for them to arrive through, and the schema rejects -each one by name with the alternative to use instead: +each one by name with the alternative to use instead. The last two are the paired +`.custom` package's alone: in any other package the save, publish and install doors, +`os validate` and `os build` refuse them, naming `place`: | Key you might reach for | Declare this instead | |:---|:---| | `actions` | A top-level action with `objectName: ''` in the same stack — it stays in the stack's top-level `actions`, and the engine's schema registry attaches it to the target object wherever the object is served, whichever package registers first; a target no loaded package registers fails the boot | | `hooks` | A top-level hook in the stack that defines the target object — a hook follows the ownership of its object, and `defineStack()` refuses a top-level hook bound to an object the stack does not define, an extended one included | | `listViews` | A top-level `view` in the stack that defines the target object — `defineStack()` refuses a top-level `view` whose `list` or `form` data source is an object the stack does not define, an extended one included | -| `fieldGroups` | A `place` entry: `{ group: { key, label }, after: '' }` adds a group of your own, and `{ field, group, after: '' }` puts a field of yours into one of the target's groups — [below](#placing-what-you-bring) | -| `relatedLists` | A `place` entry `{ list, after: '' }` for a child object of your own package that points at the target — [below](#placing-what-you-bring). The target's own tab list stays its owner's | +| `fieldGroups` (outside a `.custom` package) | A `place` entry: `{ group: { key, label }, after: '' }` adds a group of your own, and `{ field, group, after: '' }` puts a field of yours into one of the target's groups — [below](#placing-what-you-bring) | +| `relatedLists` (outside a `.custom` package) | A `place` entry `{ list, after: '' }` for a child object of your own package that points at the target — [below](#placing-what-you-bring). The target's own tab list stays its owner's, and the environment's | The same holds for any other key: the extension schema is strict, so an unknown key fails at authoring time with a prescription rather than being dropped in silence. @@ -272,6 +275,8 @@ D10). The object is extended, never replaced: pair on first use. - **An object takes no `overrides` declaration.** Declaring one on an object is refused, naming the extension as the route. +- **The pair may arrange the whole record page.** Its extension, and no other package's, + writes `fieldGroups` and `relatedLists` — [below](#arranging-the-whole-record-page). {/* os:check */} ```typescript @@ -295,6 +300,86 @@ export default defineStack({ }); ``` +### Arranging the whole record page + +A record page is arranged in three layers, and each has its own way to say where things go: + +| Layer | What it writes | Scope | +|:---|:---|:---| +| The package that owns the object | `fieldGroups` and `relatedLists` on the object | The whole arrangement | +| A package that extends it | `place` on its extension | Only the fields, groups and child lists it brings | +| The environment, in the base's paired `.custom` package | `fieldGroups` and `relatedLists` on its extension | The whole arrangement, over both layers above | + +So on an installed object the customer may move a vendor field to another group, reorder +the groups, and reorder or hide tabs, without touching the vendor's package: + +{/* os:check */} +```typescript +import { defineObjectExtension, Field } from '@objectstack/spec/data'; + +export const LeadPageExtension = defineObjectExtension({ + extend: 'crm_lead', + fields: { region__c: Field.text({ label: 'Region' }) }, + // The whole field arrangement: the two groups swapped, `status` moved to `contact`. + fieldGroups: [ + { key: 'contact', label: 'Contact', fields: ['email', 'phone', 'status'] }, + { key: 'basic', label: 'Basics', fields: ['name', 'company', 'region__c'] }, + ], + // The whole tab list: events before tasks, the notes tab hidden. + relatedLists: ['crm_event', 'crm_task', { list: 'crm_note', hidden: true }], +}); +``` + +Both keys take the shape an object declares them in ([field groups](/docs/data-modeling/objects), +`relatedLists`), and a group may list any field the object has, whoever declares it: the +vendor's, another package's extension's, the pair's own `__c` fields. A group's +`relatedList` may place any body table. + +- **Each key replaces, whole.** Written, `fieldGroups` replaces the groups the owner + declares and the other extensions' `place` entries add to; `relatedLists` replaces the + tab list the same way. Nothing is merged entry by entry. A key the extension does not + write keeps the owner's arrangement with the placements, so writing only `relatedLists` + leaves the field groups alone. +- **A field the arrangement does not list is never dropped.** It shows after the last + group, whatever group its owner or another extension had put it in: a field a later + version of the base adds, or one a package installed later brings, appears there until + the arrangement lists it. A group that lists `fields` shows exactly its list. +- **A tab the arrangement does not name still shows, after the listed ones.** That is the + reverse of an object's own `relatedLists`, where leaving a list out hides it. Hiding is + written: `{ list: 'crm_note', hidden: true }` hides that list's tab, whichever package + brings the list, and a bare child name hides every list of that child. `hidden` is + accepted only here; an object's own `relatedLists` refuses it. A list the object's owner + hides by leaving it out of its own `relatedLists` stays hidden until the arrangement + names it. The three built-in tabs are written as their bare names and keep their own + rules; they are not hidden here. +- **A reader's own tab order comes on top.** Each person's dragged order and hidden tabs + (kept per user) are laid over this list, as they are over an object's. A tab the + environment hides is not offered to them. +- **Taking it away restores the page.** Remove a key, or uninstall or disable the pair, + and the owner's arrangement with the placements is served again. Nothing is rewritten in + the base or in another package. +- **Only the pair writes these keys.** In a package that is not a `.custom` package they + are refused at save and publish, by `os validate` and `os build`, and at install, with + the prescription to use `place`. Within one extension, a `place` entry beside the key + that would replace it is refused too: list the item in the arrangement instead. +- **The pair is the App's.** An object's pair is the `.custom` package of the App the + object belongs to: for an object a module of an App owns, that is the App's pair. A + `.custom` package an earlier version created for the module itself is still read while + it is installed; where both write a key, the App's pair is served. What any other + `.custom` package writes under these keys is not refused at those doors; it is not + applied, alone or beside the pair, and the boot log names the package and the object. +- **Hiding a field is written in the arrangement.** `hidden` is not a display property a + `fieldPatches` entry may set: a hidden field is also left out of the search index and + out of a form's required check, so it is more than display. To keep a vendor field off + the record page and the forms, list it in a group whose `visibleWhen` is false: + `{ key: 'off_page', label: 'Not shown', fields: ['fax'], visibleWhen: 'false' }`. + Two limits: + - **It is presentation only, not access control.** The field stays readable and writable + through the API. + - **Do not use it for a `required` field that has no default.** The create form no + longer shows the field while the save still requires it, so the form cannot be + submitted: the save is refused naming a field the user cannot see. + --- ## Merge order and conflicts diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 0f8f3a27aa2..1a7f886fc7f 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -1,7 +1,7 @@ --- title: Object schema — Data Protocol reference navTitle: Object -description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOperation, Index and 19 more — each property with its type, default and a TypeScript example." +description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOperation, Index and 21 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOpe ## TypeScript Usage ```typescript -import { ApiMethod, ApiOperationSchema, IndexSchema, LifecycleSchema, LifecycleClassSchema, ObjectSchema, ObjectAccessConfigSchema, ObjectCapabilities, ObjectExtensionSchema, ObjectExtensionFieldPlacementSchema, ObjectExtensionGroupPlacementSchema, ObjectExtensionListPlacementSchema, ObjectExtensionPlacementSchema, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RelatedListEntrySchema, RelatedListEntryObjectSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; -import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, ObjectExtensionFieldPlacement, ObjectExtensionGroupPlacement, ObjectExtensionListPlacement, ObjectExtensionPlacement, ObjectExternalBinding, ObjectFieldGroup, ObjectRequiredPermissions, PerOperationRequiredPermissions, RelatedListEntry, RelatedListEntryObject, RowCrudActionOverride, TenancyConfig } from '@objectstack/spec/data'; +import { ApiMethod, ApiOperationSchema, IndexSchema, LifecycleSchema, LifecycleClassSchema, ObjectSchema, ObjectAccessConfigSchema, ObjectCapabilities, ObjectExtensionSchema, ObjectExtensionFieldPlacementSchema, ObjectExtensionGroupPlacementSchema, ObjectExtensionListPlacementSchema, ObjectExtensionPlacementSchema, ObjectExtensionRelatedListEntrySchema, ObjectExtensionRelatedListEntryObjectSchema, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RelatedListEntrySchema, RelatedListEntryObjectSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; +import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, ObjectExtensionFieldPlacement, ObjectExtensionGroupPlacement, ObjectExtensionListPlacement, ObjectExtensionPlacement, ObjectExtensionRelatedListEntry, ObjectExtensionRelatedListEntryObject, ObjectExternalBinding, ObjectFieldGroup, ObjectRequiredPermissions, PerOperationRequiredPermissions, RelatedListEntry, RelatedListEntryObject, RowCrudActionOverride, TenancyConfig } from '@objectstack/spec/data'; // Validate data const result = ApiMethod.parse(data); @@ -619,6 +619,8 @@ const result = ApiMethod.parse(data); | **validations** | `any[]` | optional | Additional validation rules to merge into the target object | | **indexes** | `{ name?: string; fields: string[]; unique?: false \| 'global' \| 'organization' }[]` | optional | Additional indexes to merge into the target object | | **place** | `({ field: string; group: string; after?: string; before?: string } \| { list: string; after?: string; before?: string; label?: string; … } \| { group: object; after?: string; before?: string })[]` | optional | Where the fields, groups and child lists this extension brings go on the extended object. Each entry is one of: `{ field, group, after \| before }` — a field of this extension's own `fields`, into a field group (the extended object's, or one this extension adds), right after or before a member of that group; `{ group: { key, label, … }, after \| before }` — a field group of this extension's own (its `fields` may name only fields this extension adds, its `relatedList` only a child list of this package), right after or before a group of the extended object; `{ list, after \| before, label?, columns? }` — a child list of this package (a child object of the same package that points at the extended object, or object.field), right after or before a tab of the extended object (a relatedLists entry name, a built-in tab included), with that tab's own title and columns (each column a field of the child, judged as a relatedLists entry's columns are). Write `after` or `before`, or neither for the end. An anchor may be an item another placement brings, whatever order the two are written or registered in. An anchor nobody has puts the item at the end of its group, of the groups, or of the tabs (before the approvals and activity-stream tabs); a group that does not exist puts the field among the ungrouped fields. Nothing is dropped. Several items at one anchor follow ascending `priority`, then package name, so every build gives the same order. Placement arranges what the extended object declares: list placements apply when it declares `relatedLists`, group and field placements when it declares `fieldGroups`. Where it declares none, its automatic arrangement stays as it is and the item still shows there: the list in the automatic tab order, with this entry's `label` and `columns` not applied either (write them on the child's own lookup field as `relatedListTitle` / `relatedListColumns`, which apply on every parent), and the field among the fields in declaration order, its `after` / `before` not applied. The boot log names each placement that did not apply, with the object and the package; `os validate` names it too when the extended object is in the same stack. A child list another package brings shows even when the extended object's `relatedLists` does not name it: placed, at its place; unplaced, at the end of the tabs. An extension places only its own items: a field outside its own `fields` is refused here; a field the extended object declares (an owner field this extension redeclares for its display is still the owner's), a group key the extended object declares, and a list (or a group's `relatedList`) that is not a child object of its package are refused at `defineStack` where the objects are known; the merge skips each of them too, with a warning naming whose item it is. A group key another package's extension already adds is not refused: the merge adds it once and names the second. Applied once, by the registry merge, so the record page, the forms and Studio show one arrangement; uninstalling the package removes its items and leaves the extended object's own order as it was. Example: `place: [{ field: 'tax_id', group: 'basic', after: 'industry' }, { list: 'contract', after: 'opportunity', columns: ['name', 'amount'] }]`. | +| **fieldGroups** | `{ key: string; label: string; fields?: string[]; icon?: string; … }[]` | optional | The whole field arrangement of the extended object on the record page, the forms and the preview: an object's `fieldGroups`, in the same shape. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, with the prescription to place what it brings with `place`, and the registry merge skips it with a warning. A `.custom` package that is not this object's pair is not refused at those doors: the registry merge does not apply what it writes here, alone or beside the pair, and the boot log names it. A group may list any field the object has, whoever declares it (its owner, another package's extension, or this extension's own `__c` fields), and a group's `relatedList` may place any body table. Written, it replaces the groups the owner declares and the other extensions' `place` entries add, whole: no group, member or order of that arrangement is kept unless written here, and nothing is merged entry by entry. A group that lists `fields` shows exactly its list. A field no group here lists is never dropped: it shows after the last group, whatever group its owner or another extension had put it in. That covers a field a later version of the base adds and a field another package's extension brings. A group that lists no `fields` keeps the object's older rule (the fields whose `group` names it), and a field this extension adds keeps the `group` it declares. Not written, the arrangement stays as the owner and the `place` entries give it, and removing this key, or uninstalling or disabling the package, restores that. To keep a field off the record page and the forms, list it in a group whose `visibleWhen` is false: `hidden` is not a display property a `fieldPatches` entry may set, because it also changes what search indexes and what a form requires. Such a group is presentation only, not access control: the field stays readable and writable through the API. Do not use it for a `required` field that has no default: the create form no longer shows the field while the save still requires it, so the form cannot be submitted. Example: `fieldGroups: [{ key: 'contact', label: 'Contact', fields: ['email', 'phone', 'region__c'] }, { key: 'basic', label: 'Basics', fields: ['name', 'company'] }]`. | +| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[]; hidden?: boolean })[]` | optional | The whole tab list of the extended object's record page, in order: an object's `relatedLists`, in the same shape, whose object form also takes `hidden`. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, with the prescription to place what it brings with `place`, and the registry merge skips it with a warning. A `.custom` package that is not this object's pair is not refused at those doors: the registry merge does not apply what it writes here, alone or beside the pair, and the boot log names it. An entry may name any list the object has, whoever brings it (a child object, object.field, or a built-in tab; `{ list, label?, columns?, hidden? }` gives the list its own title and columns, or hides it). Written, it replaces the tab list the owner declares and the other extensions' `place` entries add to, whole, and nothing is merged entry by entry. A tab this list does not name is not hidden, the reverse of an object's own `relatedLists`: where the object had a declared tab list, each of its tabs not named here follows the listed ones (before a trailing approvals / activity-stream run), with the title and columns it had; where the object declared none (every list shows), every list not named here follows the listed ones, and so does the attachments tab. That covers a tab a later version of the base adds and a child list a package installed later brings. Hiding is written: `{ list: 'task', hidden: true }` hides that list's tab, whoever brings the list, and a bare child name hides every list of that child. A list the object's own `relatedLists` hides by leaving it out stays hidden until this list names it. A built-in tab is written only as its bare name, keeps its own rule (approvals and the activity stream follow the listed tabs when unlisted) and cannot be hidden here. `relatedList: false` on the child's field still hides a list whatever this says, and body tables a field group places are the groups' to place. A reader's own tab order and hidden tabs (kept per user) are laid over this list, as over an object's. Not written, the tabs stay as the owner and the `place` entries give them, and removing this key, or uninstalling or disabling the package, restores that. Example: `relatedLists: ['opportunity', { list: 'contact', label: 'People' }, { list: 'task', hidden: true }]`. | | **priority** | `integer` | optional (default: `200`) | Merge priority (higher = applied later) | ### Nested Shape: `ObjectExtension.fields[string]` @@ -757,6 +759,32 @@ const result = ApiMethod.parse(data); | **after** | `string` | optional | Place it right after this group of the extended object (a group key). | | **before** | `string` | optional | Place it right before this group. Write `after` or `before`, not both. | +### Nested Shape: `ObjectExtension.fieldGroups[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **key** | `string` | ✅ | Group machine key (snake_case). Referenced by Field.group, and by a layout section's `group`. | +| **label** | `string` | ✅ | Group display label | +| **fields** | `string[]` | optional | The group's members in display order (field names of this object). Written, it decides which fields the group shows and their order on the record page and the forms, without changing the order of the object's fields. Absent, members are the fields whose `group` names this group, in field declaration order (the older spelling, still read). A field whose `group` names this group but that the list does not name follows the listed ones. Refused: a listed field whose own `group` names another group, a field two groups list, a repeated name, and `fields` on a group with `relatedList`. A name the object does not declare is skipped. | +| **icon** | `string` | optional | Icon name (Lucide/Material) for the group header | +| **description** | `string` | optional | Optional description shown under the group header | +| **relatedList** | `string` | optional | Places a related list's body table at this position in the record's details column instead of a section of fields: names one inbound relationship, as a relatedLists entry does (child object, or object.field when that child has more than one relationship to this object). A group with relatedList holds no fields: a field that names it as its group is refused, and so is a fields list on it. The name is judged as a relatedLists entry is: refused when its child is in the stack with no inbound lookup / master_detail field, or exists nowhere (by os validate / os build, which leave a sys_ / cloud_ / ai_ name to the runtime, and by a metadata write that names no package); a write into a package stores it, and the record page places nothing for it. It names a body table only (a FK declaring relatedList: 'primary', or a master_detail FK that declares no relatedList, which is a tab unless a group places it; placed, it is drawn here, and the parent's entry form inlines it here too, or below its fields when the form's sections name no field group): a group naming a side card or a list hidden by relatedList: false draws nothing, so it is refused where the child's fields are known (os validate / os build and the metadata write door), naming the FK and the remedy (set relatedList: 'primary' on it, name only the body table as object.field when a bare child name also names a side card, or remove the group's relatedList). | +| **visibleWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Section visibility predicate (CEL) — the whole group (header included) is shown only when TRUE, else hidden (fail-closed). e.g. P`record.type == 'invoice'` | +| **requiresFeature** | `Enum<'twoFactor' \| 'organization' \| 'multiOrgEnabled' \| 'degradedTenancy' \| …>` | optional | Deployment feature flag gating this group, from the same set an action's `requiresFeature` names (e.g. 'multiOrgEnabled'). Lowered at parse time into the group's `visibleWhen` (AND-composed after an authored `visibleWhen`) and stripped from the output; the whole group is hidden where the flag is off. Presentation only: the fields stay readable through the API. | +| **collapse** | `Enum<'none' \| 'expanded' \| 'collapsed'>` | optional (default: `"none"`) | [ADR-0085] Section collapse behaviour: 'none' (always open, no toggle), 'expanded' (collapsible, starts open), 'collapsed' (collapsible, starts closed). | +| **defaultExpanded** | `boolean` | optional | [DEPRECATED → collapse] true → 'expanded', false → 'collapsed'. | +| **collapsible** | `boolean` | optional | [DEPRECATED → collapse] Boolean pair with `collapsed`; use the `collapse` enum. | +| **collapsed** | `boolean` | optional | [DEPRECATED → collapse] true → 'collapsed' (collapsible, starts closed) on its own — it needs no `collapsible` and outranks `collapsible: false`; false → 'none', or 'expanded' beside `collapsible: true`. Use the `collapse` enum. | + +### Nested Shape: `ObjectExtension.relatedLists[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The relationship this entry names: a child object name (e.g. "quote_line"), or object.field when that child has more than one relationship to this object. | +| **label** | `string` | optional | This list's title on the record page (its tab and its table heading). Wins over the child FK's relatedListTitle; absent = that key, else the child object's plural label. | +| **columns** | `string[]` | optional | This list's columns, as field names of the child object (e.g. ['product', 'quantity', 'amount']). Wins over the child FK's relatedListColumns; absent = that key, else the child object's derived columns. Used wherever this list is drawn: its tab, and the body table a field group places. A name that is no field of the child is refused where the child is known. | +| **hidden** | `boolean` | optional | true = this list's tab is not shown on the record page (and a reader's own arrangement cannot bring it back); absent or false = shown at this entry's position. The one way the paired `.custom` arrangement hides a tab: a tab it does not name still shows, after the listed ones. A built-in tab is written only as its bare name and is not hidden here. | + --- @@ -882,6 +910,48 @@ This schema accepts one of the following structures: --- +--- + +## ObjectExtensionRelatedListEntry + +### Union Options + +This schema accepts one of the following structures: + +#### Option 1 + +Type: `string` + +--- + +#### Option 2 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The relationship this entry names: a child object name (e.g. "quote_line"), or object.field when that child has more than one relationship to this object. | +| **label** | `string` | optional | This list's title on the record page (its tab and its table heading). Wins over the child FK's relatedListTitle; absent = that key, else the child object's plural label. | +| **columns** | `string[]` | optional | This list's columns, as field names of the child object (e.g. ['product', 'quantity', 'amount']). Wins over the child FK's relatedListColumns; absent = that key, else the child object's derived columns. Used wherever this list is drawn: its tab, and the body table a field group places. A name that is no field of the child is refused where the child is known. | +| **hidden** | `boolean` | optional | true = this list's tab is not shown on the record page (and a reader's own arrangement cannot bring it back); absent or false = shown at this entry's position. The one way the paired `.custom` arrangement hides a tab: a tab it does not name still shows, after the listed ones. A built-in tab is written only as its bare name and is not hidden here. | + +--- + + +--- + +## ObjectExtensionRelatedListEntryObject + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The relationship this entry names: a child object name (e.g. "quote_line"), or object.field when that child has more than one relationship to this object. | +| **label** | `string` | optional | This list's title on the record page (its tab and its table heading). Wins over the child FK's relatedListTitle; absent = that key, else the child object's plural label. | +| **columns** | `string[]` | optional | This list's columns, as field names of the child object (e.g. ['product', 'quantity', 'amount']). Wins over the child FK's relatedListColumns; absent = that key, else the child object's derived columns. Used wherever this list is drawn: its tab, and the body table a field group places. A name that is no field of the child is refused where the child is known. | +| **hidden** | `boolean` | optional | true = this list's tab is not shown on the record page (and a reader's own arrangement cannot bring it back); absent or false = shown at this entry's position. The one way the paired `.custom` arrangement hides a tab: a tab it does not name still shows, after the listed ones. A built-in tab is written only as its bare name and is not hidden here. | + + --- ## ObjectExternalBinding diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 20e02b73e95..2e98af49095 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1711 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1713 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 14 | 84 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | -| [Data Protocol](/docs/references/data) | 35 | 195 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **219** | **1711** | 14 protocol modules | +| **Total** | **219** | **1713** | 14 protocol modules | --- @@ -140,7 +140,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 195 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 197 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -173,7 +173,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`hook-body.zod.ts`](/docs/references/data/hook-body) | `ExpressionBody`, `HookBody`, `HookBodyCapability`, `ScriptBody` | | [`hook-body-doors.zod.ts`](/docs/references/data/hook-body-doors) | `BodyActivityAppendInput`, `BodyDoorRecordRef`, `BodyMailSendInput` | | [`mapping.zod.ts`](/docs/references/data/mapping) | `ImportFieldMapping`, `Mapping`, `TransformType` | -| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExtensionFieldPlacement`, `ObjectExtensionGroupPlacement`, `ObjectExtensionListPlacement`, `ObjectExtensionPlacement`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RelatedListEntry`, `RelatedListEntryObject`, `RowCrudActionOverride`, `TenancyConfig` | +| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExtensionFieldPlacement`, `ObjectExtensionGroupPlacement`, `ObjectExtensionListPlacement`, `ObjectExtensionPlacement`, `ObjectExtensionRelatedListEntry`, `ObjectExtensionRelatedListEntryObject`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RelatedListEntry`, `RelatedListEntryObject`, `RowCrudActionOverride`, `TenancyConfig` | | [`picklist.zod.ts`](/docs/references/data/picklist) | `Picklist`, `PicklistExtension`, `PicklistServedField` | | [`query.zod.ts`](/docs/references/data/query) | `AggregationFunction`, `AggregationNode`, `DateGranularity`, `FieldNode`, `FullTextSearch`, `GroupByNode`, `Query`, `SortNode` | | [`recycle-bin.zod.ts`](/docs/references/data/recycle-bin) | `RecycleBinClearedReference`, `RecycleBinEntry`, `RecycleBinRetentionDays`, `RecycleBinRetentionDaysEnv`, `RecycleBinSnapshot`, `RecycleBinSnapshotRow` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md index 2219905351d..16f509d22ee 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `data/` | 183 | 114 | 2 | 0 | 67 | +| `data/` | 184 | 115 | 2 | 0 | 67 | ## `data/` — sites @@ -54,7 +54,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `hook-body.zod.ts` | 2 | | `hook.zod.ts` | 7 | | `mapping.zod.ts` | 8 | -| `object.zod.ts` | 30 | +| `object.zod.ts` | 31 | | `picklist.zod.ts` | 3 | | `query.zod.ts` | 5 | | `recycle-bin.zod.ts` | 4 | @@ -62,7 +62,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `seed-loader.zod.ts` | 12 | | `seed.zod.ts` | 2 | | `validation.zod.ts` | 6 | -| **total** | **183** | +| **total** | **184** | ## `data/` — open @@ -70,7 +70,7 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**67 strip of 183**, in 11 file(s). +**67 strip of 184**, in 11 file(s). | File | Strip | Sites | |---|---|---| @@ -85,7 +85,7 @@ over it is here. | `query.zod.ts` | 3 | 5 | | `recycle-bin.zod.ts` | 4 | 4 | | `seed-loader.zod.ts` | 12 | 12 | -| **total** | **67** | **183** | +| **total** | **67** | **184** | | Bucket | Sites | |---|---| diff --git a/packages/cli/src/commands/compile.ts b/packages/cli/src/commands/compile.ts index f821f9eef89..85a20a6666e 100644 --- a/packages/cli/src/commands/compile.ts +++ b/packages/cli/src/commands/compile.ts @@ -96,6 +96,10 @@ import { findOverrideDeclarationRefusals } from '../utils/override-declarations. // `os validate` step 3a-iv runs, over the save and install doors' own judge // (`judgeExtensionFieldSuffix`). import { findExtensionFieldSuffixRefusals } from '../utils/extension-field-suffix.js'; +// [ADR-0146 D10] …and the arrangement of an extended object, the paired +// `.custom` package's alone: the same walk and the same doors' judge +// (`judgeExtensionArrangement`). +import { findExtensionArrangementRefusals } from '../utils/extension-arrangement.js'; // [#29051] An undeclared top-level flow cycle — the walk `os validate` step // 3a-vii runs, over the automation engine's own judge. @@ -935,6 +939,28 @@ export default class Compile extends Command { this.exit(1); } + // 3b-iii-bis-2. [ADR-0146 D10] An extended object's whole arrangement + // is the paired `.custom` package's, at build time — the SAME call + // `os validate` makes at its step 3a-iv-bis + // (`judgeExtensionArrangement`): `fieldGroups` or `relatedLists` on + // an `objectExtensions` entry of any other package is refused, with + // the prescription naming `place`, and no artifact is written. + const arrangementRefusals = findExtensionArrangementRefusals(result.data as Record); + if (arrangementRefusals.length > 0) { + if (flags.json) { + await emitJson({ success: false, errors: arrangementRefusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true }); + this.exit(1); + } + const n = arrangementRefusals.length; + console.log(''); + printError(`${n} object extension key${n > 1 ? 's declare' : ' declares'} an arrangement only a paired \`.custom\` package declares (ADR-0146 D10)`); + printBulletList( + arrangementRefusals.map((r) => `${r.path} [${r.code}] ${r.message}`), + { noun: 'extension-arrangement refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 3b-iii-ter. [#28893] Flow region shape (ADR-0031) is judged by the // rule table at step 3b since #29049 (`flow-region-shape-invalid`), // the same verdict `os validate` and `os lint` give. diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts index 41273c34e09..20319d8093e 100644 --- a/packages/cli/src/commands/validate.ts +++ b/packages/cli/src/commands/validate.ts @@ -91,6 +91,7 @@ import { findNamespaceAddressLiteralRefusals } from '../utils/namespace-address- // door's own judge, walked over the artifact's packages. import { findOverrideDeclarationRefusals } from '../utils/override-declarations.js'; import { findExtensionFieldSuffixRefusals } from '../utils/extension-field-suffix.js'; +import { findExtensionArrangementRefusals } from '../utils/extension-arrangement.js'; // [ADR-0146 D10, second rule] The field-patch target check's walk; the verdict // is the marketplace install door's own judge. import { findFieldPatchTargetRefusals } from '../utils/field-patch-targets.js'; @@ -885,6 +886,34 @@ export default class Validate extends Command { this.exit(1); } + // 3a-iv-bis. [ADR-0146 D10] An extended object's whole arrangement is + // the paired `.custom` package's, at author time: `fieldGroups` or + // `relatedLists` on an `objectExtensions` entry of any other package + // is refused, with the prescription naming `place`. The verdict is + // the save and install doors' own (`judgeExtensionArrangement`); see + // `utils/extension-arrangement.ts`. + const arrangementRefusals = findExtensionArrangementRefusals(result.data as Record); + if (arrangementRefusals.length > 0) { + if (flags.json) { + await emitJson({ + valid: false, + errors: arrangementRefusals, + warnings: warningsSoFar(), + conversions: conversionNotices, + duration: timer.elapsed(), + }); + this.exit(1); + } + const n = arrangementRefusals.length; + console.log(''); + printError(`${n} object extension key${n > 1 ? 's declare' : ' declares'} an arrangement only a paired \`.custom\` package declares (ADR-0146 D10)`); + printBulletList( + arrangementRefusals.map((r) => `${r.path} [${r.code}] ${r.message}`), + { noun: 'extension-arrangement refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 3a-v. [ADR-0146 D10, second rule] The field-patch target check, at // author time: an object extension's `fieldPatches` naming a field // its target does not have, or an option value the field does not diff --git a/packages/cli/src/utils/extension-arrangement.test.ts b/packages/cli/src/utils/extension-arrangement.test.ts new file mode 100644 index 00000000000..124910a2a26 --- /dev/null +++ b/packages/cli/src/utils/extension-arrangement.test.ts @@ -0,0 +1,63 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] `findExtensionArrangementRefusals` — what `os validate` and + * `os build` hand the arrangement judge. + * + * The verdict is `@objectstack/metadata-protocol`'s `judgeExtensionArrangement`, + * the one the save and install doors ask; the protocol's own file pins its + * sentence. What is pinned here is which packages the walk hands it and under + * which id: each `packages[]` entry under its own, or the stack itself under + * `manifest.id`, every row's message EQUAL to the judge's for the same subject. + */ + +import { describe, expect, it } from 'vitest'; +import { judgeExtensionArrangement } from '@objectstack/metadata-protocol'; +import { findExtensionArrangementRefusals } from './extension-arrangement.js'; + +const VENDOR = 'com.acme.partner'; +const PAIR = 'com.acme.crm.custom'; + +const GROUPS = [{ key: 'basic', label: 'Basics', fields: ['name'] }]; +const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; +const extensions = [{ extend: 'crm_account', fieldGroups: GROUPS, relatedLists: TABS }]; + +describe('ADR-0146 D10 — the walk os validate and os build hand the arrangement judge', () => { + it('a stack under a plain id: each arrangement key is refused once under that id, located in the stack', () => { + const rows = findExtensionArrangementRefusals({ manifest: { id: VENDOR }, objectExtensions: extensions }); + const judged = judgeExtensionArrangement({ packageId: VENDOR, objectExtensions: extensions }); + expect(rows).toEqual([ + { path: 'objectExtensions[0].fieldGroups', code: 'VALIDATION_ERROR', key: 'fieldGroups', packageId: VENDOR, message: judged[0]!.message }, + { path: 'objectExtensions[0].relatedLists', code: 'VALIDATION_ERROR', key: 'relatedLists', packageId: VENDOR, message: judged[1]!.message }, + ]); + expect(rows[0]!.message).toContain('`place`'); + }); + + it('CONTROL: the same stack under its `.custom` id is admitted', () => { + expect(findExtensionArrangementRefusals({ manifest: { id: PAIR }, objectExtensions: extensions })).toEqual([]); + }); + + it('CONTROL: a plain stack that writes neither key is admitted', () => { + expect(findExtensionArrangementRefusals({ + manifest: { id: VENDOR }, + objectExtensions: [{ extend: 'crm_account', fields: { tier: { type: 'text' } }, place: [{ field: 'tier', group: 'basic' }] }], + })).toEqual([]); + }); + + it('a `packages[]` artifact: each entry is judged under its own id, located under its entry', () => { + const rows = findExtensionArrangementRefusals({ + manifest: { id: 'com.acme.bundle' }, + packages: [ + { manifest: { id: PAIR, objectExtensions: extensions } }, + { manifest: { id: VENDOR, objectExtensions: [{ extend: 'crm_account', relatedLists: TABS }] } }, + ], + }); + expect(rows.map((r) => [r.path, r.packageId])).toEqual([ + ['packages[1].manifest.objectExtensions[0].relatedLists', VENDOR], + ]); + }); + + it('a stack naming no package id is not judged', () => { + expect(findExtensionArrangementRefusals({ objectExtensions: extensions })).toEqual([]); + }); +}); diff --git a/packages/cli/src/utils/extension-arrangement.ts b/packages/cli/src/utils/extension-arrangement.ts new file mode 100644 index 00000000000..518f3ee3bb7 --- /dev/null +++ b/packages/cli/src/utils/extension-arrangement.ts @@ -0,0 +1,52 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0146 D10 — an extended object's whole arrangement is the paired + * `.custom` package's, at `os validate` and `os build`. + * + * The verdict is `@objectstack/metadata-protocol`'s `judgeExtensionArrangement`, + * the one the save, restore, publish and install doors ask, so a green + * validate is an artifact those doors admit: `fieldGroups` and `relatedLists` + * on an `objectExtensions` entry only in a base's paired `.custom` package; + * any other package places what it brings with `place`. This module only + * hands it the artifact's packages, the reading + * `findExtensionFieldSuffixRefusals` (`./extension-field-suffix.ts`) takes. A + * stack naming no package id is not judged, as the judge skips a write bound + * to no package. + */ + +import { judgeExtensionArrangement } from '@objectstack/metadata-protocol'; + +import { artifactPackages } from './artifact-packages.js'; + +/** One refused arrangement key, located. `message` is the doors' sentence, verbatim. */ +export interface ExtensionArrangementRefusalRow { + /** Where the key sits in the parsed stack, e.g. `packages[1].manifest.objectExtensions[0].fieldGroups`. */ + path: string; + /** The code the active doors refuse the same key with. */ + code: 'VALIDATION_ERROR'; + /** The key as written: `fieldGroups` or `relatedLists`. */ + key: string; + /** The package the extension is declared in. */ + packageId: string; + message: string; +} + +const isRecord = (v: unknown): v is Record => + v !== null && typeof v === 'object' && !Array.isArray(v); + +/** Every arrangement key of the parsed stack the rule refuses. */ +export function findExtensionArrangementRefusals(parsed: Record): ExtensionArrangementRefusalRow[] { + const entries = artifactPackages(parsed); + const subjects = entries.length > 0 + ? entries.map(({ index, id, body }) => ({ + packageId: id, objectExtensions: body.objectExtensions, at: `packages[${index}].manifest.`, + })) + : [{ + packageId: isRecord(parsed.manifest) ? (parsed.manifest.id as string | undefined) : undefined, + objectExtensions: parsed.objectExtensions, + }]; + return subjects.flatMap((subject) => judgeExtensionArrangement(subject).map((r) => ({ + path: r.path, code: 'VALIDATION_ERROR' as const, key: r.key, packageId: r.packageId, message: r.message, + }))); +} diff --git a/packages/cli/test/validate-build-extension-arrangement.test.ts b/packages/cli/test/validate-build-extension-arrangement.test.ts new file mode 100644 index 00000000000..6b8922d15b4 --- /dev/null +++ b/packages/cli/test/validate-build-extension-arrangement.test.ts @@ -0,0 +1,167 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] `os validate` and `os build` refuse `fieldGroups` / + * `relatedLists` on the object extension of a package that is not a base's + * paired `.custom`: the save and install doors' own judge + * (`judgeExtensionArrangement`), over the walk `utils/extension-arrangement.ts` + * takes, whose own file pins which packages it judges. + * + * What is pinned here is the two commands: a plain package writing + * `fieldGroups` exits 1 from `os validate` with ONE row, located at the key + * and prescribing `place`; `os build` answers the same rows and the same exit + * code and writes NOTHING to `dist/`. The base's paired `.custom` writing the + * same arrangement validates and builds, and so does the plain package placing + * its field with `place`. Both commands run in-process (`Command.run`), not as + * spawned CLIs. + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import Compile from '../src/commands/compile'; +import Validate from '../src/commands/validate'; +import { defineStackSource, linkSpec } from './helpers/define-stack-fixture.js'; + +// Pay the first transform of the dist-resolved deps `os build` reaches through +// dynamic `import()`s at MODULE LOAD, not inside a clocked case +// (`scripts/check-test-source-alias.mjs`). +import '@objectstack/objectql/core'; +import '@objectstack/plugin-security'; +import '@objectstack/runtime'; + +const CLI_ROOT = resolve(fileURLToPath(import.meta.url), '..', '..'); +const BASE = 'com.acme.crm'; + +interface Run { + /** The exit code `this.exit(n)` threw, or 0 when the command returned. */ + code: number; + stdout: string; +} + +/** Runs one command in-process; stdout captured ANSI-free, the write callback honoured. */ +async function run(command: typeof Compile | typeof Validate, argv: string[]): Promise { + const chunks: string[] = []; + const spy = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, ...rest: unknown[]) => { + chunks.push(String(chunk)); + const done = rest.find((a) => typeof a === 'function') as ((e?: Error | null) => void) | undefined; + done?.(null); + return true; + }) as never); + const exitCodeBefore = process.exitCode; + let code = 0; + try { + await command.run(argv, { root: CLI_ROOT }); + } catch (error) { + const exit = (error as { oclif?: { exit?: unknown } }).oclif?.exit; + if (typeof exit !== 'number') throw error; + code = exit; + } finally { + spy.mockRestore(); + process.exitCode = exitCodeBefore; + } + // eslint-disable-next-line no-control-regex + return { code, stdout: chunks.join('').replace(/\u001b\[[0-9;]*m/g, '') }; +} + +const json = (r: Run, label: string): Record => { + try { + return JSON.parse(r.stdout) as Record; + } catch { + throw new Error(`${label}: stdout was not one JSON document (exit ${r.code})\n${r.stdout}`); + } +}; + +/** A package `id` extending the base's `crm_account` with one field, its extension body carrying `extra`. */ +const extending = (id: string, namespace: string, field: string, extra: Record): Record => ({ + manifest: { id, name: 'ext', version: '1.0.0', type: 'app', namespace, dependencies: { [BASE]: '^1.0.0' } }, + objectExtensions: [{ extend: 'crm_account', fields: { [field]: { type: 'text', label: 'Region' } }, ...extra }], +}); + +const GROUPS = (field: string) => [{ key: 'basic', label: 'Basics', fields: ['name', field] }]; +const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; + +let root = ''; +const fixtures: Record = {}; + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'os-extension-arrangement-')); + const make = (label: string, s: Record) => { + const dir = join(root, label); + mkdirSync(dir, { recursive: true }); + // `strict: false`: the content is the door's to judge, not the producer's. + writeFileSync(join(dir, 'objectstack.config.ts'), defineStackSource(s, { strict: false })); + linkSpec(dir); + fixtures[label] = { + config: join(dir, 'objectstack.config.ts'), + dist: join(dir, 'dist'), + artifact: join(dir, 'dist', 'objectstack.json'), + }; + }; + make('vendorGroups', extending('com.acme.partner', 'partner', 'region', { fieldGroups: GROUPS('region') })); + make('vendorTabs', extending('com.acme.partner', 'partner', 'region', { relatedLists: TABS })); + make('vendorPlace', extending('com.acme.partner', 'partner', 'region', { place: [{ field: 'region', group: 'basic' }] })); + make('pair', extending(`${BASE}.custom`, 'crm_custom', 'region__c', { fieldGroups: GROUPS('region__c'), relatedLists: TABS })); +}); + +afterAll(() => { + if (root) rmSync(root, { recursive: true, force: true }); +}); + +const build = (label: string, ...flags: string[]) => + run(Compile, [fixtures[label].config, '--output', fixtures[label].artifact, ...flags]); +const validate = (label: string, ...flags: string[]) => run(Validate, [fixtures[label].config, ...flags]); + +describe('ADR-0146 D10 — os validate and os build refuse an arrangement outside the paired `.custom` package', () => { + it.each([ + ['vendorGroups', 'fieldGroups'], + ['vendorTabs', 'relatedLists'], + ])('THE PIN (%s): validate --json exits 1 with one row at `%s`, prescribing `place`; build answers the same and dist/ stays empty', async (label, key) => { + const validated = await validate(label, '--json'); + expect(validated.code, validated.stdout).toBe(1); + const expected = json(validated, `validate ${label}`).errors as Array>; + expect(expected.map((e) => [e.path, e.code, e.key, e.packageId])).toEqual([ + [`objectExtensions[0].${key}`, 'VALIDATION_ERROR', key, 'com.acme.partner'], + ]); + expect(String(expected[0]!.message)).toContain('`place`'); + + const built = await build(label, '--json'); + const payload = json(built, `build ${label}`); + expect(built.code).toBe(validated.code); + expect(payload.success).toBe(false); + expect(payload.errors).toEqual(expected); + expect(existsSync(fixtures[label].dist), 'os build wrote into dist/ for an artifact the doors refuse').toBe(false); + }, 60_000); + + it('the text face exits 1 and prints the key\'s path with the refusal', async () => { + const validated = await validate('vendorGroups'); + expect(validated.code).toBe(1); + expect(validated.stdout).toContain('objectExtensions[0].fieldGroups [VALIDATION_ERROR]'); + expect(validated.stdout).toContain('`place`'); + + const built = await build('vendorGroups'); + expect(built.code).toBe(1); + expect(built.stdout).toContain('objectExtensions[0].fieldGroups [VALIDATION_ERROR]'); + expect(built.stdout).not.toContain('Build complete'); + expect(existsSync(fixtures.vendorGroups.dist)).toBe(false); + }, 60_000); + + it('CONTROL: the same package placing its field with `place` validates clean and builds', async () => { + expect((await validate('vendorPlace', '--json')).code).toBe(0); + const built = await build('vendorPlace', '--json'); + expect(json(built, 'build vendorPlace').success, built.stdout).toBe(true); + }, 60_000); + + it('CONTROL: the base\'s paired .custom writing both keys validates clean and builds, the keys in the artifact', async () => { + const validated = await validate('pair', '--json'); + expect(validated.code, validated.stdout).toBe(0); + const built = await build('pair', '--json'); + const payload = json(built, 'build pair'); + expect(payload.success, JSON.stringify(payload.errors ?? payload.error)).toBe(true); + const artifact = JSON.parse(readFileSync(fixtures.pair.artifact, 'utf8')) as Record; + expect(artifact.objectExtensions[0].fieldGroups.map((g: any) => g.key)).toEqual(['basic']); + expect(artifact.objectExtensions[0].relatedLists).toEqual(TABS); + }, 60_000); +}); diff --git a/packages/cli/test/validate-build-gate-parity.test.ts b/packages/cli/test/validate-build-gate-parity.test.ts index e2ee274b440..42ce7ba6a3f 100644 --- a/packages/cli/test/validate-build-gate-parity.test.ts +++ b/packages/cli/test/validate-build-gate-parity.test.ts @@ -216,6 +216,15 @@ const SHARED_NON_REGISTRY_GATES: readonly string[] = [ // (#28727), so the row moved here — deleted there rather than reworded, for // the reason the `runPerPackageAuthoringRules` row above gives. 'findExtensionFieldSuffixRefusals', + // [ADR-0146 D10] An extended object's whole arrangement is the paired + // `.custom` package's: `fieldGroups` or `relatedLists` on an + // `objectExtensions` entry of any other package, judged by the save and + // install doors' own `judgeExtensionArrangement`. Not a registry rule, for + // the reason the row above gives: the verdict turns on the id of the + // package the extension is declared in, which the union stack a registry + // rule is handed does not carry. Both doors make the call, beside the + // `__c` reservation's. + 'findExtensionArrangementRefusals', // [#29051] An undeclared cycle in a flow's top-level graph (ADR-0044), // judged by the automation engine's own registration judge // (`findUndeclaredFlowCycle`, `@objectstack/metadata-core`), which the diff --git a/packages/cloud-connection/src/marketplace-install-local-extension-arrangement.test.ts b/packages/cloud-connection/src/marketplace-install-local-extension-arrangement.test.ts new file mode 100644 index 00000000000..f23c540fa25 --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-extension-arrangement.test.ts @@ -0,0 +1,221 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] Step 1c-arrangement of `POST /api/v1/marketplace/install-local` + * — an extended object's whole arrangement is the paired `.custom` package's, + * judged at the marketplace install beside the `__c` reservation, before the + * manifest service sees the artifact. + * + * The verdict is `@objectstack/metadata-protocol`'s `judgeExtensionArrangement`, + * the save door's own; its sentence is pinned in that package. What is pinned + * here is the door: + * + * - a plain package whose extension writes `fieldGroups` (or `relatedLists`) + * stops the install `422 VALIDATION_ERROR` (this door's existing body + * refusal), one row per key in `details.refusals`, prescribing `place`, + * before any write: nothing registered, no ledger entry; + * - each `packages[]` entry is judged under its own id; + * - the refusal comes before the install-mode judgement; + * - the `.custom` pair's arrangement installs (into its writable pair), and + * so does a vendor extension that places what it brings with `place`. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +// The install binds the package's handlers through `@objectstack/runtime` (a +// lazy `import()` inside the plugin); its first load is paid here, at module +// top — never inside a clocked `it` (`scripts/check-test-source-alias.mjs`). +import '@objectstack/runtime'; +import { judgeExtensionArrangement } from '@objectstack/metadata-protocol'; +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; +import { installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; + +type Handler = (c: any) => Promise; + +const ROUTE = 'POST /api/v1/marketplace/install-local'; +const BASE = 'com.acme.crm'; +const PAIR = 'com.acme.crm.custom'; +const PARTNER = 'com.acme.partner'; + +const deps = (...ids: string[]) => Object.fromEntries(ids.map((id) => [id, '*'])); + +/** What each installed package holds, as the protocol's per-package listing answers it. */ +type Holdings = Record>>>; + +function makeRawApp() { + const routes = new Map(); + return { + routes, + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), + delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h), + }; +} + +/** + * A kernel whose registry holds `installed` (BASE read-only — a code or + * marketplace package is in `manifests`) and whose protocol lists `holdings`. + */ +function makeCtx(rawApp: any, installed: Array<{ id: string; dependencies?: Record }>, holdings: Holdings) { + const hooks = new Map(); + const registered: any[] = []; + const saved: Array<[string, string]> = []; + // [ADR-0146 D3] BASE declares the namespace its pair's is derived from, + // as `customizationPairManifestRefusal` reads it. + const records = installed.map((p) => ({ + manifest: { id: p.id, version: '1.0.0', ...(p.id === BASE ? { namespace: 'crm' } : {}), ...(p.dependencies ? { dependencies: p.dependencies } : {}) }, + })); + const services: Record = { + manifest: { register: (m: any) => registered.push({ manifest: m }) }, + auth: installerAuthService(), + objectql: withInstallerGrants({ + syncSchemas: async () => undefined, + manifests: new Map(installed.some((p) => p.id === BASE) ? [[BASE, {}]] : []), + registry: { + getAllPackages: () => [...records, ...registered], + getPackage: (id: string) => records.find((r) => r.manifest.id === id), + }, + }), + protocol: { + getMetaItems: async ({ type, packageId }: { type: string; packageId?: string }) => ({ + type, + items: (holdings[packageId ?? '']?.[type] ?? []).map((i) => ({ ...i, _packageId: packageId })), + }), + // [ADR-0146 D3] The pair's doors: a pair is installed into its + // writable pair, each item through the save door. + ensureCustomizationPackage: async () => ({ packageId: PAIR, created: true, writable: true }), + saveMetaItem: async ({ type, name }: { type: string; name: string }) => { saved.push([type, name]); return { success: true }; }, + deletePackage: async () => ({ success: true, deletedCount: 0, failedCount: 0 }), + }, + metadata: { get: async () => undefined }, + }; + return { + registered, + saved, + ctx: { + hook: (e: string, h: any) => hooks.set(e, h), + getService: (name: string) => { + if (name === 'http-server') return { getRawApp: () => rawApp }; + const svc = services[name]; + if (svc === undefined) throw new Error(`no ${name}`); + return svc; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }, + fire: async () => { await hooks.get('kernel:ready')?.(); }, + }; +} + +function makeC(body: any) { + const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })); + return { req: { url: 'http://localhost:3000/x', raw: new Request('http://localhost:3000/x'), json: async () => body, param: () => undefined }, json }; +} + +let dir: string; +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-ext-arrangement-')); }); +afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks(); }); + +const BASE_HOLDINGS: Holdings = { + [BASE]: { + dashboard: [{ name: 'crm_board', label: 'Board' }], + object: [{ name: 'crm_account' }], + }, +}; + +async function install( + manifest: Record, + installed: Array<{ id: string; dependencies?: Record }> = [{ id: BASE }], + holdings: Holdings = BASE_HOLDINGS, + extraBody: Record = {}, +) { + const rawApp = makeRawApp(); + const k = makeCtx(rawApp, installed, holdings); + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); + await plugin.start(k.ctx as any); + await k.fire(); + const res = await rawApp.routes.get(ROUTE)!(makeC({ manifest, ...extraBody })); + const registered = k.registered.map((r) => r.manifest.id).filter((id) => id === manifest.id); + return { res, registered, saved: k.saved, ledger: readdirSync(dir) }; +} + +const GROUPS = [{ key: 'basic', label: 'Basics', fields: ['name', 'region__c'] }]; +const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; + +const extension = (extra: Record) => ({ extend: 'crm_account', ...extra }); + +/** The refusal this file pins: the door's envelope and code, every key located, nothing written. */ +function expectRefused(out: Awaited>, expected: ReturnType) { + expect(expected.length).toBeGreaterThan(0); + expect(out.res.status, JSON.stringify(out.res.payload)).toBe(422); + expect(out.res.payload?.success).toBe(false); + expect(out.res.payload?.error?.code).toBe('VALIDATION_ERROR'); + expect(out.res.payload.error.details.refusals).toEqual(expected); + expect(out.res.payload.error.message).toContain(expected[0]!.message); + expect(out.res.payload.error.message).toContain('`place`'); + expect(out.res.payload.error.message).toContain('Nothing was installed or written.'); + expect(out.registered).toEqual([]); + expect(out.ledger).toEqual([]); +} + +describe('install-local 1c-arrangement — an extended object\'s arrangement is the `.custom` pair\'s (ADR-0146 D10)', () => { + it('a plain package whose extension writes `fieldGroups` is refused 422, once, prescribing `place`; nothing is registered', async () => { + const manifest = { id: PARTNER, version: '1.0.0', dependencies: deps(BASE), objectExtensions: [extension({ fieldGroups: GROUPS })] }; + const out = await install(manifest); + expectRefused(out, judgeExtensionArrangement({ packageId: PARTNER, objectExtensions: manifest.objectExtensions })); + expect(out.res.payload.error.details.refusals.map((r: any) => [r.packageId, r.path, r.key])).toEqual([ + [PARTNER, 'objectExtensions[0].fieldGroups', 'fieldGroups'], + ]); + }); + + it('a plain package whose extension writes `relatedLists` is refused too, and both keys are one row each', async () => { + const manifest = { id: PARTNER, version: '1.0.0', dependencies: deps(BASE), objectExtensions: [extension({ fieldGroups: GROUPS, relatedLists: TABS })] }; + const out = await install(manifest); + expectRefused(out, judgeExtensionArrangement({ packageId: PARTNER, objectExtensions: manifest.objectExtensions })); + expect(out.res.payload.error.details.refusals.map((r: any) => r.key)).toEqual(['fieldGroups', 'relatedLists']); + }); + + it('a `packages[]` artifact: each entry is judged under its own id', async () => { + const out = await install({ + id: 'com.acme.bundle', version: '1.0.0', + packages: [ + { manifest: { id: PARTNER, version: '1.0.0', dependencies: deps(BASE), objectExtensions: [extension({ relatedLists: TABS })] } }, + { manifest: { id: PAIR, version: '1.0.0', namespace: 'crm_custom', dependencies: deps(BASE), objectExtensions: [extension({ relatedLists: TABS })] } }, + ], + }); + expect(out.res.status, JSON.stringify(out.res.payload)).toBe(422); + expect(out.res.payload.error.details.refusals.map((r: any) => [r.packageId, r.path])).toEqual([ + [PARTNER, 'objectExtensions[0].relatedLists'], + ]); + expect(out.registered).toEqual([]); + expect(out.ledger).toEqual([]); + }); + + it('is asked before the install-mode judgement, so an `unmanaged` request is refused by it too', async () => { + const manifest = { id: PARTNER, version: '1.0.0', dependencies: deps(BASE), objectExtensions: [extension({ fieldGroups: GROUPS })] }; + expectRefused( + await install(manifest, undefined, undefined, { installMode: 'unmanaged' }), + judgeExtensionArrangement({ packageId: PARTNER, objectExtensions: manifest.objectExtensions }), + ); + }); + + it('CONTROL: the `.custom` pair\'s arrangement installs, and so does a vendor extension that places with `place`', async () => { + const pair = await install({ + id: PAIR, version: '1.0.0', namespace: 'crm_custom', dependencies: deps(BASE), + objectExtensions: [extension({ fields: { region__c: { type: 'text', label: 'Region' } }, fieldGroups: GROUPS, relatedLists: TABS })], + }); + expect(pair.res.status, JSON.stringify(pair.res.payload)).toBe(200); + // [ADR-0146 D3] Into its writable pair, through the save door. + expect(pair.registered).toEqual([]); + expect(pair.saved).toEqual([['object_extension', 'crm_account']]); + + const vendor = await install({ + id: PARTNER, version: '1.0.0', dependencies: deps(BASE), + objectExtensions: [extension({ fields: { tier: { type: 'text', label: 'Tier' } }, place: [{ field: 'tier', group: 'basic' }] })], + }); + expect(vendor.res.status, JSON.stringify(vendor.res.payload)).toBe(200); + expect(vendor.registered).toEqual([PARTNER]); + }); +}); diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index d1ff86838c5..ce597290a6c 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -412,9 +412,11 @@ import { customizationPairManifestRefusal } from '@objectstack/metadata-protocol // [ADR-0146 D2, #28410] The override write gate's one rule and its item walk, // asked at the managed install exactly as the publish doors ask them. import { judgeOverrideWrite, overrideWriteIdentityOf, overrideWriteItemsOf, type OverrideWriteItem, type OverrideWriteRule } from '@objectstack/metadata-protocol'; -// [ADR-0146 D10, #28564] The `__c` extension-field reservation's one judge, step 1c''. +// [ADR-0146 D10, #28564] The `__c` extension-field reservation's one judge, step 1c'', and +// the arrangement judge beside it (step 1c-arrangement). import { judgeExtensionFieldSuffix, + judgeExtensionArrangement, judgeRedeclaredOwnerFields, redeclaredOwnerFieldInstallMessage, type ObjectOwnerDeclaration, @@ -3170,6 +3172,42 @@ export class MarketplaceInstallLocalPlugin implements Plugin { } } + // 1c-arrangement. [ADR-0146 D10] ⭐ THE WHOLE ARRANGEMENT OF AN EXTENDED + // OBJECT is the paired `.custom` package's, judged where the `__c` + // reservation is and for the same reason: before the manifest + // service sees the artifact, so a refused install registers, writes + // and ledgers nothing. Every package this act delivers is judged by + // the save door's judge (`judgeExtensionArrangement`): + // `fieldGroups` or `relatedLists` on an `objectExtensions` entry of + // a package that is not a `.custom` pair is refused, with the + // prescription naming `place`. The answer is this door's own body + // refusal, `VALIDATION_ERROR` / 422, one row per key in + // `details.refusals`. No code is minted. + { + const bodies: Array<{ id: unknown; body: Record }> = Array.isArray(manifest.packages) + ? manifest.packages + .filter((entry: unknown) => isPlainObject(entry) && isPlainObject((entry as any).manifest)) + .map((entry: any) => ({ id: manifestIdOf(entry.manifest), body: flattenPackageBody(entry.manifest) })) + : [{ id: manifestId, body: flattenPackageBody(manifest) }]; + const refusals = bodies.flatMap(({ id, body }) => judgeExtensionArrangement({ + packageId: typeof id === 'string' ? id : undefined, + objectExtensions: body.objectExtensions, + })); + if (refusals.length > 0) { + const n = refusals.length; + return c.json({ + success: false, + error: { + code: UNRUNNABLE_REFUSAL_CODE, + message: `Package '${manifestId}' cannot be installed: ${refusals[0].message}` + + (n > 1 ? ` (${n - 1} more in \`details.refusals\`.)` : '') + + ' Nothing was installed or written.', + details: { refusals }, + }, + }, UNRUNNABLE_REFUSAL_STATUS); + } + } + // 1e. [ADR-0131 D6] ⭐ THE INSTALL MODE — after the payload, id, D3 // walled-catalog and handshake checks and before every other // judgement of the package and any write, because nothing an diff --git a/packages/lint/src/object-graph.ts b/packages/lint/src/object-graph.ts index 7216c756cc7..0ff71210f1b 100644 --- a/packages/lint/src/object-graph.ts +++ b/packages/lint/src/object-graph.ts @@ -396,6 +396,16 @@ export interface VisibleObjectExtension { */ label: unknown; fieldPatches: Record; + /** + * [ADR-0146 D10] Its `fieldGroups` records (`[]` when absent): the whole + * field arrangement the base's paired `.custom` package declares for the + * target. Carried for the one reader that addresses an object's groups by + * key (`validate-translation-references.ts`, `_sections.KEY`); like + * `validations`, carrying them changes nothing about which entries survive. + * Which package may write the key is the arrangement judge's question + * (`os validate` refuses any other writer), not this fold's. + */ + fieldGroups: AnyRec[]; /** * [#33494] Set on an entry the host's registry already holds * ({@link StoredObjectExtension}), folded in at its priority but never @@ -483,6 +493,7 @@ export function objectExtensionsByTarget( priority: typeof ext.priority === 'number' ? ext.priority : 200, fields: recordsOf(ext.fields), validations: recordsOf(ext.validations), + fieldGroups: Array.isArray(ext.fieldGroups) ? ext.fieldGroups.filter(isRec) : [], label: ext.label, fieldPatches: isRec(ext.fieldPatches) ? Object.fromEntries( diff --git a/packages/lint/src/validate-security-posture.test.ts b/packages/lint/src/validate-security-posture.test.ts index 083f0db7afa..6ab6729c4e4 100644 --- a/packages/lint/src/validate-security-posture.test.ts +++ b/packages/lint/src/validate-security-posture.test.ts @@ -2393,7 +2393,9 @@ const READ_SURFACES: Array<{ receiver: string; expected: string[]; declaredBy: s }, { receiver: 'ext', - expected: ['extend', 'fieldPatches', 'fields', 'label', 'priority', 'validations'], + // `fieldGroups` [ADR-0146 D10]: carried by the shared extension fold for + // the translation rule's `_sections` anchors; this rule reads none of it. + expected: ['extend', 'fieldGroups', 'fieldPatches', 'fields', 'label', 'priority', 'validations'], declaredBy: 'ObjectStackSchema.objectExtensions[]', keys: () => shapeKeysOf(ObjectStackSchema.shape.objectExtensions), }, diff --git a/packages/lint/src/validate-translation-references.test.ts b/packages/lint/src/validate-translation-references.test.ts index 0c2ca1addec..bf2dd432553 100644 --- a/packages/lint/src/validate-translation-references.test.ts +++ b/packages/lint/src/validate-translation-references.test.ts @@ -1083,10 +1083,33 @@ describe('validateTranslationReferences — objectExtensions-injected surfaces ( }); /** - * ⛔ The fold reaches `fields.*` and `_validations.*` and no other rung, - * because `ObjectExtensionSchema` reaches no further: an author cannot - * contribute a view, a section, a filter-preset tab or an action through an - * extension at all, so a key for one is an orphan exactly as it was. + * [ADR-0146 D10] The third rung an extension reaches: the base's paired + * `.custom` package declares the target's whole field arrangement + * (`fieldGroups`), and `fieldGroups[].key` is the `_sections` anchor + * (ADR-0085), so a group that arrangement brings is addressable. A section + * no group of the object or of an extension declares is still an orphan. + */ + it('accepts a `_sections` key for a group an extension\'s `fieldGroups` brings, and still reports one nobody declares', () => { + const stack = (sections: Record) => ({ + objects: [{ name: 'crm_lead', label: 'Lead', fields: { name: { type: 'text', label: 'Name' } } }], + objectExtensions: [ + { extend: 'crm_lead', fieldGroups: [{ key: 'reach', label: 'Reach', fields: ['name'] }] }, + ], + translations: [{ 'zh-CN': { objects: { crm_lead: { _sections: sections } } } }], + }); + expect(validateTranslationReferences(stack({ reach: { label: '联系方式' } }))).toEqual([]); + expect(validateTranslationReferences(stack({ zzz_gone: { label: 'x' } })).map((f) => f.path)).toEqual([ + 'translations[0]["zh-CN"].objects.crm_lead._sections.zzz_gone', + ]); + }); + + /** + * ⛔ The fold reaches `fields.*`, `_validations.*` and the `_sections` of a + * `fieldGroups` arrangement, and no other rung, because + * `ObjectExtensionSchema` reaches no further: an author cannot contribute a + * view, a filter-preset tab or an action through an extension at all, and a + * section its `fieldGroups` does not declare is not one either, so a key + * for one is an orphan exactly as it was. */ it('folds no other rung — an extended object still reports its ghost view, section, tab and action', () => { const findings = validateTranslationReferences( @@ -1110,7 +1133,7 @@ describe('validateTranslationReferences — objectExtensions-injected surfaces ( * the SCHEMA, so if `ObjectExtensionSchema` ever accepts one of these keys, * this fails here rather than leaving the rule reporting correct keys for a * surface that has started to exist. Both arms are asserted, so the refusal - * reading is not a dead instrument: the two keys the fold DOES read parse. + * reading is not a dead instrument: the keys the fold DOES read parse. */ it('pins the extension key surface the fold is sized against', () => { const refusedByName = (key: string): boolean => { @@ -1125,7 +1148,9 @@ describe('validateTranslationReferences — objectExtensions-injected surfaces ( 'views:refused', 'listViews:refused', 'actions:refused', - 'fieldGroups:refused', + // [ADR-0146 D10] The paired `.custom` package's arrangement: accepted by + // the schema, and its group keys are folded into `_sections` (above). + 'fieldGroups:accepted', 'sections:refused', 'tabs:refused', 'hooks:refused', diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index bed72caf306..ba86481878f 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -1113,21 +1113,25 @@ function contributedNavItemsByApp(stack: AnyRec): Map { * * `ObjectExtensionSchema` is a `strictObject`, so the fold surface is EXACTLY * its declared keys: `extend`, `priority`, `fields`, `validations`, `indexes`, - * `label`, `pluralLabel`, `description`. Everything else is refused BY NAME at - * the extension level with authoring guidance (`actions`, `listViews`, - * `fieldGroups`, `hooks` carry their own `guidance` text; `views`, `sections` - * and `tabs` fall to the shared unknown-key refusal). Measured against the - * schema rather than read off the merge: each of those seven produced an - * extension-level `unrecognized_keys` issue, while `fields` and `validations` - * parsed. - * - * ⇒ Only TWO of this rule's rungs are reachable through an extension: - * `objects..fields.*` and `objects.._validations.*`. `indexes` is - * not translatable; `label` / `pluralLabel` / `description` are leaf copy on - * an object that already resolved, and this rule checks no leaf. ⛔ Do not - * grow this fold to `_views` / `_sections` / `_tabs` / `_actions` "for - * symmetry": an extension cannot contribute any of them, so a key there is an - * orphan exactly as it was, and widening those rungs would silence real ones. + * `label`, `pluralLabel`, `description`, and the arrangement keys the base's + * paired `.custom` package writes, `fieldGroups` and `relatedLists` + * (ADR-0146 D10). Everything else is refused BY NAME at the extension level + * with authoring guidance (`actions`, `listViews`, `hooks` carry their own + * `guidance` text; `views`, `sections` and `tabs` fall to the shared + * unknown-key refusal). Measured against the schema rather than read off the + * merge: each of those six produced an extension-level `unrecognized_keys` + * issue, while `fields`, `validations` and `fieldGroups` parsed. + * + * ⇒ THREE of this rule's rungs are reachable through an extension: + * `objects..fields.*`, `objects.._validations.*`, and + * `objects.._sections.*` for the groups a `.custom` arrangement brings + * (`fieldGroups[].key` is the section anchor, ADR-0085). `indexes` and + * `relatedLists` are not translatable here; `label` / `pluralLabel` / + * `description` are leaf copy on an object that already resolved, and this + * rule checks no leaf. ⛔ Do not grow this fold to `_views` / `_tabs` / + * `_actions` "for symmetry": an extension cannot contribute any of them, so a + * key there is an orphan exactly as it was, and widening those rungs would + * silence real ones. * * ## Read through the package's one fold (#30471) * @@ -1359,6 +1363,14 @@ function buildUniverse(stack: AnyRec): Universe { for (const rule of extension.validations) { collectValidationRuleNames(rule, facts.validations); } + // [ADR-0146 D10] `_sections.` is keyed by `fieldGroups[].key` + // (ADR-0085), and the base's paired `.custom` package declares the + // target's whole field arrangement in its extension: a group it brings + // is a section anchor of the target, as the target's own groups are. + for (const group of extension.fieldGroups) { + const key = strName(group.key); + if (key) facts.sections.add(key); + } } } diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index 77d57f4c7a9..57e8016f5bc 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -62,6 +62,11 @@ export { judgeOverrideWrite, overrideWriteIdentityOf, overrideWriteItemsOf, type // exported for the doors outside this package — `os validate` and the // marketplace install — so every door that lets a field in asks one judgement. export { judgeExtensionFieldSuffix, extensionFieldSuffixRefusalError, objectBodyExtensionFieldSuffixRefusal, type ExtensionFieldSuffixRefusal, type ExtensionFieldSuffixRule, type ExtensionFieldSuffixSubject } from './protocol-extension-field-suffix.js'; +// [ADR-0146 D10] The whole arrangement of an extended object is the paired +// `.custom` package's: one judge of an extension's `fieldGroups` / +// `relatedLists`, asked by the save doors here and by `os validate` / +// `os build` and the marketplace install outside. +export { judgeExtensionArrangement, extensionArrangementRefusalError, type ExtensionArrangementRefusal, type ExtensionArrangementSubject } from './protocol-extension-arrangement.js'; // [ADR-0146 D10, second rule] An extension's `fields` entry re-declaring an // owner's field beyond the display-property whitelist: one judge, asked by the // save doors here and by `os validate` and the marketplace install outside. diff --git a/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts b/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts new file mode 100644 index 00000000000..927674e771f --- /dev/null +++ b/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts @@ -0,0 +1,118 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] The arrangement judge and the save door's gate that asks it: + * `fieldGroups` and `relatedLists` on an object extension are the base's + * paired `.custom` package's to write. Any other package is refused once per + * key, with the active doors' envelope (`VALIDATION_ERROR` / 400, `issues[]` + * locating the key) and the prescription naming `place`. Each refusal is + * paired with a CONTROL through the same call that differs by one thing. + */ + +import './lint-root-preload.testkit.js'; +import { describe, expect, it } from 'vitest'; +import { judgeExtensionArrangement, extensionArrangementRefusalError } from './protocol-extension-arrangement.js'; +import { objectExtensionItemRefusal } from './protocol-object-extension-item.js'; + +const BASE = 'com.vendor.crm'; +const PAIR = 'com.vendor.crm.custom'; +const PARTNER = 'com.acme.partner'; + +const GROUPS = [{ key: 'basic', label: 'Basics', fields: ['name', 'region__c'] }]; +const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; + +describe('judgeExtensionArrangement — the rule', () => { + it('a plain package writing `fieldGroups` is refused once, at the key, prescribing `place`', () => { + const refusals = judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS }], + }); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ + path: 'objectExtensions[0].fieldGroups', object: 'crm_lead', key: 'fieldGroups', packageId: PARTNER, + }); + expect(refusals[0]!.message).toContain('`place`'); + expect(refusals[0]!.message).toContain('`.custom`'); + expect(refusals[0]!.message.length).toBeLessThanOrEqual(500); + }); + + it('`relatedLists` is refused the same way; both keys are one row each, in the list\'s order', () => { + const refusals = judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', relatedLists: TABS, fieldGroups: GROUPS }, { extend: 'crm_account', relatedLists: [] }], + at: 'packages[1].manifest.', + }); + expect(refusals.map((r) => r.path)).toEqual([ + 'packages[1].manifest.objectExtensions[0].fieldGroups', + 'packages[1].manifest.objectExtensions[0].relatedLists', + 'packages[1].manifest.objectExtensions[1].relatedLists', + ]); + expect(refusals[1]!.message).toContain("place: [{ list: 'contract', after: 'opportunity' }]"); + }); + + it('CONTROL: the same body in the base\'s paired `.custom` package is admitted', () => { + expect(judgeExtensionArrangement({ + packageId: PAIR, + objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS, relatedLists: TABS }], + })).toEqual([]); + }); + + it('CONTROL: a plain package that writes neither key, and places with `place`, is admitted', () => { + expect(judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', fields: { tier: { type: 'text' } }, place: [{ field: 'tier', group: 'basic' }] }], + })).toEqual([]); + }); + + it.each([[undefined], [null], ['']])('a body bound to no package (%j) is not judged', (packageId) => { + expect(judgeExtensionArrangement({ packageId, objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS }] })).toEqual([]); + }); + + it('the envelope: VALIDATION_ERROR / 400, the first sentence, every key located in `issues`', () => { + const refusals = judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS, relatedLists: TABS }], + }); + const err = extensionArrangementRefusalError(refusals); + expect(err.code).toBe('VALIDATION_ERROR'); + expect(err.status).toBe(400); + expect(err.message).toContain(refusals[0]!.message); + expect(err.message).toContain('1 more key in `issues`'); + expect(err.issues.map((i) => i.path)).toEqual(['objectExtensions[0].fieldGroups', 'objectExtensions[0].relatedLists']); + }); +}); + +describe('objectExtensionItemRefusal — the save, publish and restore gate asks it', () => { + const item = (extra: Record) => ({ extend: 'crm_lead', ...extra }); + const ask = (binding: string, body: Record) => objectExtensionItemRefusal('object_extension', { + item: body, name: 'crm_lead', binding, registry: undefined, scope: undefined, + }) as (Error & { code?: string; status?: number; issues?: Array<{ path: string; message: string }> }) | undefined; + + it('an `object_extension` item written into a plain package with `fieldGroups` is refused, located at the key', () => { + const err = ask(PARTNER, item({ fieldGroups: GROUPS })); + expect(err?.code).toBe('VALIDATION_ERROR'); + expect(err?.status).toBe(400); + expect(err?.issues).toHaveLength(1); + expect(err?.issues?.[0]?.path).toBe('fieldGroups'); + expect(err?.message).toContain('`place`'); + }); + + it('…and with `relatedLists`, located at that key', () => { + const err = ask(PARTNER, item({ relatedLists: TABS })); + expect(err?.status).toBe(400); + expect(err?.issues?.map((i) => i.path)).toEqual(['relatedLists']); + }); + + it('CONTROL: the same item written into the paired `.custom` package is admitted', () => { + expect(ask(PAIR, item({ fields: { region__c: { type: 'text' } }, fieldGroups: GROUPS, relatedLists: TABS }))).toBeUndefined(); + }); + + it('CONTROL: the plain package\'s item without the keys is admitted', () => { + expect(ask(PARTNER, item({ fields: { tier: { type: 'text' } }, place: [{ field: 'tier', group: 'basic' }] }))).toBeUndefined(); + }); + + it(`the base (${BASE}) extending its own object is refused too: its own arrangement is the object's`, () => { + const err = ask(BASE, item({ fieldGroups: GROUPS })); + expect(err?.issues?.map((i) => i.path)).toEqual(['fieldGroups']); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-extension-arrangement.ts b/packages/metadata-protocol/src/protocol-extension-arrangement.ts new file mode 100644 index 00000000000..9c3e1bad6a8 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-extension-arrangement.ts @@ -0,0 +1,128 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0146 D10 — the whole arrangement of an extended object is the paired + * `.custom` package's to declare, judged. + * + * Maintainer, verbatim: 「软件包字段、子表自定义分三种,原始软件包,继承软件包和环境管理员覆盖, + * 继承软件包 我记得已经有一套标准,只能申明插入位置,原始软件包、环境管理员 应该可以申明完整的配置」. + * An object extension carries two keys for it, `fieldGroups` and + * `relatedLists` (`CUSTOM_ARRANGEMENT_KEYS`, `@objectstack/spec/data`), in the + * shape an object declares them in. Which package an extension belongs to is + * not in its body, so the schema cannot say who wrote them; this module is + * the ONE judge and every door calls it, as the `__c` reservation's doors + * call theirs (`protocol-extension-field-suffix.ts`): + * + * - the save, the restore and the draft promotion of an `object_extension` + * item (`objectExtensionItemRefusal`, `protocol-object-extension-item.ts`), + * as the package's one `objectExtensions` entry; + * - `os validate` and `os build` (`@objectstack/cli`) and the marketplace + * install (`@objectstack/cloud-connection`), for a whole package body. + * + * ## The rule + * + * In a package that is NOT a base's paired `.custom` + * ({@link isCustomizationPackage}, the `__c` judge's predicate), every + * arrangement key an `objectExtensions` entry writes is refused, with the + * prescription to place what the package brings with `place`. In a `.custom` + * package nothing is refused. A body bound to no package is not judged: the + * rule is about packages, as the `__c` reservation is. + * + * The registry fold applies only a `.custom` package's keys + * (`applyCustomArrangement`, `@objectstack/objectql`), so a body that reaches + * the registry past every door (a manifest loaded unparsed) is skipped there + * and named in the boot log; nothing here depends on that. + * + * Pure: no I/O, no throw from {@link judgeExtensionArrangement}. Each door + * keeps its own envelope; the active doors' is + * {@link extensionArrangementRefusalError}'s `VALIDATION_ERROR` / 400. No code + * is minted. + */ + +import { extensionArrangementKeys, type CustomArrangementKey } from '@objectstack/spec/data'; +import { isCustomizationPackage } from '@objectstack/spec/kernel'; +import type { MetadataIssueEntry } from './protocol.js'; + +/** One refused arrangement key, located. */ +export interface ExtensionArrangementRefusal { + /** Where the key sits in the judged body, e.g. `objectExtensions[0].fieldGroups`. */ + path: string; + /** The extension's `extend` target. */ + object: string; + /** The key as written. */ + key: CustomArrangementKey; + /** The package the body is written into. */ + packageId: string; + /** The door's sentence: what is wrong, then the prescription. */ + message: string; +} + +/** What a door hands the judge: the package written into and its extensions. */ +export interface ExtensionArrangementSubject { + /** The package the body is written into. Not a non-empty string ⇒ not judged. */ + packageId: string | null | undefined; + /** The package's `objectExtensions` entries. */ + objectExtensions?: unknown; + /** Prefix of every reported path, e.g. `packages[1].manifest.`. */ + at?: string; +} + +const isRecord = (v: unknown): v is Record => + v !== null && typeof v === 'object' && !Array.isArray(v); + +/** What `place` writes instead, per key. */ +const PLACE_EXAMPLE: Readonly> = Object.freeze({ + fieldGroups: "`place: [{ field: 'tax_id', group: 'basic', after: 'industry' }]`", + relatedLists: "`place: [{ list: 'contract', after: 'opportunity' }]`", +}); + +/** The sentence. Prescription inside the first 500 characters: a 4xx message crosses the REST boundary capped there. */ +function arrangementOutsidePairMessage(key: CustomArrangementKey, object: string, packageId: string): string { + return `\`${key}\` in the extension of object '${object}' in package '${packageId}': only the object extension of a ` + + 'base\'s paired `.custom` package declares an object\'s whole arrangement (ADR-0146 D10). Remove the key and ' + + `place what this package brings with \`place\`, e.g. ${PLACE_EXAMPLE[key]}.`; +} + +/** + * Every arrangement key the rule refuses in what `subject` declares, in + * declaration order. Empty when the subject names no package, names a + * `.custom` package, or writes neither key. + */ +export function judgeExtensionArrangement(subject: ExtensionArrangementSubject): ExtensionArrangementRefusal[] { + const { packageId } = subject; + if (typeof packageId !== 'string' || packageId === '') return []; + if (isCustomizationPackage(packageId) || !Array.isArray(subject.objectExtensions)) return []; + const at = subject.at ?? ''; + const refusals: ExtensionArrangementRefusal[] = []; + subject.objectExtensions.forEach((ext, i) => { + if (!isRecord(ext)) return; + const object = typeof ext.extend === 'string' ? ext.extend : ''; + for (const key of extensionArrangementKeys(ext)) { + refusals.push({ + path: `${at}objectExtensions[${i}].${key}`, + object, key, packageId, + message: arrangementOutsidePairMessage(key, object, packageId), + }); + } + }); + return refusals; +} + +/** + * The active doors' envelope around a non-empty refusal list: `VALIDATION_ERROR` + * / 400, the message the first refusal's sentence (and how many more), and + * `issues[]` locating every key, the shape the Studio designer keys on. + */ +export function extensionArrangementRefusalError( + refusals: readonly ExtensionArrangementRefusal[], +): Error & { code: 'VALIDATION_ERROR'; status: 400; issues: MetadataIssueEntry[] } { + const [first] = refusals; + const more = refusals.length - 1; + const err = new Error( + `${first!.message}${more > 0 ? ` (${more} more key${more === 1 ? '' : 's'} in \`issues\`.)` : ''}`, + ) as Error & { code: 'VALIDATION_ERROR'; status: 400; issues: MetadataIssueEntry[] }; + err.code = 'VALIDATION_ERROR'; + err.status = 400; + err.issues = refusals.map((r) => ({ path: r.path, message: r.message, code: 'custom' })); + return err; +} diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index b824cb199d7..960ea88d718 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -47,6 +47,7 @@ import { packageDependencyClosure, pairsOf, type PackageClosureRegistry } from ' import { disabledExactAddressHolder } from './protocol-exact-qualifier.js'; import type { PrereadActiveRows } from './protocol-meta-item-reads.js'; import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; +import { RELATED_LISTS_ARRANGEMENT_DECORATION, type RelatedListsArrangement } from '@objectstack/spec/data'; import { overlayMemberValue, overlayMemberWhere } from './migrations/overlay-index.js'; import { isServedOverrideRowOf } from './served-override.js'; import { @@ -811,6 +812,54 @@ export function withWithheldFieldsDecoration(registry: unknown, item: unknown, n return { ...body, _withheldFields: Object.fromEntries(entries.map(([field, at]) => [field, { packageId: at.packageId }])) }; } +/** + * [ADR-0146 D10] `item` with the served object read's + * `_relatedListsArrangement` decoration: what the tab list the base's paired + * `.custom` package declares says that the served `relatedLists` cannot + * (`SchemaRegistry.getRelatedListsArrangement`): the lists it hides, and + * whether a list no entry names is shown after the listed tabs. `item` itself + * when no `.custom` package arranges the object's tabs, or when the registry + * cannot answer. + * + * Why it is served: the registry fold writes the `.custom` tab list into + * `relatedLists` (the entries it shows, then the entries of the arrangement + * it replaces that it does not name), and `relatedLists` keeps the meaning it + * has on every object. Which lists exist for the reader is the record page's + * to know, so the two things that depend on it travel beside the list, and + * the record page reads them through `readRelatedListsArrangement` + * (`@objectstack/spec/data`). + * + * A read decoration (`METADATA_READ_DECORATIONS`, `@objectstack/spec`), on the + * faces {@link withWithheldFieldsDecoration} is stamped on and no other. + */ +export function withRelatedListsArrangementDecoration(registry: unknown, item: unknown, name?: string): unknown { + if (item === null || typeof item !== 'object' || Array.isArray(item)) return item; + const body = item as Record; + const objectName = typeof name === 'string' && name !== '' ? name : body.name; + const r = registry as { getRelatedListsArrangement?: (name: string) => RelatedListsArrangement | undefined } | null | undefined; + if (typeof objectName !== 'string' || typeof r?.getRelatedListsArrangement !== 'function') return item; + const arrangement = r.getRelatedListsArrangement(objectName); + if (arrangement === undefined) return item; + return { + ...body, + [RELATED_LISTS_ARRANGEMENT_DECORATION]: { + packageId: arrangement.packageId, + hidden: [...arrangement.hidden], + unlisted: arrangement.unlisted, + }, + }; +} + +/** + * `item` with every decoration the served object read derives from the + * registry: {@link withWithheldFieldsDecoration} and + * {@link withRelatedListsArrangementDecoration}. `item` itself when neither + * applies. The one call of the served by-name read and the served list. + */ +export function withServedObjectDecorations(registry: unknown, item: unknown, name?: string): unknown { + return withRelatedListsArrangementDecoration(registry, withWithheldFieldsDecoration(registry, item, name), name); +} + /** The body of `ObjectStackProtocolImplementation#readMetaItemFace`; the method's docblock there is its contract. */ export async function readMetaItemFace( this: Pick & ServedRowHost, @@ -912,10 +961,12 @@ export async function readMetaItemFace( if (withheldHolder === undefined && (request.type === 'object' || request.type === 'package' || (!withheldAction && !isItemOfDisabledPackage(this.engine?.registry, answer?.item)))) { // [#34901] The served object read names the fields a disabled - // package withholds ({@link withWithheldFieldsDecoration}); the - // execution face and a pending draft's authoring read never do. + // package withholds, and [ADR-0146 D10] what the paired `.custom` + // tab list says beside `relatedLists` + // ({@link withServedObjectDecorations}); the execution face and a + // pending draft's authoring read never do. if (request.type === 'object' && face === 'served' && request.state !== 'draft' && answer?.item != null) { - const item = withWithheldFieldsDecoration(this.engine?.registry, answer.item, request.name); + const item = withServedObjectDecorations(this.engine?.registry, answer.item, request.name); return item === answer.item ? answer : { ...answer, item }; } return answer; diff --git a/packages/metadata-protocol/src/protocol-meta-list-reads.ts b/packages/metadata-protocol/src/protocol-meta-list-reads.ts index 086e0b043f8..6ed202a04b0 100644 --- a/packages/metadata-protocol/src/protocol-meta-list-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-list-reads.ts @@ -49,7 +49,7 @@ import { storedEntryRow } from './protocol-stored-overlay-types.js'; import { viewIdentityPatch } from './protocol-view-normalization.js'; import { isServedOverrideRowOf, type ServedOverrideRow } from './served-override.js'; import { installedManifestsOfEngine } from './installed-manifests.js'; -import { packagelessRowWithheld, withWithheldFieldsDecoration } from './protocol-meta-item-face.js'; +import { packagelessRowWithheld, withServedObjectDecorations } from './protocol-meta-item-face.js'; import { declinesPackageLessRowAt, disabledExactAddressHolder, @@ -1100,13 +1100,15 @@ export async function readFlattenedMetaItems(host: Pick { const listed = decorateListedItem(request.type, it); return request.type === 'object' && layer === 'effective' - ? withWithheldFieldsDecoration(host.engine?.registry, listed) + ? withServedObjectDecorations(host.engine?.registry, listed) : listed; }) : governed, diff --git a/packages/metadata-protocol/src/protocol-object-extension-item.ts b/packages/metadata-protocol/src/protocol-object-extension-item.ts index 37a1bdaf4a7..a25ac11dc0d 100644 --- a/packages/metadata-protocol/src/protocol-object-extension-item.ts +++ b/packages/metadata-protocol/src/protocol-object-extension-item.ts @@ -41,6 +41,7 @@ import { closureDependencyRemedy, narrowObjectsToPackageClosure } from '@objects import type { RuntimePackageScope } from '@objectstack/lint/runtime'; import { judgeExtensionFieldSuffix, extensionFieldSuffixRefusalError } from './protocol-extension-field-suffix.js'; import { judgeRedeclaredOwnerFields, redeclaredOwnerFieldRefusalError } from './protocol-extension-redeclared-owner-field.js'; +import { judgeExtensionArrangement, extensionArrangementRefusalError } from './protocol-extension-arrangement.js'; import type { MetadataIssueEntry } from './protocol.js'; /** The metadata type of an object extension item. */ @@ -163,6 +164,9 @@ export interface ObjectExtensionItemSubject { * changes anything outside the display-property whitelist, with the * prescription naming `fieldPatches`. A registry without `getObjectOwner` * leaves it unasked, as the target checks above are. + * 8. ADR-0146 D10's arrangement (`judgeExtensionArrangement`): `fieldGroups` + * or `relatedLists` written into a package that is not a base's paired + * `.custom` is refused, with the prescription naming `place`. * * Whether the package is writable is the door's own refusal * (`WRITABLE_PACKAGE_REQUIRED`), asked before any of this. @@ -248,6 +252,11 @@ export function objectExtensionItemRefusal( : undefined), }).map((r) => ({ ...r, path: r.path.slice('objectExtensions[0].'.length) })); if (redeclared.length > 0) return redeclaredOwnerFieldRefusalError(redeclared); + + // 8. + const arrangement = judgeExtensionArrangement({ packageId: binding, objectExtensions: [item] }) + .map((r) => ({ ...r, path: r.path.slice('objectExtensions[0].'.length) })); + if (arrangement.length > 0) return extensionArrangementRefusalError(arrangement); return undefined; } diff --git a/packages/objectql/src/engine-registration.ts b/packages/objectql/src/engine-registration.ts index cbc7b4d3e62..f89f669b362 100644 --- a/packages/objectql/src/engine-registration.ts +++ b/packages/objectql/src/engine-registration.ts @@ -141,6 +141,7 @@ export function objectExtensionContribution(ext: any): { definition: { name: string; fields: unknown; fieldPatches: unknown; label: unknown; pluralLabel: unknown; description: unknown; validations: unknown; indexes: unknown; place: unknown; + fieldGroups: unknown; relatedLists: unknown; }; priority: number; } { @@ -162,6 +163,12 @@ export function objectExtensionContribution(ext: any): { // applied by the registry fold after every contributor's // fields are merged (`applyExtensionPlacements`). place: ext.place, + // [ADR-0146 D10] The whole arrangement the paired `.custom` + // package declares — applied by the registry fold, last + // (`applyCustomArrangement`), which skips any other + // package's and names it. + fieldGroups: ext.fieldGroups, + relatedLists: ext.relatedLists, }, priority: ext.priority ?? 200, }; diff --git a/packages/objectql/src/protocol-custom-arrangement.test.ts b/packages/objectql/src/protocol-custom-arrangement.test.ts new file mode 100644 index 00000000000..53583fdaf57 --- /dev/null +++ b/packages/objectql/src/protocol-custom-arrangement.test.ts @@ -0,0 +1,280 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] A base's paired `.custom` package declares an installed + * object's whole arrangement, through the real protocol over the real + * `ObjectQL` engine and an in-memory driver. + * + * A code package owns `crm_lead` with field groups and a tab list; another + * code package extends it and places a field. Pinned here: + * + * - the pair's `object_extension` writing `fieldGroups` / `relatedLists` is + * saved, and the served object (by name and in the list read) carries the + * replaced arrangement and the `_relatedListsArrangement` decoration; the + * execution face does not carry the decoration; + * - the same keys in a writable package that is not a `.custom` one are + * refused at the save door, once, and nothing is stored or served; + * - saving the pair's extension without the keys, or disabling the pair, + * serves the owner's arrangement with the placements again. + * + * Test-path resolution: the protocol is `@objectstack/metadata-protocol`'s + * `dist/`, so a change there is read here after that package is rebuilt. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { deriveFieldGroupLayout } from '@objectstack/spec/data'; +import type { ServiceObject } from '@objectstack/spec/data'; +import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol'; +import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject } from '@objectstack/metadata-core'; +import { ObjectQL } from './engine.js'; + +const sysMetadataObject: ServiceObject = { + name: 'sys_metadata', label: 'System Metadata', + fields: { + id: { name: 'id', label: 'ID', type: 'text' as const }, + type: { name: 'type', label: 'Type', type: 'text' as const, required: true }, + name: { name: 'name', label: 'Name', type: 'text' as const, required: true }, + organization_id: { name: 'organization_id', label: 'Org', type: 'text' as const }, + package_id: { name: 'package_id', label: 'Package', type: 'text' as const }, + bundle_member: { name: 'bundle_member', label: 'Bundle Member', type: 'text' as const, maxLength: 100 }, + metadata: { name: 'metadata', label: 'Body', type: 'textarea' as const }, + draft_changes: { name: 'draft_changes', label: 'Draft Changes', type: 'textarea' as const }, + checksum: { name: 'checksum', label: 'Checksum', type: 'text' as const, maxLength: 71 }, + state: { name: 'state', label: 'State', type: 'text' as const }, + version: { name: 'version', label: 'Version', type: 'number' as const }, + created_at: { name: 'created_at', label: 'Created', type: 'datetime' as const }, + updated_at: { name: 'updated_at', label: 'Updated', type: 'datetime' as const }, + }, +}; + +function makeMemoryDriver() { + const stores = new Map>>(); + const storeFor = (o: string) => { let s = stores.get(o); if (!s) { s = new Map(); stores.set(o, s); } return s; }; + let nextId = 0; + const matchesWhere = (row: Record, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k === '$and' && Array.isArray(v)) { if (!v.every((w: any) => matchesWhere(row, w))) return false; continue; } + if (k === '$or' && Array.isArray(v)) { if (!v.some((w: any) => matchesWhere(row, w))) return false; continue; } + if (k.startsWith('$')) continue; + const rowVal = row[k]; + if (v && typeof v === 'object' && Array.isArray((v as any).$in)) { if (!(v as any).$in.includes(rowVal === undefined ? null : rowVal)) return false; continue; } + const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; + if ((rowVal === undefined ? null : rowVal) !== (expected === undefined ? null : expected)) return false; + } + return true; + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {} as any, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(o: string, ast: any) { const rows = Array.from(storeFor(o).values()).filter((r) => matchesWhere(r, ast?.where)); return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; }, + async findOne(o: string, ast: any) { for (const r of storeFor(o).values()) if (matchesWhere(r, ast?.where)) return r; return null; }, + async create(o: string, data: Record) { nextId += 1; const id = (data.id as string) ?? `r_${nextId}`; const row = { ...data, id }; storeFor(o).set(id, row); return row; }, + async update(o: string, id: string, data: Record) { const s = storeFor(o); const cur = s.get(id); if (!cur) throw new Error(`not found ${o}/${id}`); const u = { ...cur, ...data, id }; s.set(id, u); return u; }, + async upsert(o: string, data: Record) { const id = data.id as string | undefined; if (id && storeFor(o).has(id)) return this.update(o, id, data); return this.create(o, data); }, + async delete(o: string, id: string) { return storeFor(o).delete(id); }, + async count(o: string, ast: any) { return (await this.find(o, ast)).length; }, + async bulkCreate(o: string, rows: Record[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, stores }; +} + +const BASE = 'com.example.crm'; +const EXT = 'com.example.tax'; +const PAIR = `${BASE}.custom`; +const ADDON = 'com.example.addon'; +const OBJ = 'crm_lead'; + +const text = (name: string, label: string, extra: Record = {}) => ({ name, label, type: 'text', ...extra }); +const child = (name: string, label: string) => ({ + name, label, + fields: { name: text('name', 'Name'), lead: { name: 'lead', label: 'Lead', type: 'lookup', reference: OBJ } }, +}); + +async function boot() { + const engine = new ObjectQL(); + const { driver, stores } = makeMemoryDriver(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(sysMetadataObject, 'test-package'); + for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any, 'test-package'); + engine.registerApp({ + id: BASE, name: 'crm', version: '1.0.0', namespace: 'crm', type: 'app', + objects: [ + { + name: OBJ, label: 'Lead', + fields: { + name: text('name', 'Name'), company: text('company', 'Company'), status: text('status', 'Status'), + email: text('email', 'Email'), phone: text('phone', 'Phone'), fax: text('fax', 'Fax'), + }, + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'status'] }, + { key: 'contact', label: 'Contact', fields: ['email', 'phone', 'fax'] }, + ], + relatedLists: ['crm_task', 'crm_event', 'crm_note'], + }, + child('crm_task', 'Task'), child('crm_event', 'Event'), child('crm_note', 'Note'), + ], + } as any); + engine.registerApp({ + id: EXT, name: 'tax', version: '1.0.0', namespace: 'crm', type: 'app', dependencies: { [BASE]: '^1.0.0' }, + objectExtensions: [{ + extend: OBJ, + fields: { crm_tax_id: text('crm_tax_id', 'Tax ID') }, + place: [{ field: 'crm_tax_id', group: 'basic', after: 'company' }], + }], + } as any); + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()); + await (protocol as any).installPackage({ manifest: { id: PAIR, name: 'crm-custom', version: '0.1.0', type: 'app', namespace: 'crm_custom', dependencies: { [BASE]: '^1' } } }); + await (protocol as any).installPackage({ manifest: { id: ADDON, name: 'addon', version: '0.1.0', type: 'app', namespace: 'addon', dependencies: { [BASE]: '^1' } } }); + return { engine, registry: engine.registry as any, protocol: protocol as any, stores }; +} + +const savedWritable = process.env.OS_METADATA_WRITABLE; +beforeEach(() => { delete process.env.OS_METADATA_WRITABLE; ObjectStackProtocolImplementation.resetEnvWritableCache(); resetEnvWritableMetadataTypes(); }); +afterEach(() => { + vi.restoreAllMocks(); + if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE; else process.env.OS_METADATA_WRITABLE = savedWritable; + ObjectStackProtocolImplementation.resetEnvWritableCache(); resetEnvWritableMetadataTypes(); +}); + +const AUTHORED = new Set(['name', 'company', 'status', 'email', 'phone', 'fax', 'crm_tax_id', 'region__c']); +/** The derived layout as `[group key | null for the trailing bucket, authored members]`. */ +const layout = (body: any): Array<[string | null, string[]]> => + (deriveFieldGroupLayout(body) ?? []) + .map((section): [string | null, string[]] => [section.key ?? null, section.fields.filter((f) => AUTHORED.has(f))]) + // The trailing bucket also carries the object's system fields; with no authored member it is not a reading. + .filter(([key, members]) => key !== null || members.length > 0); + +const servedObject = async (protocol: any) => (await protocol.getMetaItem({ type: 'object', name: OBJ })).item; + +/** Steps 1–2: the owner's arrangement with the extension package's placement. */ +const STEPS_1_2 = { + layout: [ + ['basic', ['name', 'company', 'crm_tax_id', 'status']], + ['contact', ['email', 'phone', 'fax']], + ], + relatedLists: ['crm_task', 'crm_event', 'crm_note'], +}; + +const REGION = text('region__c', 'Region'); +const ARRANGEMENT = { + // The two groups swapped, `status` moved to `contact`, `fax` and the extension package's field left out. + fieldGroups: [ + { key: 'contact', label: 'Contact', fields: ['email', 'phone', 'status'] }, + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'region__c'] }, + ], + // Two tabs swapped, one hidden. + relatedLists: ['crm_event', 'crm_task', { list: 'crm_note', hidden: true }], +}; + +const saveExtension = (protocol: any, packageId: string, body: Record) => + protocol.saveMetaItem({ type: 'object_extension', name: OBJ, packageId, mode: 'publish', item: { extend: OBJ, ...body } }); + +async function outcome(fn: () => Promise) { + try { + await fn(); + return { ok: true as const }; + } catch (e: any) { + return { + ok: false as const, + code: e?.code, + status: e?.status, + issues: Array.isArray(e?.issues) ? e.issues.length : 0, + message: String(e?.message ?? ''), + }; + } +} + +describe('ADR-0146 D10 — the paired `.custom` package arranges an installed object, through the protocol', () => { + it('control: before any `.custom` arrangement the served object is the owner\'s with the placement, undecorated', async () => { + const { protocol } = await boot(); + const item = await servedObject(protocol); + expect(layout(item)).toEqual(STEPS_1_2.layout); + expect(item.relatedLists).toEqual(STEPS_1_2.relatedLists); + expect('_relatedListsArrangement' in item).toBe(false); + }); + + it('the pair\'s extension is saved, and the by-name and list reads serve the replaced arrangement with its decoration', async () => { + const { protocol } = await boot(); + expect(await outcome(() => saveExtension(protocol, PAIR, { fields: { region__c: REGION }, ...ARRANGEMENT }))).toEqual({ ok: true }); + + const item = await servedObject(protocol); + expect(layout(item)).toEqual([ + ['contact', ['email', 'phone', 'status']], + ['basic', ['name', 'company', 'region__c']], + // Unlisted, never dropped: the owner's `fax` and the extension package's placed field, after the last group. + [null, ['fax', 'crm_tax_id']], + ]); + expect(item.relatedLists).toEqual(['crm_event', 'crm_task']); + expect(item._relatedListsArrangement).toEqual({ packageId: PAIR, hidden: ['crm_note'], unlisted: 'hidden' }); + + const listed = ((await protocol.getMetaItems({ type: 'object' })).items as any[]).find((o) => o?.name === OBJ); + expect(listed?.relatedLists, 'the list read serves the same tabs').toEqual(['crm_event', 'crm_task']); + expect(listed?._relatedListsArrangement, 'and carries the decoration').toEqual(item._relatedListsArrangement); + + const execution = (await protocol.getMetaItemForExecution({ type: 'object', name: OBJ }))?.item; + expect(execution, 'precondition: the execution face answers').toBeTruthy(); + expect('_relatedListsArrangement' in execution, 'the execution face is not decorated').toBe(false); + }); + + it('only `relatedLists` written: the field groups keep the owner\'s arrangement with the placement', async () => { + const { protocol } = await boot(); + expect(await outcome(() => saveExtension(protocol, PAIR, { relatedLists: ARRANGEMENT.relatedLists }))).toEqual({ ok: true }); + const item = await servedObject(protocol); + expect(layout(item)).toEqual(STEPS_1_2.layout); + expect(item.relatedLists).toEqual(['crm_event', 'crm_task']); + }); + + it('a writable package that is not a `.custom` one is refused at the save door, once, and nothing is stored or served', async () => { + const { protocol, stores } = await boot(); + for (const [key, body] of [ + ['fieldGroups', { fieldGroups: [{ key: 'addon', label: 'Addon', fields: ['name'] }] }], + ['relatedLists', { relatedLists: ['crm_event'] }], + ] as const) { + const refused = await outcome(() => saveExtension(protocol, ADDON, body)); + expect(refused, key).toMatchObject({ ok: false, code: 'VALIDATION_ERROR', status: 400, issues: 1 }); + expect((refused as any).message, key).toContain(`\`${key}\``); + expect((refused as any).message, 'prescribes `place`').toContain('`place`'); + } + const rows = Array.from(stores.get('sys_metadata')?.values() ?? []).filter((r) => r.type === 'object_extension' && r.package_id === ADDON); + expect(rows, 'no row was written').toEqual([]); + const item = await servedObject(protocol); + expect(layout(item)).toEqual(STEPS_1_2.layout); + expect(item.relatedLists).toEqual(STEPS_1_2.relatedLists); + + // Control: the same package's extension without the keys is admitted by the same door. + expect(await outcome(() => saveExtension(protocol, ADDON, { fields: { addon_score: text('addon_score', 'Score') } }))).toEqual({ ok: true }); + }); + + it('saving the pair\'s extension without the keys restores the owner\'s arrangement with the placement', async () => { + const { protocol } = await boot(); + await saveExtension(protocol, PAIR, { fields: { region__c: REGION }, ...ARRANGEMENT }); + expect((await servedObject(protocol)).relatedLists).toEqual(['crm_event', 'crm_task']); + + await saveExtension(protocol, PAIR, { fields: { region__c: REGION } }); + const item = await servedObject(protocol); + expect(item.relatedLists).toEqual(STEPS_1_2.relatedLists); + expect('_relatedListsArrangement' in item).toBe(false); + // The pair's own field stays, ungrouped; the owner's groups are back. + expect(layout(item)).toEqual([...STEPS_1_2.layout, [null, ['region__c']]]); + }); + + it('disabling the pair restores it too, with no write, and enabling brings the arrangement back', async () => { + const { registry, protocol } = await boot(); + await saveExtension(protocol, PAIR, { fields: { region__c: REGION }, ...ARRANGEMENT }); + + registry.disablePackage(PAIR); + const off = await servedObject(protocol); + expect(layout(off)).toEqual(STEPS_1_2.layout); + expect(off.relatedLists).toEqual(STEPS_1_2.relatedLists); + expect('_relatedListsArrangement' in off).toBe(false); + + registry.enablePackage(PAIR); + const on = await servedObject(protocol); + expect(on.relatedLists).toEqual(['crm_event', 'crm_task']); + expect(on._relatedListsArrangement).toEqual({ packageId: PAIR, hidden: ['crm_note'], unlisted: 'hidden' }); + }); +}); diff --git a/packages/objectql/src/registry-custom-arrangement.test.ts b/packages/objectql/src/registry-custom-arrangement.test.ts new file mode 100644 index 00000000000..424bccda6e3 --- /dev/null +++ b/packages/objectql/src/registry-custom-arrangement.test.ts @@ -0,0 +1,511 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] The third layer of an installed object's record-page + * arrangement, over a base + extension package + `.custom` fixture: + * + * 1. the base declares its field groups and its tabs; + * 2. an extension package places what it brings with `place`; + * 3. where the base's paired `.custom` package writes `fieldGroups` or + * `relatedLists`, that key replaces the result of 1–2, whole. + * + * The field arrangement is asserted through `deriveFieldGroupLayout`, the one + * derivation the record page, the create and edit forms and the preview + * share (ADR-0085 §5), so "shows in the new arrangement" is one reading. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { deriveFieldGroupLayout, ObjectExtensionSchema, ObjectSchema } from '@objectstack/spec/data'; +import { SchemaRegistry } from './registry.js'; +import { applyCustomArrangement } from './registry-custom-arrangement.js'; + +const BASE = 'com.vendor.crm'; +const PAIR = 'com.vendor.crm.custom'; +const EXT = 'com.acme.tax'; +const OBJ = 'crm_lead'; + +/** + * The vendor's lead. `basic` lists its members (the current spelling); + * `contact`'s members name it in their own `group` (the older spelling), so + * every rule is read against both. + */ +function vendorLead(extra: Record = {}): any { + return { + name: OBJ, + label: 'Lead', + fields: { + name: { name: 'name', type: 'text', label: 'Name' }, + company: { name: 'company', type: 'text', label: 'Company' }, + status: { name: 'status', type: 'text', label: 'Status' }, + email: { name: 'email', type: 'text', label: 'Email', group: 'contact' }, + phone: { name: 'phone', type: 'text', label: 'Phone', group: 'contact' }, + fax: { name: 'fax', type: 'text', label: 'Fax', group: 'contact' }, + }, + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'status'] }, + { key: 'contact', label: 'Contact' }, + ], + relatedLists: ['crm_task', 'crm_event', 'crm_note'], + ...extra, + }; +} + +const child = (name: string, label: string) => ({ + name, + label, + fields: { lead_id: { name: 'lead_id', type: 'lookup', label: 'Lead', reference: OBJ } }, +}); + +function registry(): SchemaRegistry { + const reg = new SchemaRegistry({ multiTenant: false, searchCompanion: false } as never); + reg.logLevel = 'silent'; + return reg; +} + +function withBase(lead: any = vendorLead(), reg = registry()): SchemaRegistry { + reg.registerObject(lead, BASE, undefined, 'own'); + for (const [name, label] of [['crm_task', 'Task'], ['crm_event', 'Event'], ['crm_note', 'Note']]) { + reg.registerObject(child(name, label) as any, BASE, undefined, 'own'); + } + return reg; +} + +/** The extension package: a field placed into `basic`, and a child list placed after the tasks. */ +function withExtensionPackage(reg: SchemaRegistry): SchemaRegistry { + reg.registerObject(child('acme_audit', 'Audit') as any, EXT, undefined, 'own'); + reg.registerObject( + { + name: OBJ, + fields: { tax_id: { name: 'tax_id', type: 'text', label: 'Tax ID' } }, + place: [{ field: 'tax_id', group: 'basic', after: 'company' }, { list: 'acme_audit', after: 'crm_task' }], + } as any, + EXT, undefined, 'extend', 200, + ); + return reg; +} + +const REGION = { name: 'region__c', type: 'text', label: 'Region' }; + +/** The `.custom` package's extension of the lead: its own field, plus the arrangement keys it writes. */ +function customize(reg: SchemaRegistry, arrangement: Record, options: { pkg?: string; fields?: Record } = {}): SchemaRegistry { + reg.registerObject( + { name: OBJ, fields: options.fields ?? { region__c: REGION }, ...arrangement } as any, + options.pkg ?? PAIR, undefined, 'extend', 200, + ); + return reg; +} + +const served = (reg: SchemaRegistry): any => reg.getObject(OBJ); + +const AUTHORED = new Set(['name', 'company', 'status', 'email', 'phone', 'fax', 'tax_id', 'region__c']); +/** The derived layout as `[group key | null for the trailing bucket, authored members]`. */ +const layout = (body: any): Array<[string | null, string[]]> => + (deriveFieldGroupLayout(body) ?? []) + .map((section): [string | null, string[]] => [section.key ?? null, section.fields.filter((f) => AUTHORED.has(f))]) + // The trailing bucket also carries the object's system fields; with no authored member it is not a reading. + .filter(([key, members]) => key !== null || members.length > 0); + +afterEach(() => vi.restoreAllMocks()); + +describe('ADR-0146 D10 — the fixture, before the `.custom` arrangement (steps 1–2)', () => { + it('control: the base arrangement with the extension package\'s placements', () => { + const body = served(withExtensionPackage(withBase())); + expect(layout(body)).toEqual([ + ['basic', ['name', 'company', 'tax_id', 'status']], + ['contact', ['email', 'phone', 'fax']], + ]); + expect(body.relatedLists).toEqual(['crm_task', 'acme_audit', 'crm_event', 'crm_note']); + }); +}); + +describe('ADR-0146 D10 — `.custom` fieldGroups replaces the field arrangement whole', () => { + it('a base field moved to another group and two groups swapped: the layout every surface derives', () => { + const reg = customize(withBase(), { + fieldGroups: [ + { key: 'contact', label: 'Reach', fields: ['email', 'phone', 'fax', 'status'] }, + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'region__c'] }, + ], + }); + const body = served(reg); + expect(layout(body)).toEqual([ + ['contact', ['email', 'phone', 'fax', 'status']], + ['basic', ['name', 'company', 'region__c']], + ]); + expect(body.fieldGroups.map((g: any) => [g.key, g.label])).toEqual([['contact', 'Reach'], ['basic', 'Basic']]); + // The served object is one an object parse accepts: no field names a group other than the one listing it. + expect(ObjectSchema.safeParse({ name: OBJ, fields: body.fields, fieldGroups: body.fieldGroups }).success).toBe(true); + }); + + it('a base field the arrangement does not list shows after the last group, in either spelling', () => { + // `company` was in `basic` by the group's list, `fax` in `contact` by its own `group`. + const reg = customize(withBase(), { + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name', 'status'] }, + { key: 'contact', label: 'Contact', fields: ['email', 'phone'] }, + ], + }); + const body = served(reg); + expect(layout(body)).toEqual([ + ['basic', ['name', 'status']], + ['contact', ['email', 'phone']], + [null, ['company', 'fax', 'region__c']], + ]); + expect(body.fields.fax.group).toBeUndefined(); + expect(body.fields.fax.label).toBe('Fax'); + }); + + it('an extension package\'s placed field the arrangement does not list still shows, after the last group', () => { + const reg = customize(withExtensionPackage(withBase()), { + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'status'] }, + { key: 'contact', label: 'Contact', fields: ['email', 'phone', 'fax'] }, + ], + }); + const body = served(reg); + expect(layout(body)).toEqual([ + ['basic', ['name', 'company', 'status']], + ['contact', ['email', 'phone', 'fax']], + [null, ['tax_id', 'region__c']], + ]); + expect(Object.keys(body.fields)).toContain('tax_id'); + }); + + it('the arrangement may list any field: the base\'s, another extension\'s, its own', () => { + const reg = customize(withExtensionPackage(withBase()), { + fieldGroups: [{ key: 'all', label: 'Everything', fields: ['region__c', 'tax_id', 'name', 'fax'] }], + }); + expect(layout(served(reg))[0]).toEqual(['all', ['region__c', 'tax_id', 'name', 'fax']]); + }); + + it('its own statements keep the object\'s rule: a field it declares keeps its `group`, a list-less group takes the fields naming it', () => { + const reg = customize(withBase(), { + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name'] }, + { key: 'contact', label: 'Contact' }, + ], + }, { fields: { region__c: { ...REGION, group: 'basic' } } }); + expect(layout(served(reg))).toEqual([ + ['basic', ['name', 'region__c']], + ['contact', ['email', 'phone', 'fax']], + [null, ['company', 'status']], + ]); + }); + + it('a group placing a body table takes no field: a `group` naming it is taken off', () => { + const reg = customize(withBase(), { + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name'] }, + { key: 'contact', label: 'Notes', relatedList: 'crm_note' }, + ], + }); + const body = served(reg); + expect(body.fieldGroups[1]).toEqual({ key: 'contact', label: 'Notes', relatedList: 'crm_note' }); + expect(body.fields.email.group).toBeUndefined(); + expect(ObjectSchema.safeParse({ name: OBJ, fields: body.fields, fieldGroups: body.fieldGroups }).success).toBe(true); + }); + + it('an empty list is an arrangement with no group: the fields show ungrouped', () => { + const body = served(customize(withBase(), { fieldGroups: [] })); + expect(body.fieldGroups).toEqual([]); + expect(deriveFieldGroupLayout(body)).toBeNull(); + }); +}); + +describe('ADR-0146 D10 — `.custom` relatedLists replaces the tab list whole', () => { + it('two tabs swapped and one hidden: the order changes, the hidden one is not a tab, and the read says who hides it', () => { + const reg = customize(withBase(), { relatedLists: ['crm_event', 'crm_task', { list: 'crm_note', hidden: true }] }); + expect(served(reg).relatedLists).toEqual(['crm_event', 'crm_task']); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: ['crm_note'], unlisted: 'hidden' }); + }); + + it('an original tab the list does not name shows last', () => { + const reg = customize(withBase(), { relatedLists: ['crm_event'] }); + expect(served(reg).relatedLists).toEqual(['crm_event', 'crm_task', 'crm_note']); + }); + + it('…before a trailing approvals / activity-stream run, with the title and columns it had', () => { + const base = vendorLead({ relatedLists: [{ list: 'crm_task', label: 'To do', columns: ['name'] }, 'crm_event', 'sys_activity'] }); + const reg = customize(withBase(base), { relatedLists: ['crm_event', 'sys_approval_request', 'sys_activity'] }); + expect(served(reg).relatedLists).toEqual([ + 'crm_event', + { list: 'crm_task', label: 'To do', columns: ['name'] }, + 'sys_approval_request', + 'sys_activity', + ]); + }); + + it('an extension package\'s placed list the arrangement does not name still shows, after the listed ones', () => { + const reg = customize(withExtensionPackage(withBase()), { relatedLists: ['crm_note', 'crm_task'] }); + expect(served(reg).relatedLists).toEqual(['crm_note', 'crm_task', 'acme_audit', 'crm_event']); + }); + + it('the object form travels as written, without `hidden`; an entry left with its name alone is the bare name', () => { + const reg = customize(withBase(), { + relatedLists: [{ list: 'crm_note', label: 'Notes', columns: ['name'], hidden: false }, { list: 'crm_task', hidden: false }], + }); + expect(served(reg).relatedLists).toEqual([{ list: 'crm_note', label: 'Notes', columns: ['name'] }, 'crm_task', 'crm_event']); + }); + + it('a bare child covers every relationship of that child: hidden whole, or carried only where no entry covers it', () => { + const base = vendorLead({ relatedLists: ['crm_task.lead_id', 'crm_task.converted_lead', 'crm_event', 'crm_note'] }); + const hiddenWhole = customize(withBase(base), { relatedLists: [{ list: 'crm_task', hidden: true }] }); + expect(served(hiddenWhole).relatedLists).toEqual(['crm_event', 'crm_note']); + // One relationship named: the other is not covered, so it is carried over. + const one = customize(withBase(base), { relatedLists: ['crm_note', 'crm_task.converted_lead'] }); + expect(served(one).relatedLists).toEqual(['crm_note', 'crm_task.converted_lead', 'crm_task.lead_id', 'crm_event']); + }); + + it('over the AUTOMATIC tab list (the base declares none): the read says every unnamed list still shows', () => { + const { relatedLists: _none, ...automatic } = vendorLead(); + const reg = customize(withBase(automatic), { relatedLists: ['crm_event', { list: 'crm_note', hidden: true }] }); + expect(served(reg).relatedLists).toEqual(['crm_event']); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: ['crm_note'], unlisted: 'shown' }); + }); + + it('every tab of a declared list hidden: nothing is left to serve, and the read says the list is still a declared one', () => { + // The owner lists two of its three child lists: `crm_note` is hidden by being left out. + const base = vendorLead({ relatedLists: ['crm_task', 'crm_event'] }); + const reg = customize(withBase(base), { + relatedLists: [{ list: 'crm_task', hidden: true }, { list: 'crm_event', hidden: true }], + }); + expect(served(reg).relatedLists).toEqual([]); + // An empty list alone reads as "none declared, every list shows". `unlisted: 'hidden'` is what keeps + // `crm_note` hidden: the record page reads the empty list beside it as a declared one. + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: ['crm_task', 'crm_event'], unlisted: 'hidden' }); + }); + + it('…and a one-entry list whose entry is hidden is the same case', () => { + const reg = customize(withBase(vendorLead({ relatedLists: ['crm_task'] })), { relatedLists: [{ list: 'crm_task', hidden: true }] }); + expect(served(reg).relatedLists).toEqual([]); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: ['crm_task'], unlisted: 'hidden' }); + }); + + it('an empty list hides nothing and reorders nothing', () => { + const declared = customize(withBase(), { relatedLists: [] }); + expect(served(declared).relatedLists).toEqual(['crm_task', 'crm_event', 'crm_note']); + expect(declared.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: [], unlisted: 'hidden' }); + }); +}); + +describe('ADR-0146 D10 — a key the `.custom` package does not write keeps the result of steps 1–2', () => { + it('only `relatedLists` written: the field groups are the base\'s with the extension package\'s placements', () => { + const before = served(withExtensionPackage(withBase())); + const reg = customize(withExtensionPackage(withBase()), { relatedLists: ['crm_note'] }, { fields: {} }); + const body = served(reg); + expect(body.fieldGroups).toEqual(before.fieldGroups); + expect(body.fields).toEqual(before.fields); + expect(layout(body)).toEqual(layout(before)); + }); + + it('only `fieldGroups` written: the tabs are the base\'s with the extension package\'s placements, and nothing is said beside them', () => { + const before = served(withExtensionPackage(withBase())); + const reg = customize(withExtensionPackage(withBase()), { fieldGroups: [{ key: 'basic', label: 'Basic', fields: ['name'] }] }); + expect(served(reg).relatedLists).toEqual(before.relatedLists); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + }); +}); + +describe('ADR-0146 D10 — taking the arrangement away restores steps 1–2', () => { + const ARRANGEMENT = { + fieldGroups: [{ key: 'contact', label: 'Reach', fields: ['email', 'name'] }], + relatedLists: ['crm_note', { list: 'crm_task', hidden: true }], + }; + + it('removing both keys from the `.custom` extension: the object is as it was', () => { + const before = served(customize(withExtensionPackage(withBase()), {})); + const reg = customize(withExtensionPackage(withBase()), ARRANGEMENT); + expect(served(reg).relatedLists).toEqual(['crm_note', 'acme_audit', 'crm_event']); + customize(reg, {}); + expect(served(reg)).toEqual(before); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + }); + + it('uninstalling the `.custom` package: the object is as it was before the package', () => { + const before = served(withExtensionPackage(withBase())); + const reg = customize(withExtensionPackage(withBase()), ARRANGEMENT); + reg.unregisterObjectsByPackage(PAIR); + expect(served(reg)).toEqual(before); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + }); + + it('disabling the `.custom` package: the served object carries none of it, and enabling brings it back', () => { + const before = served(withExtensionPackage(withBase())); + const reg = withExtensionPackage(withBase()); + reg.installPackage({ id: PAIR, name: PAIR, version: '0.1.0', type: 'app', namespace: 'crm_custom' } as never, 'code'); + customize(reg, ARRANGEMENT); + const on = served(reg); + reg.disablePackage(PAIR); + const off = served(reg); + expect(off.fieldGroups).toEqual(before.fieldGroups); + expect(off.relatedLists).toEqual(before.relatedLists); + expect(layout(off)).toEqual(layout(before)); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + reg.enablePackage(PAIR); + expect(served(reg)).toEqual(on); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: ['crm_task'], unlisted: 'hidden' }); + }); + + it('a body that already carries the arrangement folds to itself', () => { + const reg = customize(withExtensionPackage(withBase()), ARRANGEMENT); + const body = served(reg); + const refolded = reg.foldObjectExtendersOnto(OBJ, structuredClone(body)) as any; + expect(refolded.relatedLists).toEqual(body.relatedLists); + expect(refolded.fieldGroups).toEqual(body.fieldGroups); + expect(refolded.fields).toEqual(body.fields); + }); +}); + +describe('ADR-0146 D10 — only a `.custom` package\'s arrangement is applied', () => { + it('another package\'s `fieldGroups` and `relatedLists` are skipped, each named once, prescribing `place`', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const before = served(withBase()); + const reg = customize(withBase(), { + fieldGroups: [{ key: 'contact', label: 'Reach', fields: ['email'] }], + relatedLists: ['crm_note'], + }, { pkg: EXT, fields: {} }); + const body = served(reg); + served(reg); + reg.foldObjectExtendersOnto(OBJ, vendorLead()); + expect(body.fieldGroups).toEqual(before.fieldGroups); + expect(body.relatedLists).toEqual(before.relatedLists); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('is not applied')); + expect(lines).toHaveLength(2); + for (const [line, key] of [[lines[0], 'fieldGroups'], [lines[1], 'relatedLists']] as const) { + expect(line).toContain(`from package "${EXT}"`); + expect(line).toContain(`\`${key}\``); + expect(line).toContain('`place`'); + } + }); + + it('a `.custom` package that is not the object\'s pair is skipped and named, beside the pair and alone', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const OTHER = 'com.acme.tax.custom'; + // Beside the pair, and folded after it: the pair is served. + const reg = withBase(); + customize(reg, { relatedLists: ['crm_note'] }, { fields: {} }); + customize(reg, { relatedLists: ['crm_event'] }, { pkg: OTHER, fields: {} }); + expect(served(reg).relatedLists).toEqual(['crm_note', 'crm_task', 'crm_event']); + expect(reg.getRelatedListsArrangement(OBJ)?.packageId).toBe(PAIR); + // Alone: nothing is applied, as for any package that is not the pair. + const before = served(withBase()); + const alone = customize(withBase(), { + fieldGroups: [{ key: 'contact', label: 'Reach', fields: ['email'] }], + relatedLists: ['crm_event'], + }, { pkg: OTHER, fields: {} }); + expect(served(alone).fieldGroups).toEqual(before.fieldGroups); + expect(served(alone).relatedLists).toEqual(before.relatedLists); + expect(alone.getRelatedListsArrangement(OBJ)).toBeUndefined(); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('is not the customization package of this object')); + expect(lines).toHaveLength(3); + for (const line of lines) { + expect(line).toContain(`from package "${OTHER}"`); + expect(line).toContain(`(that is "${PAIR}")`); + } + }); +}); + +describe('ADR-0146 D10 — the pair is the App\'s, chosen by role (an object a module owns)', () => { + const APP = 'com.hotcrm'; + const MODULE = 'com.hotcrm.sales'; + const APP_PAIR = 'com.hotcrm.custom'; + const MEMBER_PAIR = 'com.hotcrm.sales.custom'; + const OTHER_PAIR = 'com.acme.custom'; + + /** The App and the module of it that owns the lead, as the registry holds two installed packages. */ + function hotcrm(): SchemaRegistry { + const reg = registry(); + reg.installPackage({ id: APP, name: APP, version: '1.0.0', type: 'app', namespace: 'hotcrm' } as never, 'code'); + reg.installPackage({ id: MODULE, name: MODULE, version: '1.0.0', type: 'module', namespace: 'crm', dependencies: { [APP]: '^1.0.0' } } as never, 'code'); + reg.registerObject(vendorLead(), MODULE, undefined, 'own'); + for (const [name, label] of [['crm_task', 'Task'], ['crm_event', 'Event'], ['crm_note', 'Note']]) { + reg.registerObject(child(name, label) as any, MODULE, undefined, 'own'); + } + return reg; + } + + it.each([ + ['the App\'s pair folded first', [APP_PAIR, OTHER_PAIR]], + ['the App\'s pair folded last', [OTHER_PAIR, APP_PAIR]], + ])('two writers, %s: the App\'s pair is served and the other is named', (_label, order) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const lists: Record = { [APP_PAIR]: ['crm_note'], [OTHER_PAIR]: ['crm_event'] }; + const reg = hotcrm(); + for (const pkg of order) customize(reg, { relatedLists: lists[pkg] }, { pkg, fields: {} }); + expect(served(reg).relatedLists).toEqual(['crm_note', 'crm_task', 'crm_event']); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: APP_PAIR, hidden: [], unlisted: 'hidden' }); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('is not applied')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(`from package "${OTHER_PAIR}"`); + expect(lines[0]).toContain(`(that is "${APP_PAIR}")`); + }); + + it('a `.custom` id named after the module is not the pair of the module\'s object: the unit is the App', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const before = served(hotcrm()); + const reg = customize(hotcrm(), { relatedLists: ['crm_event'] }, { pkg: MEMBER_PAIR, fields: {} }); + expect(served(reg).relatedLists).toEqual(before.relatedLists); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('is not applied')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(`from package "${MEMBER_PAIR}"`); + expect(lines[0]).toContain(`(that is "${APP_PAIR}")`); + }); + + it('a per-package pair an earlier version created is still read while installed, and the App\'s pair comes first', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const legacy = (): SchemaRegistry => { + const reg = hotcrm(); + reg.installPackage({ id: MEMBER_PAIR, name: MEMBER_PAIR, version: '1.0.0' } as never, 'code'); + return reg; + }; + // Alone, the installed per-package pair is served as it is. + const alone = customize(legacy(), { relatedLists: ['crm_event'] }, { pkg: MEMBER_PAIR, fields: {} }); + expect(served(alone).relatedLists).toEqual(['crm_event', 'crm_task', 'crm_note']); + expect(alone.getRelatedListsArrangement(OBJ)?.packageId).toBe(MEMBER_PAIR); + // Beside the App's pair, whichever folds first, the App's pair is served and the other is named. + for (const order of [[APP_PAIR, MEMBER_PAIR], [MEMBER_PAIR, APP_PAIR]]) { + warn.mockClear(); + const lists: Record = { [APP_PAIR]: ['crm_note'], [MEMBER_PAIR]: ['crm_event'] }; + const reg = legacy(); + for (const pkg of order) customize(reg, { relatedLists: lists[pkg] }, { pkg, fields: {} }); + expect(served(reg).relatedLists).toEqual(['crm_note', 'crm_task', 'crm_event']); + expect(reg.getRelatedListsArrangement(OBJ)?.packageId).toBe(APP_PAIR); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('one arrangement is served')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(`from package "${MEMBER_PAIR}"`); + expect(lines[0]).toContain(`package "${APP_PAIR}"`); + } + }); + + it('the App\'s pair alone arranges the module\'s object', () => { + const reg = customize(hotcrm(), { relatedLists: ['crm_event', { list: 'crm_note', hidden: true }] }, { pkg: APP_PAIR, fields: {} }); + expect(served(reg).relatedLists).toEqual(['crm_event', 'crm_task']); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: APP_PAIR, hidden: ['crm_note'], unlisted: 'hidden' }); + }); +}); + +describe('ADR-0146 D10 — the pure step', () => { + it('answers the object by reference when no contributor writes an arrangement key', () => { + const object = vendorLead(); + const result = applyCustomArrangement(object, [ + { packageId: EXT, ownership: 'extend', priority: 200, definition: { name: OBJ, fields: {} } } as never, + ], { objectName: OBJ, customizationPairs: () => { throw new Error('the pairs are asked only when a key is written'); } }); + expect(result.object).toBe(object); + expect(result.notes).toEqual([]); + expect(result.relatedLists).toBeUndefined(); + }); + + it('the arrangement the tests above register is one the schema parses', () => { + const parsed = ObjectExtensionSchema.safeParse({ + extend: OBJ, + fields: { region__c: { type: 'text', label: 'Region' } }, + fieldGroups: [ + { key: 'contact', label: 'Reach', fields: ['email', 'phone', 'fax', 'status'] }, + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'region__c'] }, + ], + relatedLists: ['crm_event', 'crm_task', { list: 'crm_note', hidden: true }], + }); + expect(parsed.success).toBe(true); + }); +}); diff --git a/packages/objectql/src/registry-custom-arrangement.ts b/packages/objectql/src/registry-custom-arrangement.ts new file mode 100644 index 00000000000..0ce324d8158 --- /dev/null +++ b/packages/objectql/src/registry-custom-arrangement.ts @@ -0,0 +1,315 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] The third layer of an installed object's record-page + * arrangement: the whole arrangement the base's paired `.custom` package + * declares, applied by the registry fold (`foldExtendersOntoDefinition`) + * LAST, after every extension's `place` entries + * (`applyExtensionPlacements`), so the record page, the forms, the preview + * and Studio read one result. + * + * 1. the owner's arrangement (the object's `fieldGroups` / `relatedLists`); + * 2. each extension's `place` entries, inserted into it; + * 3. where the `.custom` extension writes `fieldGroups` or `relatedLists` + * (`CUSTOM_ARRANGEMENT_KEYS`), that key REPLACES the result of 1–2, + * whole. A key it does not write keeps that result. Nothing is merged + * entry by entry. + * + * What the replacement leaves to the object's own rules: + * + * - a FIELD no group of the arrangement lists is never dropped: it shows + * after the last group (`deriveFieldGroupLayout`'s trailing bucket), + * whatever group the owner or another extension had put it in. Replaced + * whole means their membership statements are replaced in either + * spelling: a group that lists `fields` shows exactly its list, so a + * field of theirs that no list names loses a `group` naming such a group + * or a group the arrangement does not have, and a listed field's own + * `group` is rewritten to the group that lists it. The arrangement's own statements stay the object's rule: a field + * the `.custom` extension declares keeps its `group`, and a group that + * lists no `fields` keeps the fields whose `group` names it. A `group` + * naming a group that now places a body table is taken off. The served + * object stays one an object parse accepts; + * - a TAB the arrangement does not name is not hidden, the reverse of an + * object's own `relatedLists`. Where steps 1–2 gave a declared tab list, + * each of its entries no entry of the arrangement covers is carried over, + * after the listed ones and before a trailing approvals / activity-stream + * run. Where they gave none (the automatic list: every list shows), the + * served object says so beside its `relatedLists` + * ({@link RelatedListsArrangement}, `unlisted: 'shown'`), because only + * the record page knows which lists exist for the reader. The lists the + * arrangement hides (`{ list, hidden: true }`) travel the same way: a + * served `relatedLists` cannot hide another package's list by leaving it + * out. Where the arrangement hides every tab of a declared list, nothing + * is left to serve: the served `relatedLists` is empty, and + * `unlisted: 'hidden'` beside it says it is still a declared list, so a + * list the owner hid by leaving it out stays hidden. + * + * Only the object's own pair is served: the customization package of the App + * the object's owner belongs to, as `@objectstack/metadata-core`'s pair lookup + * answers it (`pairsOf` over the installed manifests: the App's pair, then a + * per-package pair an earlier version created, while one is installed; where + * both write a key the App's pair is served and the other is named). The + * choice is by role, never by fold order (ADR-0146 D2): a `.custom` package + * that is not the object's pair is skipped and named, whether it writes the + * key alone or beside the pair. The doors refuse a writer that is not a + * `.custom` package (`isCustomizationPackage`, the `__c` judge's predicate) at + * publish, `os validate` / `os build` and install; a manifest's body reaches + * the registry unparsed, so the fold skips such a key too and names it. + * + * Nothing here is stored: disabling or uninstalling the `.custom` package, + * or removing the key, leaves its contribution out of the fold, and the + * result of steps 1–2 is served again. + */ + +import { + extensionArrangementKeys, + relatedListEntryHidden, + relatedListEntryName, + relatedListNameCovers, +} from '@objectstack/spec/data'; +import type { CustomArrangementKey, RelatedListsArrangement, ServiceObject } from '@objectstack/spec/data'; +import { isCustomizationPackage } from '@objectstack/spec/kernel'; +import type { ExtensionPlacementNote } from './registry-extension-placement.js'; +import type { ObjectContributor } from './registry-top-level.js'; + +/** The record-page tabs a trailing run of which the carried-over tabs go before. */ +const TRAILING_BUILTIN_TABS: ReadonlySet = new Set(['sys_approval_request', 'sys_activity']); + +type AnyRecord = Record; + +function isRecord(value: unknown): value is AnyRecord { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** What the fold knows beyond the object itself. */ +export interface CustomArrangementContext { + /** The extended object's name, for the notes. */ + readonly objectName: string; + /** + * The packages whose rows are this object's customizations, the one served + * first: `pairsOf(owner, installed)` of `@objectstack/metadata-core` over the + * registry's installed manifests (the pair of the owner's App, then a + * per-package pair an earlier version created). Empty when the object has + * no pair (it is registered with no package). Asked only when an extension + * writes an arrangement key. + */ + readonly customizationPairs: () => readonly string[]; +} + +/** What {@link applyCustomArrangement} answers. */ +export interface CustomArrangementResult { + /** The object to serve (by reference when no `.custom` arrangement applies). */ + readonly object: ServiceObject; + /** What was skipped, named once by the fold. */ + readonly notes: ExtensionPlacementNote[]; + /** + * What the served `relatedLists` cannot say about the `.custom` tab list: + * the served read's `_relatedListsArrangement` decoration. `undefined` when + * no `.custom` package arranges the tabs. + */ + readonly relatedLists: RelatedListsArrangement | undefined; +} + +/** + * The served objects whose tabs a `.custom` package arranges, each with what + * its `relatedLists` cannot say. Keyed on the served body's identity, so a + * fold of other contributors (a package's own export layer, a disabled + * package folded back in) answers for itself, and an entry leaves with the + * body it describes. + */ +const servedRelatedListsArrangements = new WeakMap(); + +/** Record what a served body's `relatedLists` cannot say. The fold calls it once per body. */ +export function rememberRelatedListsArrangement(served: unknown, arrangement: RelatedListsArrangement | undefined): void { + if (arrangement === undefined || typeof served !== 'object' || served === null) return; + servedRelatedListsArrangements.set(served, arrangement); +} + +/** What a served body's `relatedLists` cannot say, or `undefined` when no `.custom` package arranges its tabs. */ +export function relatedListsArrangementOf(served: unknown): RelatedListsArrangement | undefined { + return typeof served === 'object' && served !== null ? servedRelatedListsArrangements.get(served) : undefined; +} + +/** One `.custom` (or refused) writer of an arrangement key. */ +interface ArrangementWriter { + readonly packageId: string | undefined; + readonly body: AnyRecord; +} + +/** + * [ADR-0146 D10] Apply the paired `.custom` package's arrangement to `object` + * (the fold's merged body, placements applied). Pure: the caller names the + * notes and records the tab arrangement. + */ +export function applyCustomArrangement( + object: ServiceObject, + contributors: readonly ObjectContributor[], + context: CustomArrangementContext, +): CustomArrangementResult { + const notes: ExtensionPlacementNote[] = []; + const writers = new Map(); + for (const contributor of contributors) { + if (contributor.ownership !== 'extend') continue; + const body = contributor.definition as unknown; + if (!isRecord(body)) continue; + for (const key of extensionArrangementKeys(body)) { + const list = writers.get(key) ?? []; + list.push({ packageId: contributor.packageId, body }); + writers.set(key, list); + } + } + if (writers.size === 0) return { object, notes, relatedLists: undefined }; + + const objectName = context.objectName; + const from = (packageId: string | undefined): string => (packageId ? ` from package "${packageId}"` : ''); + const note = (writer: ArrangementWriter, key: CustomArrangementKey, message: string): void => { + const text = `[Registry] An extension of object "${objectName}"${from(writer.packageId)} ${message}`; + notes.push({ key: `arrangement|${key}|${text}`, packageId: writer.packageId, message: text }); + }; + + // By role, never by fold order (ADR-0146 D2): the object's own pairs, the + // App's first. + const pairs = context.customizationPairs(); + + /** The one writer of `key` the fold serves, the others named. */ + const servedWriter = (key: CustomArrangementKey): ArrangementWriter | undefined => { + const admitted: Array = []; + for (const writer of writers.get(key) ?? []) { + const packageId = writer.packageId; + if (typeof packageId !== 'string' || !isCustomizationPackage(packageId)) { + note(writer, key, + `declares \`${key}\`, which is not applied: only the object extension of a base's paired \`.custom\` ` + + 'package declares the whole arrangement of an object. An extension places the fields, groups and ' + + 'child lists it brings with `place`.'); + continue; + } + if (!pairs.includes(packageId)) { + note(writer, key, + `declares \`${key}\`, which is not applied: it is not the customization package of this object` + + (pairs.length > 0 ? ` (that is "${pairs[0]}")` : ', which has none') + + '. Only the paired `.custom` package of the App an object belongs to declares its arrangement.'); + continue; + } + if (!Array.isArray(writer.body[key])) { + note(writer, key, `declares \`${key}\` that is not a list, so it is not applied.`); + continue; + } + admitted.push({ ...writer, packageId }); + } + if (admitted.length === 0) return undefined; + // Every admitted writer is one of `pairs`; the one listed first there is served. + const served = admitted.reduce((best, writer) => + (pairs.indexOf(writer.packageId) < pairs.indexOf(best.packageId) ? writer : best)); + for (const writer of admitted) { + if (writer === served) continue; + note(writer, key, + `declares \`${key}\`, which is not applied: package "${served.packageId}" declares it for this object ` + + 'too, and one arrangement is served. Keep it in one package.'); + } + return served; + }; + + const record = object as unknown as AnyRecord; + const out: AnyRecord = { ...record }; + let changed = false; + let relatedLists: RelatedListsArrangement | undefined; + + // ── fieldGroups ───────────────────────────────────────────────────────── + const groupsWriter = servedWriter('fieldGroups'); + if (groupsWriter !== undefined) { + const groups = (groupsWriter.body.fieldGroups as unknown[]).filter(isRecord).map((group) => ({ ...group })); + out.fieldGroups = groups; + changed = true; + // Replaced whole means the membership the owner and the other extensions + // stated is replaced too, in either spelling. A group that lists `fields` + // shows exactly its list: a listed field's own `group` follows the group + // that lists it, and a field of the object or of another extension that + // no list names loses a `group` naming a listing group, or a group the + // arrangement does not have (a placement's `group` names the owner's + // group, which is gone with the owner's list), so it shows after the + // last group. The arrangement's own statements stay: a field this + // extension declares keeps its `group`, and a group that lists no + // `fields` keeps the fields whose `group` names it. No field names a + // group that places a body table (a refusal on an object parse). + const listedIn = new Map(); + const groupKeys = new Set(); + const listingGroups = new Set(); + const tableGroups = new Set(); + for (const group of groups) { + if (typeof group.key !== 'string') continue; + groupKeys.add(group.key); + if (typeof group.relatedList === 'string') { + tableGroups.add(group.key); + continue; + } + if (!Array.isArray(group.fields)) continue; + listingGroups.add(group.key); + for (const name of group.fields) { + if (typeof name === 'string' && !listedIn.has(name)) listedIn.set(name, group.key); + } + } + const declaredHere = isRecord(groupsWriter.body.fields) ? groupsWriter.body.fields : {}; + if (isRecord(record.fields)) { + let fields: AnyRecord | undefined; + for (const [name, field] of Object.entries(record.fields)) { + if (!isRecord(field) || typeof field.group !== 'string') continue; + const listing = listedIn.get(name); + if (listing !== undefined) { + if (field.group !== listing) fields = { ...(fields ?? record.fields), [name]: { ...field, group: listing } }; + continue; + } + const own = Object.prototype.hasOwnProperty.call(declaredHere, name); + const replaced = !groupKeys.has(field.group) || listingGroups.has(field.group); + if (tableGroups.has(field.group) || (replaced && !own)) { + const { group: _replaced, ...rest } = field; + fields = { ...(fields ?? record.fields), [name]: rest }; + } + } + if (fields !== undefined) out.fields = fields; + } + } + + // ── relatedLists ──────────────────────────────────────────────────────── + const tabsWriter = servedWriter('relatedLists'); + if (tabsWriter !== undefined && typeof tabsWriter.packageId === 'string') { + const declared = tabsWriter.body.relatedLists as unknown[]; + const shown: unknown[] = []; + const hidden: string[] = []; + const named: string[] = []; + for (const entry of declared) { + const name = relatedListEntryName(entry); + if (name === undefined || name === '') continue; + named.push(name); + if (relatedListEntryHidden(entry)) { + if (!hidden.includes(name)) hidden.push(name); + continue; + } + if (isRecord(entry)) { + // `hidden: false` says nothing the served entry needs; an entry left + // with its name alone is the bare name. + const { hidden: _shown, ...rest } = entry; + shown.push(Object.keys(rest).length === 1 ? name : rest); + } else { + shown.push(entry); + } + } + // The tab list steps 1–2 gave: declared (non-empty), or the automatic one. + const before = Array.isArray(record.relatedLists) ? record.relatedLists : []; + const carried = before.filter((entry) => { + const name = relatedListEntryName(entry); + return name !== undefined && name !== '' && !named.some((written) => relatedListNameCovers(written, name)); + }); + let end = shown.length; + while (end > 0 && TRAILING_BUILTIN_TABS.has(relatedListEntryName(shown[end - 1]) ?? '')) end -= 1; + out.relatedLists = [...shown.slice(0, end), ...carried, ...shown.slice(end)]; + changed = true; + relatedLists = { + packageId: tabsWriter.packageId, + hidden, + unlisted: before.length > 0 ? 'hidden' : 'shown', + }; + } + + if (!changed) return { object, notes, relatedLists: undefined }; + return { object: out as unknown as ServiceObject, notes, relatedLists }; +} diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index 6e2e2bbc1ec..3eaa3c2318b 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -46,13 +46,14 @@ */ import { BASE_FIELD_DISPLAY_WHITELIST, isInjectedColumnDefinition, materializeTreeSelfReferences, provisionPrimary, resolveInjectedSystemColumns } from '@objectstack/spec/data'; -import type { ObjectOwnership, ServiceObject } from '@objectstack/spec/data'; -import { QUEUE_FIELD_DEF, applyAuditFieldGovernance, fieldPatchTargetMisses, isCodeArtifactBody, isTenantAuthored } from '@objectstack/metadata-core'; +import type { ObjectOwnership, RelatedListsArrangement, ServiceObject } from '@objectstack/spec/data'; +import { QUEUE_FIELD_DEF, applyAuditFieldGovernance, fieldPatchTargetMisses, installedManifestsOf, isCodeArtifactBody, isTenantAuthored, pairsOf } from '@objectstack/metadata-core'; import type { FieldPatchTargetMiss } from '@objectstack/metadata-core'; import { scalarOverridesPackagedBase } from '@objectstack/spec/system'; import { SEARCH_COMPANION_FIELD, provisionSearchCompanion } from './search-companion.js'; import { applyExtensionPlacements, fieldGroupKeysOf, placementContributorsOf } from './registry-extension-placement.js'; import type { ExtensionPlacementNote } from './registry-extension-placement.js'; +import { applyCustomArrangement, relatedListsArrangementOf, rememberRelatedListsArrangement } from './registry-custom-arrangement.js'; import { applyProtection } from '@objectstack/spec/shared'; import { isObjectLessActionKey, standaloneActionOwnerKey } from './action-governance.js'; import { recordCurrencyFollowRefusal, recordCurrencySummaryRefusal } from './record-currency-aggregate-door.js'; @@ -107,6 +108,7 @@ export interface ObjectRegistrationHost { getObject: SchemaRegistry['getObject']; getObjectContributors: SchemaRegistry['getObjectContributors']; getObjectOwner: SchemaRegistry['getObjectOwner']; + getPackage: SchemaRegistry['getPackage']; hasDisabledPackage: SchemaRegistry['hasDisabledPackage']; isActionWithheldByDisabledPackage: SchemaRegistry['isActionWithheldByDisabledPackage']; isPackageDisabled: SchemaRegistry['isPackageDisabled']; @@ -783,6 +785,31 @@ export class ObjectRegistrationFacet { return { kept, withheldFields, withheldRules, withheldIndexes }; } + /** + * [ADR-0146 D10] The body, and the contract, of + * `SchemaRegistry#getRelatedListsArrangement` (the facade keeps its line + * count, so the docblock lives here). + * + * What the served `relatedLists` of `name` cannot say about the tab list + * the base's paired `.custom` package declares for it: the lists it hides, + * and whether a list no entry names is shown after the listed tabs + * (`RelatedListsArrangement`, `@objectstack/spec/data`). `undefined` when + * no `.custom` package arranges the object's tabs: none extends it, none + * writes `relatedLists`, or the one that does is disabled. + * + * The served object read stamps this as its `_relatedListsArrangement` read + * decoration, because only the record page knows which lists exist for the + * reader: a served `relatedLists` names tabs and cannot hide another + * package's list by leaving it out. Accepts a short name or an FQN, as + * `getObject` does. Read off the served fold's own body + * ({@link resolveObject}), so this answer and the served `relatedLists` + * cannot disagree. + */ + static getRelatedListsArrangement(this: Pick, name: string): RelatedListsArrangement | undefined { + const fqn = this.resolveObjectKey(name); + return fqn === undefined ? undefined : relatedListsArrangementOf(this.resolveObject(fqn)); + } + /** * [#34901] The body of `SchemaRegistry#getWithheldExtensionFields`; the * method's docblock there is its contract. Read off @@ -865,7 +892,7 @@ export class ObjectRegistrationFacet { * {@link foldObjectExtendersOnto} can apply it to a body that never came * from this registry without growing a second copy of the merge. */ - static foldExtendersOntoDefinition(this: Pick, contributors: ObjectContributor[], baseDefinition: ServiceObject, layer: ServedObjectLayer = 'served'): ServiceObject { + static foldExtendersOntoDefinition(this: Pick, contributors: ObjectContributor[], baseDefinition: ServiceObject, layer: ServedObjectLayer = 'served'): ServiceObject { // [ADR-0029 D9.2a] Computed ONCE, over the base the fold starts from — never // re-derived from the running `merged`, which would make an extender's own // scalar look "authored" to the next extender and silently invert @@ -960,11 +987,25 @@ export class ObjectRegistrationFacet { merged = placed.object; this.reportExtensionPlacements(placed.notes); } + // [ADR-0146 D10] The third layer, last: where the base's paired `.custom` + // package writes `fieldGroups` or `relatedLists`, that key replaces the + // arrangement the owner and the placements above gave, whole. The pair is + // the owner's App's, asked of the one pair lookup (ADR-0146 D3). + const arranged = applyCustomArrangement(merged, contributors, { + objectName: String(merged.name ?? baseDefinition.name ?? ''), + customizationPairs: () => pairsOf(contributors.find((c) => c.ownership === 'own')?.packageId, installedManifestsOf(this)), + }); + merged = arranged.object; + this.reportExtensionPlacements(arranged.notes); if (tenantRules) this.reportChangedRuleCopies(contributors, baseDefinition); // A picklist-bound field is served with its list's options resolved onto // it — here, in the fold every object read and the write door share, so // the set a client is offered and the set a write is judged by are one. - return this.finishServedObject(merged, layer, picklistReferrerOf(contributors)); + const served = this.finishServedObject(merged, layer, picklistReferrerOf(contributors)); + // …and what the `.custom` tab list says that `relatedLists` cannot travels + // beside the body it describes ({@link getRelatedListsArrangement}). + rememberRelatedListsArrangement(served, arranged.relatedLists); + return served; } /** diff --git a/packages/objectql/src/registry-revision.ts b/packages/objectql/src/registry-revision.ts index cf97c60eff3..6f4ecbbcbe2 100644 --- a/packages/objectql/src/registry-revision.ts +++ b/packages/objectql/src/registry-revision.ts @@ -88,6 +88,7 @@ export const SCHEMA_REGISTRY_METHOD_KINDS: Readonly registry.getObject(...a), getObjectContributors: (...a) => registry.getObjectContributors(...a), getObjectOwner: (...a) => registry.getObjectOwner(...a), + getPackage: (...a) => registry.getPackage(...a), hasDisabledPackage: (...a) => registry.hasDisabledPackage(...a), isActionWithheldByDisabledPackage: (...a) => registry.isActionWithheldByDisabledPackage(...a), isPackageDisabled: (...a) => registry.isPackageDisabled(...a), diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 1d3ea53d301..fa1e0431b47 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -117,6 +117,7 @@ "CROSS_FIELD_COMPARISON_TYPE_CLASSES (const)", "CROSS_FIELD_NO_CLASS_REASONS (const)", "CURRENCY_FRACTION_DIGITS (const)", + "CUSTOM_ARRANGEMENT_KEYS (const)", "CalendarDateValue (type)", "CalendarDateValueSchema (const)", "ClockTimeValue (type)", @@ -163,6 +164,7 @@ "CurrencyConfig (type)", "CurrencyConfigParsed (type)", "CurrencyConfigSchema (const)", + "CustomArrangementKey (type)", "CustomPersistenceConfig (type)", "CustomPersistenceConfigSchema (const)", "DATABASE_DRIVER_SELECTION_ALIASES (const)", @@ -604,6 +606,11 @@ "ObjectExtensionPlacement (type)", "ObjectExtensionPlacementParsed (type)", "ObjectExtensionPlacementSchema (const)", + "ObjectExtensionRelatedListEntry (type)", + "ObjectExtensionRelatedListEntryObject (interface)", + "ObjectExtensionRelatedListEntryObjectSchema (const)", + "ObjectExtensionRelatedListEntryParsed (type)", + "ObjectExtensionRelatedListEntrySchema (const)", "ObjectExtensionSchema (const)", "ObjectExternalBinding (type)", "ObjectExternalBindingParsed (type)", @@ -706,6 +713,7 @@ "RECYCLE_BIN_RESTORE_REFUSAL_STATUS (const)", "RECYCLE_BIN_RETENTION_DAYS_ENV (const)", "REFERENCE_VALUE_TYPES (const)", + "RELATED_LISTS_ARRANGEMENT_DECORATION (const)", "RELATED_LIST_BUILTIN_PART_OF (const)", "RETIRED_DRIVER_ID_GUIDANCE (const)", "RETIRED_FILTER_OPERATORS (const)", @@ -766,6 +774,7 @@ "RelatedListEntryParsed (type)", "RelatedListEntrySchema (const)", "RelatedListRelationshipFields (interface)", + "RelatedListsArrangement (interface)", "RenderAutonumberInput (interface)", "RenderedAutonumber (interface)", "ReplicationConfig (type)", @@ -1038,6 +1047,7 @@ "effectiveOperationsArray (function)", "emptyGroupValueFor (function)", "expandEmptyOperator (function)", + "extensionArrangementKeys (function)", "externalBindingDatasourceRefusal (function)", "externalColumnMapTargets (function)", "fieldForm (const)", @@ -1164,6 +1174,7 @@ "readBooleanComparand (function)", "readFieldGroupMembership (function)", "readNumericString (function)", + "readRelatedListsArrangement (function)", "recordCurrencyDynamicRollupNotHomeError (function)", "recordCurrencyFollowedCodeError (function)", "recordCurrencyRecordRollupError (function)", @@ -1184,7 +1195,9 @@ "refusedCredentialPathsOfSchema (function)", "refusedInlineCredentialKey (function)", "refusedPassthroughSecretPaths (function)", + "relatedListEntryHidden (function)", "relatedListEntryName (function)", + "relatedListNameCovers (function)", "renderAutonumber (function)", "resolveAutonumberFormat (function)", "resolveBulkPerRowHookBudget (function)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 87e905cc603..be25a0054b7 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -739,6 +739,7 @@ "data/ObjectDependencyNode:references", "data/ObjectExtension:description", "data/ObjectExtension:extend", + "data/ObjectExtension:fieldGroups", "data/ObjectExtension:fieldPatches", "data/ObjectExtension:fields", "data/ObjectExtension:indexes", @@ -746,6 +747,7 @@ "data/ObjectExtension:place", "data/ObjectExtension:pluralLabel", "data/ObjectExtension:priority", + "data/ObjectExtension:relatedLists", "data/ObjectExtension:validations", "data/ObjectExtensionFieldPlacement:after", "data/ObjectExtensionFieldPlacement:before", @@ -759,6 +761,10 @@ "data/ObjectExtensionListPlacement:columns", "data/ObjectExtensionListPlacement:label", "data/ObjectExtensionListPlacement:list", + "data/ObjectExtensionRelatedListEntryObject:columns", + "data/ObjectExtensionRelatedListEntryObject:hidden", + "data/ObjectExtensionRelatedListEntryObject:label", + "data/ObjectExtensionRelatedListEntryObject:list", "data/ObjectExternalBinding:columnMap", "data/ObjectExternalBinding:ignoreColumns", "data/ObjectExternalBinding:introspectedAt", diff --git a/packages/spec/declaration-map/data.json b/packages/spec/declaration-map/data.json index 0fe438a6de8..a1fe37afb61 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -235,6 +235,10 @@ "ObjectExtensionListPlacementSchema": "data/ObjectExtensionListPlacement", "ObjectExtensionPlacement": "data/ObjectExtensionPlacement", "ObjectExtensionPlacementSchema": "data/ObjectExtensionPlacement", + "ObjectExtensionRelatedListEntry": "data/ObjectExtensionRelatedListEntry", + "ObjectExtensionRelatedListEntryObject": "data/ObjectExtensionRelatedListEntryObject", + "ObjectExtensionRelatedListEntryObjectSchema": "data/ObjectExtensionRelatedListEntryObject", + "ObjectExtensionRelatedListEntrySchema": "data/ObjectExtensionRelatedListEntry", "ObjectExtensionSchema": "data/ObjectExtension", "ObjectExternalBinding": "data/ObjectExternalBinding", "ObjectExternalBindingSchema": "data/ObjectExternalBinding", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 27eba52bc46..10b7e6aa332 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -114,6 +114,7 @@ "CROSS_FIELD_COMPARISON_TYPE_CLASSES": "src/data/filter-cross-field-comparison-class.ts#CROSS_FIELD_COMPARISON_TYPE_CLASSES (const)", "CROSS_FIELD_NO_CLASS_REASONS": "src/data/filter-cross-field-comparison-class.ts#CROSS_FIELD_NO_CLASS_REASONS (const)", "CURRENCY_FRACTION_DIGITS": "src/data/currency-fraction-digits.ts#CURRENCY_FRACTION_DIGITS (const)", + "CUSTOM_ARRANGEMENT_KEYS": "src/data/field-customization.ts#CUSTOM_ARRANGEMENT_KEYS (const)", "CalendarDateValue": "src/data/field-value.zod.ts#CalendarDateValue (type)", "CalendarDateValueSchema": "src/data/field-value.zod.ts#CalendarDateValueSchema (const)", "ClockTimeValue": "src/data/field-value.zod.ts#ClockTimeValue (type)", @@ -160,6 +161,7 @@ "CurrencyConfig": "src/data/field.zod.ts#CurrencyConfig (type)", "CurrencyConfigParsed": "src/data/field.zod.ts#CurrencyConfigParsed (type)", "CurrencyConfigSchema": "src/data/field.zod.ts#CurrencyConfigSchema (const)", + "CustomArrangementKey": "src/data/field-customization.ts#CustomArrangementKey (type)", "CustomPersistenceConfig": "src/data/driver/memory.zod.ts#CustomPersistenceConfig (type)", "CustomPersistenceConfigSchema": "src/data/driver/memory.zod.ts#CustomPersistenceConfigSchema (const)", "DATABASE_DRIVER_SELECTION_ALIASES": "src/data/driver/config-registry.zod.ts#DATABASE_DRIVER_SELECTION_ALIASES (const)", @@ -593,6 +595,11 @@ "ObjectExtensionPlacement": "src/data/object.zod.ts#ObjectExtensionPlacement (type)", "ObjectExtensionPlacementParsed": "src/data/object.zod.ts#ObjectExtensionPlacementParsed (type)", "ObjectExtensionPlacementSchema": "src/data/object.zod.ts#ObjectExtensionPlacementSchema (const)", + "ObjectExtensionRelatedListEntry": "src/data/object.zod.ts#ObjectExtensionRelatedListEntry (type)", + "ObjectExtensionRelatedListEntryObject": "src/data/related-list-entry.ts#ObjectExtensionRelatedListEntryObject (interface)", + "ObjectExtensionRelatedListEntryObjectSchema": "src/data/object.zod.ts#ObjectExtensionRelatedListEntryObjectSchema (const)", + "ObjectExtensionRelatedListEntryParsed": "src/data/object.zod.ts#ObjectExtensionRelatedListEntryParsed (type)", + "ObjectExtensionRelatedListEntrySchema": "src/data/object.zod.ts#ObjectExtensionRelatedListEntrySchema (const)", "ObjectExtensionSchema": "src/data/object.zod.ts#ObjectExtensionSchema (const)", "ObjectExternalBinding": "src/data/object.zod.ts#ObjectExternalBinding (type)", "ObjectExternalBindingParsed": "src/data/object.zod.ts#ObjectExternalBindingParsed (type)", @@ -695,6 +702,7 @@ "RECYCLE_BIN_RESTORE_REFUSAL_STATUS": "src/data/recycle-bin.zod.ts#RECYCLE_BIN_RESTORE_REFUSAL_STATUS (const)", "RECYCLE_BIN_RETENTION_DAYS_ENV": "src/data/recycle-bin.zod.ts#RECYCLE_BIN_RETENTION_DAYS_ENV (const)", "REFERENCE_VALUE_TYPES": "src/data/field-value.zod.ts#REFERENCE_VALUE_TYPES (const)", + "RELATED_LISTS_ARRANGEMENT_DECORATION": "src/data/related-list-entry.ts#RELATED_LISTS_ARRANGEMENT_DECORATION (const)", "RELATED_LIST_BUILTIN_PART_OF": "src/data/related-list-entry.ts#RELATED_LIST_BUILTIN_PART_OF (const)", "RETIRED_DRIVER_ID_GUIDANCE": "src/data/driver/config-registry.zod.ts#RETIRED_DRIVER_ID_GUIDANCE (const)", "RETIRED_FILTER_OPERATORS": "src/data/filter.zod.ts#RETIRED_FILTER_OPERATORS (const)", @@ -754,6 +762,7 @@ "RelatedListEntryParsed": "src/data/object.zod.ts#RelatedListEntryParsed (type)", "RelatedListEntrySchema": "src/data/object.zod.ts#RelatedListEntrySchema (const)", "RelatedListRelationshipFields": "src/data/related-list-body-table.ts#RelatedListRelationshipFields (interface)", + "RelatedListsArrangement": "src/data/related-list-entry.ts#RelatedListsArrangement (interface)", "RenderAutonumberInput": "src/data/autonumber-format.ts#RenderAutonumberInput (interface)", "RenderedAutonumber": "src/data/autonumber-format.ts#RenderedAutonumber (interface)", "ReplicationConfig": "src/data/driver-nosql.zod.ts#ReplicationConfig (type)", @@ -1023,6 +1032,7 @@ "effectiveOperationsArray": "src/data/api-derivation.ts#effectiveOperationsArray (function)", "emptyGroupValueFor": "src/data/aggregation-policy.ts#emptyGroupValueFor (function)", "expandEmptyOperator": "src/data/filter-empty-operator.ts#expandEmptyOperator (function)", + "extensionArrangementKeys": "src/data/field-customization.ts#extensionArrangementKeys (function)", "externalBindingDatasourceRefusal": "src/data/external-binding-datasource.ts#externalBindingDatasourceRefusal (function)", "externalColumnMapTargets": "src/data/injected-system-column-provenance.ts#externalColumnMapTargets (function)", "fieldForm": "src/data/field.form.ts#fieldForm (const)", @@ -1149,6 +1159,7 @@ "readBooleanComparand": "src/data/filter-boolean-comparand-declared-type.ts#readBooleanComparand (function)", "readFieldGroupMembership": "src/data/field-group-layout.ts#readFieldGroupMembership (function)", "readNumericString": "src/data/filter-number-comparand-declared-type.ts#readNumericString (function)", + "readRelatedListsArrangement": "src/data/related-list-entry.ts#readRelatedListsArrangement (function)", "recordCurrencyDynamicRollupNotHomeError": "src/data/record-currency-path.ts#recordCurrencyDynamicRollupNotHomeError (function)", "recordCurrencyFollowedCodeError": "src/data/record-currency-path.ts#recordCurrencyFollowedCodeError (function)", "recordCurrencyRecordRollupError": "src/data/record-currency-path.ts#recordCurrencyRecordRollupError (function)", @@ -1169,7 +1180,9 @@ "refusedCredentialPathsOfSchema": "src/data/datasource-credential-redaction.ts#refusedCredentialPathsOfSchema (function)", "refusedInlineCredentialKey": "src/data/driver/common.zod.ts#refusedInlineCredentialKey (function)", "refusedPassthroughSecretPaths": "src/data/datasource-credential-redaction.ts#refusedPassthroughSecretPaths (function)", + "relatedListEntryHidden": "src/data/related-list-entry.ts#relatedListEntryHidden (function)", "relatedListEntryName": "src/data/related-list-entry.ts#relatedListEntryName (function)", + "relatedListNameCovers": "src/data/related-list-entry.ts#relatedListNameCovers (function)", "renderAutonumber": "src/data/autonumber-format.ts#renderAutonumber (function)", "resolveAutonumberFormat": "src/data/autonumber-format.ts#resolveAutonumberFormat (function)", "resolveBulkPerRowHookBudget": "src/data/bulk-write-hook-conformance.ts#resolveBulkPerRowHookBudget (function)", diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index d565e88684f..0b931c87222 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -127,6 +127,8 @@ "data/ObjectExtensionGroupPlacement", "data/ObjectExtensionListPlacement", "data/ObjectExtensionPlacement", + "data/ObjectExtensionRelatedListEntry", + "data/ObjectExtensionRelatedListEntryObject", "data/ObjectExternalBinding", "data/ObjectFieldGroup", "data/ObjectOwnershipEnum", diff --git a/packages/spec/src/data/field-customization.ts b/packages/spec/src/data/field-customization.ts index 8631828e76e..f3d73e0fbca 100644 --- a/packages/spec/src/data/field-customization.ts +++ b/packages/spec/src/data/field-customization.ts @@ -16,8 +16,17 @@ * 2. **A base field changes only within a display-property whitelist** (Q7). * {@link BASE_FIELD_DISPLAY_WHITELIST} is that whitelist: the closed constant * the write gate reads, never a judgement it makes. + * 3. **Only the paired `.custom` package arranges the whole record page** + * (maintainer, verbatim: 「软件包字段、子表自定义分三种,原始软件包,继承软件包和环境管理员覆盖, + * 继承软件包 我记得已经有一套标准,只能申明插入位置,原始软件包、环境管理员 应该可以申明完整的配置」). + * {@link CUSTOM_ARRANGEMENT_KEYS} are the two keys its object extension + * writes, in an object's own shape; any other package's extension places + * what it brings with `place`, and outside a `.custom` package is refused + * these keys at publish, at `os validate` and at the install door. The + * pair is the `.custom` package of the App the object belongs to; what + * another `.custom` package writes under these keys is not applied. * - * Constants and one pure predicate, imports nothing. The shape that carries a + * Constants and pure predicates, imports nothing. The shape that carries a * per-field patch is `ObjectExtensionSchema.fieldPatches` * (`data/object.zod.ts`), its keys derived from the whitelist below; the merge * that applies it is not declared in `packages/spec`. @@ -71,6 +80,22 @@ export function isExtensionFieldName(name: unknown): boolean { * enters by a recorded decision, because widening a published whitelist is * reversible and narrowing it is not. `field-customization.test.ts` checks that * every member exists on `FieldSchema` and that none is structural. + * + * `hidden` was measured against the test and stays OUT: it is not display-only. + * A hidden field is left out of the object's search companion column, so the + * stored `__search` value changes; a form's required verdict reads it + * (`required && hidden !== true`), so a validation verdict changes; and the + * default `search` and export columns drop it. The environment keeps a base + * field off the record page and the forms in its arrangement instead: the + * paired `.custom` extension's `fieldGroups` lists the field in a group whose + * `visibleWhen` is false ({@link CUSTOM_ARRANGEMENT_KEYS}). Two limits of + * that recipe, which the key's description states too: + * + * - it is presentation only, not access control: the field stays readable + * and writable through the API; + * - it is not for a `required` field that has no default: the create form + * no longer shows the field while the save still requires it, so the form + * cannot be submitted. */ export const BASE_FIELD_DISPLAY_WHITELIST = Object.freeze({ /** Keys of the base field itself. */ @@ -83,3 +108,33 @@ export const BASE_FIELD_DISPLAY_WHITELIST = Object.freeze({ export type BaseFieldDisplayProperty = (typeof BASE_FIELD_DISPLAY_WHITELIST.field)[number]; /** A key of one base field option the extension may patch. */ export type BaseFieldOptionDisplayProperty = (typeof BASE_FIELD_DISPLAY_WHITELIST.option)[number]; + +/** + * [ADR-0146 D10] The keys of an object extension only a base's paired + * `.custom` package writes: the whole field arrangement and the whole tab + * list of the extended object, each in the shape an object declares it in + * (`ObjectExtensionSchema.fieldGroups` / `.relatedLists`). Written, a key + * replaces what the owner declares and the other extensions' `place` entries + * add to, whole; not written, that arrangement stays. + * + * The ONE list: the registry fold that applies the keys, and the judge that + * refuses them outside `.custom` (publish, `os validate` / `os build`, the + * install door), read it through {@link extensionArrangementKeys}. + */ +export const CUSTOM_ARRANGEMENT_KEYS = Object.freeze(['fieldGroups', 'relatedLists'] as const); + +/** One of {@link CUSTOM_ARRANGEMENT_KEYS}. */ +export type CustomArrangementKey = (typeof CUSTOM_ARRANGEMENT_KEYS)[number]; + +/** + * [ADR-0146 D10] The {@link CUSTOM_ARRANGEMENT_KEYS} an object extension body + * writes, in the list's order. A key counts as written when the body carries + * any value under it (an empty array included: it declares an arrangement + * with nothing in it); `undefined` and `null` do not. Tolerant of an unparsed + * body, so every door and the fold share one reading. + */ +export function extensionArrangementKeys(extension: unknown): CustomArrangementKey[] { + if (typeof extension !== 'object' || extension === null || Array.isArray(extension)) return []; + const body = extension as Record; + return CUSTOM_ARRANGEMENT_KEYS.filter((key) => body[key] !== undefined && body[key] !== null); +} diff --git a/packages/spec/src/data/object-extension-arrangement.test.ts b/packages/spec/src/data/object-extension-arrangement.test.ts new file mode 100644 index 00000000000..81e50f4d484 --- /dev/null +++ b/packages/spec/src/data/object-extension-arrangement.test.ts @@ -0,0 +1,247 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] `ObjectExtensionSchema.fieldGroups` / `.relatedLists` — the + * whole arrangement the paired `.custom` package's extension writes for an + * installed object, in the shape an object declares it in. The shape is + * judged here; WHO wrote it is the server's (the package is not in the body). + * Every refusal row differs from its control by one key alone. + */ +import { describe, it, expect } from 'vitest'; +import { + ObjectExtensionRelatedListEntrySchema, + ObjectExtensionSchema, + ObjectSchema, + RelatedListEntrySchema, +} from './object.zod'; +import { BASE_FIELD_DISPLAY_WHITELIST, CUSTOM_ARRANGEMENT_KEYS, extensionArrangementKeys } from './field-customization'; +import { + RELATED_LISTS_ARRANGEMENT_DECORATION, + readRelatedListsArrangement, + relatedListEntryHidden, + relatedListNameCovers, +} from './related-list-entry'; +import { METADATA_READ_DECORATIONS } from '../kernel/metadata-read-decorations'; + +const extension = (extra: Record = {}) => ({ + extend: 'crm_lead', + fields: { region__c: { type: 'text', label: 'Region' } }, + ...extra, +}); + +const issues = (input: unknown) => { + const parsed = ObjectExtensionSchema.safeParse(input); + return parsed.success ? [] : parsed.error.issues.map((issue) => ({ path: issue.path.join('.'), message: issue.message })); +}; + +describe('the arrangement keys', () => { + it('are fieldGroups and relatedLists, frozen', () => { + expect([...CUSTOM_ARRANGEMENT_KEYS]).toEqual(['fieldGroups', 'relatedLists']); + expect(Object.isFrozen(CUSTOM_ARRANGEMENT_KEYS)).toBe(true); + }); + + it.each([ + [{ extend: 'a' }, []], + [{ extend: 'a', fieldGroups: [] }, ['fieldGroups']], + [{ extend: 'a', relatedLists: ['task'] }, ['relatedLists']], + [{ extend: 'a', relatedLists: [], fieldGroups: [{ key: 'b', label: 'B' }] }, ['fieldGroups', 'relatedLists']], + [{ extend: 'a', fieldGroups: undefined, relatedLists: null }, []], + [undefined, []], + [['fieldGroups'], []], + ])('extensionArrangementKeys(%j) → %j', (body, keys) => { + expect(extensionArrangementKeys(body)).toEqual(keys); + }); +}); + +describe('ObjectExtensionSchema.fieldGroups — an object\'s field groups, in the same shape', () => { + const groups = [ + { key: 'contact', label: 'Contact', fields: ['email', 'phone', 'region__c'] }, + { key: 'basic', label: 'Basics', collapse: 'collapsed', fields: ['name', 'company'] }, + { key: 'lines', label: 'Lines', relatedList: 'crm_lead_line' }, + ]; + + it('accepts groups listing base fields, the extension\'s own field and a body table (control)', () => { + const parsed = ObjectExtensionSchema.safeParse(extension({ fieldGroups: groups })); + expect(parsed.success).toBe(true); + expect(parsed.success && parsed.data.fieldGroups?.map((group) => group.key)).toEqual(['contact', 'basic', 'lines']); + }); + + it('accepts exactly what an object accepts: the same groups parse on ObjectSchema', () => { + const parsed = ObjectSchema.safeParse({ + name: 'crm_lead', + fields: { name: { type: 'text' }, company: { type: 'text' }, email: { type: 'text' }, phone: { type: 'text' }, region__c: { type: 'text' } }, + fieldGroups: groups, + }); + expect(parsed.success).toBe(true); + }); + + it('accepts an empty list: an arrangement with no group', () => { + expect(ObjectExtensionSchema.safeParse(extension({ fieldGroups: [] })).success).toBe(true); + }); + + it('a group whose `visibleWhen` is false parses: the written way to keep a base field off the page', () => { + const parsed = ObjectExtensionSchema.safeParse(extension({ + fieldGroups: [ + { key: 'basic', label: 'Basics', fields: ['name'] }, + { key: 'off_page', label: 'Not shown', fields: ['fax'], visibleWhen: 'false' }, + ], + })); + expect(parsed.success).toBe(true); + }); + + it.each([ + ['a repeated group key', [{ key: 'basic', label: 'A' }, { key: 'basic', label: 'B' }], 'fieldGroups'], + ['an unknown group key', [{ key: 'basic', label: 'A', hidden: true }], 'fieldGroups.0'], + ['a field two groups list', [{ key: 'a', label: 'A', fields: ['name'] }, { key: 'b', label: 'B', fields: ['name'] }], 'fieldGroups.1.fields.0'], + ['a name one list repeats', [{ key: 'a', label: 'A', fields: ['name', 'name'] }], 'fieldGroups.0.fields.1'], + ['`fields` on a group that places a body table', [{ key: 'a', label: 'A', relatedList: 'task', fields: ['name'] }], 'fieldGroups.0.fields'], + ])('refuses %s, at the entry', (_label, value, path) => { + expect(issues(extension({ fieldGroups: value })).map((issue) => issue.path)).toContain(path); + }); + + it('refuses a field of its own whose `group` names another declared group than the one listing it', () => { + const found = issues({ + extend: 'crm_lead', + fields: { region__c: { type: 'text', label: 'Region', group: 'basic' } }, + fieldGroups: [{ key: 'contact', label: 'Contact', fields: ['region__c'] }, { key: 'basic', label: 'Basics' }], + }); + expect(found.map((issue) => issue.path)).toEqual(expect.arrayContaining(['fieldGroups.0.fields.0', 'fields.region__c.group'])); + }); + + it('refuses a field of its own whose `group` names a group that places a body table', () => { + const found = issues({ + extend: 'crm_lead', + fields: { region__c: { type: 'text', label: 'Region', group: 'lines' } }, + fieldGroups: [{ key: 'lines', label: 'Lines', relatedList: 'crm_lead_line' }], + }); + expect(found.map((issue) => issue.path)).toContain('fields.region__c.group'); + }); +}); + +describe('ObjectExtensionSchema.relatedLists — an object\'s tab list, plus `hidden`', () => { + it('accepts bare names, the object form, a built-in tab and a hidden entry (control)', () => { + const parsed = ObjectExtensionSchema.safeParse(extension({ + relatedLists: [ + 'crm_opportunity', + { list: 'crm_contact', label: 'People', columns: ['name', 'email'] }, + 'sys_attachment', + { list: 'crm_task', hidden: true }, + { list: 'crm_event.related_to', hidden: false }, + ], + })); + expect(parsed.success).toBe(true); + }); + + it('accepts an empty list: every tab is unlisted, so every tab still shows', () => { + expect(ObjectExtensionSchema.safeParse(extension({ relatedLists: [] })).success).toBe(true); + }); + + it('`hidden` is accepted on the extension\'s entry and refused on an object\'s, by name', () => { + const entry = { list: 'crm_task', hidden: true }; + expect(ObjectExtensionRelatedListEntrySchema.safeParse(entry).success).toBe(true); + const onObject = RelatedListEntrySchema.safeParse(entry); + expect(onObject.success).toBe(false); + expect(JSON.stringify(onObject.success ? [] : onObject.error.issues)).toContain('.custom'); + }); + + it.each([ + ['a built-in tab in the object form', [{ list: 'sys_attachment', hidden: true }]], + ['a name that is no entry name', ['Task']], + ['an unknown entry key', [{ list: 'crm_task', visible: false }]], + ['a non-boolean `hidden`', [{ list: 'crm_task', hidden: 'yes' }]], + ])('refuses %s', (_label, value) => { + expect(ObjectExtensionSchema.safeParse(extension({ relatedLists: value })).success).toBe(false); + }); + + it.each([ + ['the same list shown and hidden', ['crm_task', { list: 'crm_task', hidden: true }], 'relatedLists.1.hidden'], + ['a list hidden, then shown', [{ list: 'crm_task', hidden: true }, 'crm_task'], 'relatedLists.1'], + ['one relationship shown of a child hidden whole', [{ list: 'crm_task', hidden: true }, { list: 'crm_task.lead', label: 'Tasks' }], 'relatedLists.1'], + ])('refuses %s, at the later entry', (_label, value, path) => { + const found = issues(extension({ relatedLists: value })); + expect(found).toHaveLength(1); + expect(found[0].path).toBe(path); + expect(found[0].message).toContain('hidden'); + }); + + it('a child shown with one of its relationships hidden is no contradiction', () => { + expect(ObjectExtensionSchema.safeParse(extension({ + relatedLists: ['crm_task', { list: 'crm_task.converted_lead', hidden: true }], + })).success).toBe(true); + }); +}); + +describe('ObjectExtensionSchema — `place` beside the arrangement that replaces it', () => { + const place = [ + { field: 'region__c', group: 'basic', after: 'company' }, + { group: { key: 'extra', label: 'Extra' }, after: 'basic' }, + { list: 'crm_visit', after: 'crm_task' }, + ]; + + it('control: the three placements parse with neither key written', () => { + expect(ObjectExtensionSchema.safeParse(extension({ place })).success).toBe(true); + }); + + it('`fieldGroups` written: the field and group placements are refused, the list placement stays', () => { + const found = issues(extension({ place, fieldGroups: [{ key: 'basic', label: 'Basics' }] })); + expect(found.map((issue) => issue.path)).toEqual(['place.0', 'place.1']); + expect(found[0].message).toContain('`fieldGroups`'); + }); + + it('`relatedLists` written: the list placement is refused, the field and group placements stay', () => { + const found = issues(extension({ place, relatedLists: ['crm_task'] })); + expect(found.map((issue) => issue.path)).toEqual(['place.2']); + expect(found[0].message).toContain('`relatedLists`'); + }); +}); + +describe('the display whitelist is not widened', () => { + it('`hidden` is not a patchable base-field property', () => { + expect([...BASE_FIELD_DISPLAY_WHITELIST.field]).not.toContain('hidden'); + const parsed = ObjectExtensionSchema.safeParse(extension({ fieldPatches: { fax: { hidden: true } } })); + expect(parsed.success).toBe(false); + }); +}); + +describe('the served decoration', () => { + it('is a read decoration, so every write strips it', () => { + expect(RELATED_LISTS_ARRANGEMENT_DECORATION).toBe('_relatedListsArrangement'); + expect(METADATA_READ_DECORATIONS).toContain(RELATED_LISTS_ARRANGEMENT_DECORATION); + }); + + it.each([ + [{ name: 'a' }, undefined], + [{ _relatedListsArrangement: null }, undefined], + [{ _relatedListsArrangement: { hidden: ['task'] } }, undefined], + [{ _relatedListsArrangement: { packageId: 'crm.custom' } }, { packageId: 'crm.custom', hidden: [], unlisted: 'hidden' }], + [ + { _relatedListsArrangement: { packageId: 'crm.custom', hidden: ['task', 7, ''], unlisted: 'shown' } }, + { packageId: 'crm.custom', hidden: ['task'], unlisted: 'shown' }, + ], + [undefined, undefined], + ])('readRelatedListsArrangement(%j) → %j', (object, arrangement) => { + expect(readRelatedListsArrangement(object)).toEqual(arrangement); + }); + + it.each([ + ['task', false], + [{ list: 'task' }, false], + [{ list: 'task', hidden: false }, false], + [{ list: 'task', hidden: true }, true], + [{ hidden: true }, false], + ])('relatedListEntryHidden(%j) → %s', (entry, verdict) => { + expect(relatedListEntryHidden(entry)).toBe(verdict); + }); + + it.each([ + ['task', 'task', true], + ['task', 'task.account', true], + ['task.account', 'task.account', true], + ['task.account', 'task', false], + ['task.account', 'task.owner', false], + ['task', 'task_note', false], + ['task', 'event.task', false], + ])('relatedListNameCovers(%j, %j) → %s', (entry, name, verdict) => { + expect(relatedListNameCovers(entry, name)).toBe(verdict); + }); +}); diff --git a/packages/spec/src/data/object-extension-place.test.ts b/packages/spec/src/data/object-extension-place.test.ts index b2804e9137e..e92a685952e 100644 --- a/packages/spec/src/data/object-extension-place.test.ts +++ b/packages/spec/src/data/object-extension-place.test.ts @@ -130,12 +130,16 @@ describe('ObjectExtensionSchema.place — the guide\'s example', () => { }); }); -describe('ObjectExtensionSchema — the owner\'s arrangement keys point to place', () => { +describe('ObjectExtensionSchema — the arrangement keys are the paired `.custom` package\'s', () => { + // [ADR-0146 D10] `fieldGroups` and `relatedLists` are keys of the shape, written by the + // paired `.custom` package's extension (`object-extension-arrangement.test.ts`). Which + // package an extension belongs to is not in its body, so this parse cannot refuse another + // writer: the server does, prescribing `place` (`judgeExtensionArrangement`, + // `@objectstack/metadata-protocol`), at publish, `os validate` / `os build` and install. it.each([ ['fieldGroups', [{ key: 'tax', label: 'Tax' }]], ['relatedLists', ['contract']], - ])('refuses `%s` with a prescription naming `place`', (key, value) => { - const messages = issuesAt(extension({ [key]: value }), ''); - expect(messages.join('\n')).toContain('`place`'); + ])('`%s` parses: the shape carries it, the server judges who wrote it', (key, value) => { + expect(ObjectExtensionSchema.safeParse(extension({ [key]: value })).success).toBe(true); }); }); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index fa0baf5ecbd..7639786fa97 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -27,7 +27,7 @@ import { suggestRename } from '../shared/rename-guess'; import { refuseRecordProtoKey } from '../shared/record-proto-key-guard'; import { bannedKeys } from '../shared/refinement-projection'; import { FIELD_GROUP_KEY_PATTERN } from './field-group-layout'; -import { RECORD_PAGE_BUILTIN_TABS } from './related-list-entry'; +import { RECORD_PAGE_BUILTIN_TABS, relatedListEntryHidden, relatedListEntryName, relatedListNameCovers } from './related-list-entry'; // [#23809] The stage-field option-kind rule, in its own module so the AI // blueprint object (`ai/solution-blueprint.zod.ts`) runs this same refinement. import { refuseStageFieldWithoutKinds } from './stage-field-kinds'; @@ -1342,6 +1342,12 @@ export const RelatedListEntryObjectSchema = lazySchema(() => strictObject({ '`filter` is not a relatedLists entry key: a related list\'s scope is the child FK\'s `relatedListFilter`.', sort: '`sort` is not a relatedLists entry key: a related list orders its rows the way the child object\'s default list view sorts.', + // [ADR-0146 D10] Hiding by name is the environment's word, written in the + // paired `.custom` package's arrangement; an object hides by leaving out. + hidden: + '`hidden` is not a relatedLists entry key on an object: an object hides a tab by leaving its list out of ' + + '`relatedLists`. Only the object extension of a base\'s paired `.custom` package writes ' + + '`{ list, hidden: true }`, in its own `relatedLists` (ADR-0146 D10).', }, }, { list: z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: RELATED_LIST_ENTRY_NAME_MESSAGE }) @@ -6657,6 +6663,228 @@ function refuseForeignPlacements(fields: unknown, place: unknown, ctx: z.Refinem }); } +// ================================================================= +// The paired `.custom` package's arrangement (ADR-0146 D10) +// ================================================================= + +/** + * [ADR-0146 D10] The OBJECT form of one entry of the paired `.custom` + * package's `ObjectExtensionSchema.relatedLists`: an object's own entry + * ({@link RelatedListEntryObjectSchema}: `list`, `label`, `columns`) plus + * `hidden`. The environment's tab list shows a tab it does not name (after + * the listed ones), so hiding one is written: `{ list: 'task', hidden: true }`. + * `hidden` is accepted here and nowhere else: an object's own `relatedLists` + * refuses it by name. + */ +export const ObjectExtensionRelatedListEntryObjectSchema = lazySchema(() => strictObject({ + surface: 'this relatedLists entry of an object extension', + history: + 'An unknown key here would be dropped silently: the tab would still draw, as the arrangement before this ' + + 'one had it, so the author would believe the setting they wrote had been applied.', + aliases: { + name: 'list', + object: 'list', + objectName: 'list', + relationship: 'list', + title: 'label', + fields: 'columns', + hide: 'hidden', + }, + guidance: { + filter: + '`filter` is not a relatedLists entry key: a related list\'s scope is the child FK\'s `relatedListFilter`.', + sort: + '`sort` is not a relatedLists entry key: a related list orders its rows the way the child object\'s default list view sorts.', + visible: + '`visible` is not a relatedLists entry key: a listed tab is shown. Write `hidden: true` to hide it.', + }, +}, { + ...RelatedListEntryObjectSchema.shape, + hidden: z.boolean().optional() + .describe("true = this list's tab is not shown on the record page (and a reader's own arrangement cannot bring it back); absent or false = shown at this entry's position. The one way the paired `.custom` arrangement hides a tab: a tab it does not name still shows, after the listed ones. A built-in tab is written only as its bare name and is not hidden here."), +})); + +/** + * [ADR-0146 D10] One entry of the paired `.custom` package's + * `ObjectExtensionSchema.relatedLists`: the bare name (a child object, + * `object.field`, or a built-in tab), or + * {@link ObjectExtensionRelatedListEntryObjectSchema}'s object form. + */ +export const ObjectExtensionRelatedListEntrySchema = lazySchema(() => z.union([ + z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: RELATED_LIST_ENTRY_NAME_MESSAGE }), + ObjectExtensionRelatedListEntryObjectSchema, +])); +/** One entry of the paired `.custom` package's `relatedLists`, as an author writes it. */ +export type ObjectExtensionRelatedListEntry = z.input; +/** One entry of the paired `.custom` package's `relatedLists`, after parse. */ +export type ObjectExtensionRelatedListEntryParsed = z.infer; + +/** + * [ADR-0146 D10] A `.custom` arrangement's group keys are unique, as an + * object's are. Judged here, in the extension's own refinement, and not as a + * `.refine()` on the `fieldGroups` array: that would be a new position at + * which a rule reaches the runtime and not the published JSON Schema + * (`dropped-refinements.baseline.json`), where this refinement is already + * one recorded position for the whole extension. + */ +function refuseDuplicateExtensionFieldGroupKeys(fieldGroups: unknown, ctx: z.RefinementCtx): void { + if (!Array.isArray(fieldGroups)) return; + const keys = fieldGroups.map((group) => (group as { key?: unknown } | null | undefined)?.key); + if (new Set(keys).size === keys.length) return; + ctx.addIssue({ + code: 'custom', + path: ['fieldGroups'], + message: 'fieldGroups[].key must be unique within an object extension', + }); +} + +/** + * [ADR-0146 D10] Refuse a `.custom` tab list that says two things about one + * list: an entry that shows a list another entry hides. The hiding entry + * hides every list it names (a bare child name, all of that child's lists), + * so a shown entry naming the same list, or one relationship of a child the + * list hides whole, would draw nothing. Located at the later of the two. + * `'task'` shown beside `{ list: 'task.account', hidden: true }` is not a + * contradiction: every list of the child shows but the one hidden. + * + * Judged on the extension's root refinement, where `ObjectExtensionSchema` + * already carries one, so the published JSON Schema gains no + * dropped-refinement site. + */ +function refuseContradictoryRelatedListEntries(relatedLists: unknown, ctx: z.RefinementCtx): void { + if (!Array.isArray(relatedLists)) return; + const entries = relatedLists.map((entry: unknown, index: number) => ({ + index, + name: relatedListEntryName(entry), + hidden: relatedListEntryHidden(entry), + })).filter((entry): entry is { index: number; name: string; hidden: boolean } => entry.name !== undefined); + for (const shown of entries) { + if (shown.hidden) continue; + const hiding = entries.find((entry) => entry.hidden && relatedListNameCovers(entry.name, shown.name)); + if (hiding === undefined) continue; + const at = Math.max(shown.index, hiding.index); + ctx.addIssue({ + code: 'custom', + path: at === shown.index ? ['relatedLists', at] : ['relatedLists', at, 'hidden'], + message: + `List '${shown.name}' is listed (relatedLists[${shown.index}]) and hidden ` + + `(relatedLists[${hiding.index}]${hiding.name === shown.name ? '' : `, which hides every list of '${hiding.name}'`}): ` + + 'a hidden list is not shown wherever it is listed. Keep one of the two entries.', + }); + } +} + +/** + * [ADR-0146 D10] Refuse a `place` entry beside the arrangement key that + * replaces it, in one extension: `fieldGroups` is the whole field + * arrangement, so a `{ field }` or `{ group }` placement written beside it + * would be applied and then replaced; `relatedLists` is the whole tab list, + * so a `{ list }` placement beside it would be. Located at the entry, naming + * where the item is written instead. An extension that writes only one of + * the two keys keeps the placements of the other kind. + */ +function refusePlacementsTheArrangementReplaces( + extension: { place?: unknown; fieldGroups?: unknown; relatedLists?: unknown }, + ctx: z.RefinementCtx, +): void { + if (!Array.isArray(extension.place)) return; + const groupsWritten = Array.isArray(extension.fieldGroups); + const tabsWritten = Array.isArray(extension.relatedLists); + if (!groupsWritten && !tabsWritten) return; + extension.place.forEach((entry: unknown, index: number) => { + if (entry === null || typeof entry !== 'object') return; + const { field, group, list } = entry as { field?: unknown; group?: unknown; list?: unknown }; + if (groupsWritten && typeof field === 'string') { + ctx.addIssue({ + code: 'custom', + path: ['place', index], + message: + `This extension writes \`fieldGroups\`, the whole field arrangement, so the placement of the field ` + + `'${field}' would be replaced by it. List '${field}' in a group's \`fields\` there and remove this entry.`, + }); + } else if (groupsWritten && group !== null && typeof group === 'object') { + const key = (group as { key?: unknown }).key; + ctx.addIssue({ + code: 'custom', + path: ['place', index], + message: + `This extension writes \`fieldGroups\`, the whole field arrangement, so the placement of the group ` + + `${typeof key === 'string' ? `'${key}' ` : ''}would be replaced by it. Declare the group in \`fieldGroups\`, ` + + 'at its position, and remove this entry.', + }); + } else if (tabsWritten && typeof list === 'string') { + ctx.addIssue({ + code: 'custom', + path: ['place', index], + message: + `This extension writes \`relatedLists\`, the whole tab list, so the placement of the list '${list}' ` + + `would be replaced by it. Name '${list}' in \`relatedLists\`, at its position, and remove this entry.`, + }); + } + }); +} + +/** [ADR-0146 D10] The words every key of the paired `.custom` arrangement shares: who may write it, and what refuses anyone else. */ +const CUSTOM_ARRANGEMENT_WRITER = + 'Written only by the object extension of the paired `.custom` package of the App the object belongs to ' + + '(ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by ' + + '`os validate` / `os build` and at install, with the prescription to place what it brings with `place`, and ' + + 'the registry merge skips it with a warning. A `.custom` package that is not this object\'s pair is not ' + + 'refused at those doors: the registry merge does not apply what it writes here, alone or beside the pair, ' + + 'and the boot log names it.'; + +/** [ADR-0146 D10] The extension's `fieldGroups` description. */ +function objectExtensionFieldGroupsDescription(): string { + return ( + 'The whole field arrangement of the extended object on the record page, the forms and the preview: an ' + + 'object\'s `fieldGroups`, in the same shape. ' + CUSTOM_ARRANGEMENT_WRITER + ' A group may list any field the ' + + 'object has, whoever declares it (its owner, another package\'s extension, or this extension\'s own `__c` ' + + 'fields), and a group\'s `relatedList` may place any body table. Written, it replaces the groups the owner ' + + 'declares and the other extensions\' `place` entries add, whole: no group, member or order of that ' + + 'arrangement is kept unless written here, and nothing is merged entry by entry. A group that lists `fields` ' + + 'shows exactly its list. A field no group here lists is never dropped: it shows after the last group, ' + + 'whatever group its owner or another extension had put it in. That covers a field a later version of the ' + + 'base adds and a field another package\'s extension brings. A group that lists no `fields` keeps the ' + + 'object\'s older rule (the fields whose `group` names it), and a field this extension adds keeps the ' + + '`group` it declares. Not written, the arrangement stays as ' + + 'the owner and the `place` entries give it, and removing this key, or uninstalling or disabling the package, ' + + 'restores that. To keep a field off the record page and the forms, list it in a group whose `visibleWhen` ' + + 'is false: `hidden` is not a display property a `fieldPatches` entry may set, because it also changes what ' + + 'search indexes and what a form requires. Such a group is presentation only, not access control: the field ' + + 'stays readable and writable through the API. Do not use it for a `required` field that has no default: ' + + 'the create form no longer shows the field while the save still requires it, so the form cannot be ' + + 'submitted. Example: `fieldGroups: [{ key: \'contact\', label: \'Contact\', ' + + 'fields: [\'email\', \'phone\', \'region__c\'] }, { key: \'basic\', label: \'Basics\', fields: [\'name\', ' + + '\'company\'] }]`.' + ); +} + +/** [ADR-0146 D10] The extension's `relatedLists` description. */ +function objectExtensionRelatedListsDescription(): string { + return ( + 'The whole tab list of the extended object\'s record page, in order: an object\'s `relatedLists`, in the same ' + + 'shape, whose object form also takes `hidden`. ' + CUSTOM_ARRANGEMENT_WRITER + ' An entry may name any list ' + + 'the object has, whoever brings it (a child object, object.field, or a built-in tab; `{ list, label?, ' + + 'columns?, hidden? }` gives the list its own title and columns, or hides it). Written, it replaces the tab ' + + 'list the owner declares and the other extensions\' `place` entries add to, whole, and nothing is merged ' + + 'entry by entry. A tab this list does not name is not hidden, the reverse of an object\'s own `relatedLists`: ' + + 'where the object had a declared tab list, each of its tabs not named here follows the listed ones (before ' + + 'a trailing approvals / activity-stream run), with the title and columns it had; where the object declared ' + + 'none (every list shows), every list not named here follows the listed ones, and so does the attachments ' + + 'tab. That covers a tab a later version of the base adds and a child list a package installed later brings. ' + + 'Hiding is written: `{ list: \'task\', hidden: true }` hides that list\'s tab, whoever brings the list, and ' + + 'a bare child name hides every list of that child. A list the object\'s own `relatedLists` hides by leaving ' + + 'it out stays hidden until this list names it. A built-in tab is written only as its bare name, keeps its ' + + 'own rule (approvals and the activity stream follow the listed tabs when unlisted) and cannot be hidden ' + + 'here. `relatedList: false` on the child\'s field still hides a list whatever this says, and body tables a ' + + 'field group places are the groups\' to place. A reader\'s own tab order and hidden tabs (kept per user) ' + + 'are laid over this list, as over an object\'s. Not written, the tabs stay as the owner and the `place` ' + + 'entries give them, and removing this key, or uninstalling or disabling the package, restores that. ' + + 'Example: `relatedLists: [\'opportunity\', { list: \'contact\', label: \'People\' }, { list: \'task\', ' + + 'hidden: true }]`.' + ); +} + /** * Object Extension Entry — used in `objectExtensions` array. * Declares fields/config to merge into an existing object owned by another package. @@ -6719,17 +6947,11 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ 'carry them. Declare the views as a top-level `view` in the stack that defines the ' + 'target object. `defineStack()` refuses a top-level `view` whose `list` or `form` data ' + 'source is an object the stack does not define, an extended one included.', - // [#35901] An extension's groups, and where its fields and child lists go, - // are its `place` entries; the owner's own arrangement is the owner's. - fieldGroups: - '`fieldGroups` is not an object extension key: an extension adds a group of its own with a ' + - '`place` entry — `place: [{ group: { key: \'tax\', label: \'Tax\' }, after: \'basic\' }]` — and puts a field ' + - 'it adds into a group with `{ field: \'tax_id\', group: \'basic\', after: \'industry\' }`. The extended ' + - 'object\'s own groups stay its owner\'s.', - relatedLists: - '`relatedLists` is not an object extension key: an extension places a child list its package brings ' + - 'with a `place` entry — `place: [{ list: \'contract\', after: \'opportunity\' }]`. The extended object\'s ' + - 'own tab list stays its owner\'s.', + // [#35901, ADR-0146 D10] `fieldGroups` and `relatedLists` are KEYS of this + // schema, not guidance: the paired `.custom` package's extension writes + // them, and which package an extension belongs to is not in its body, so + // the refusal of any other writer is the server's (`CUSTOM_ARRANGEMENT_KEYS` + // and its judge, at publish, `os validate` / `os build` and install). // A membership key belongs to the package that owns the roster object, so a // key cannot reach into another package's object (the ruled refusal 10). membershipKeys: @@ -6833,6 +7055,32 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ */ place: z.array(ObjectExtensionPlacementSchema).optional().describe(objectExtensionPlaceDescription()), + /** + * [ADR-0146 D10] The whole field arrangement of the extended object, written + * by the object extension of the base's paired `.custom` package and by no + * other: an object's `fieldGroups` ({@link ObjectFieldGroupSchema}), in the + * same shape. Written, it replaces the arrangement the owner declares and + * the other extensions' `place` entries add to, whole; the registry fold + * applies it last (`applyCustomArrangement` in `@objectstack/objectql`). + * Pure shape: which package the extension belongs to is not in its body, so + * any other writer is refused by the server (`judgeExtensionArrangement` in + * `@objectstack/metadata-protocol`, at publish, `os validate` / `os build` + * and install). See {@link objectExtensionFieldGroupsDescription}. + */ + fieldGroups: z.array(ObjectFieldGroupSchema).optional().describe(objectExtensionFieldGroupsDescription()), + + /** + * [ADR-0146 D10] The whole tab list of the extended object's record page, + * written by the object extension of the base's paired `.custom` package + * and by no other: an object's `relatedLists`, whose object form also takes + * `hidden` ({@link ObjectExtensionRelatedListEntrySchema}). Written, it + * replaces the tab list the owner declares and the other extensions' + * `place` entries add to, whole; a tab it does not name still shows, after + * the listed ones. Applied and refused where `fieldGroups` is. See + * {@link objectExtensionRelatedListsDescription}. + */ + relatedLists: z.array(ObjectExtensionRelatedListEntrySchema).optional().describe(objectExtensionRelatedListsDescription()), + /** Merge priority. Higher number applied later (wins on conflict). Default: 200 */ priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'), }).superRefine((extension, ctx) => { @@ -6845,6 +7093,16 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ refuseFieldPatchOfReplacedField(extension.fields, extension.fieldPatches, ctx); // [#35901] An extension places only what it brings, each item once, with one anchor. refuseForeignPlacements(extension.fields, extension.place, ctx); + // [ADR-0146 D10] The `.custom` arrangement: the object's own two membership + // rules, over the fields this extension adds (a base field's `group` is + // not in this body; the registry fold lets the list win over it)… + refuseDuplicateExtensionFieldGroupKeys(extension.fieldGroups, ctx); + refuseFieldsInRelatedListGroups(extension.fieldGroups, extension.fields, ctx); + refuseFieldGroupMembershipConflicts(extension.fieldGroups, extension.fields, ctx); + // …one statement per list… + refuseContradictoryRelatedListEntries(extension.relatedLists, ctx); + // …and no `place` entry the extension's own arrangement replaces. + refusePlacementsTheArrangementReplaces(extension, ctx); }).overwrite((extension) => { // [#23065] …and the object a referenceless `tree` field references. See // {@link materializeTreeSelfReferences}. diff --git a/packages/spec/src/data/related-list-entry.ts b/packages/spec/src/data/related-list-entry.ts index c159d59ca82..1cbba3eccad 100644 --- a/packages/spec/src/data/related-list-entry.ts +++ b/packages/spec/src/data/related-list-entry.ts @@ -30,6 +30,8 @@ * and the lint rule, each through these exports, so no second list exists. */ +import type { MetadataReadDecoration } from '../kernel/metadata-read-decorations'; + /** The record page's three built-in tabs, by the platform object each draws, in their default order. */ export const RECORD_PAGE_BUILTIN_TABS = ['sys_attachment', 'sys_approval_request', 'sys_activity'] as const; @@ -62,6 +64,16 @@ export interface RelatedListEntryObject { /** One `relatedLists` entry: the bare name, or the object form. */ export type RelatedListEntryInput = string | RelatedListEntryObject; +/** + * [ADR-0146 D10] One entry of the paired `.custom` package's + * `ObjectExtensionSchema.relatedLists`, in its object form: the object's entry + * plus `hidden`. Only that arrangement writes `hidden`; an object's own + * `relatedLists` hides a tab by leaving it out. + */ +export interface ObjectExtensionRelatedListEntryObject extends RelatedListEntryObject { + readonly hidden?: boolean; +} + /** * The name one `relatedLists` entry gives: the bare string itself, or the * object form's `list`. `undefined` for anything else (a value the parse @@ -75,3 +87,94 @@ export function relatedListEntryName(entry: unknown): string | undefined { } return undefined; } + +/** + * [ADR-0146 D10] Does one entry of the paired `.custom` package's + * `relatedLists` hide its list (`{ list, hidden: true }`)? `false` for the + * bare name and for every other value. + */ +export function relatedListEntryHidden(entry: unknown): boolean { + return typeof entry === 'object' && entry !== null && !Array.isArray(entry) + && typeof (entry as { list?: unknown }).list === 'string' + && (entry as { hidden?: unknown }).hidden === true; +} + +/** + * [ADR-0146 D10] Does the entry name `entry` cover the list `name` whole? + * The same name, or a bare child, which names every list of that child + * (`task` covers `task` and `task.account`). One relationship does not cover + * its child (`task.account` covers neither `task` nor `task.owner`). + * + * The ONE reading of "this entry speaks for that list", for the paired + * `.custom` arrangement: a hidden entry hides the lists it covers, and an + * entry of the arrangement it replaces is carried over unless an entry + * covers it. + */ +export function relatedListNameCovers(entry: string, name: string): boolean { + return entry === name || (!entry.includes('.') && name.startsWith(`${entry}.`)); +} + +/** + * [ADR-0146 D10] The key of the read decoration a served `object` carries when + * the paired `.custom` package arranges its record-page tabs (a member of + * `METADATA_READ_DECORATIONS`, `@objectstack/spec/kernel`): derived on every + * read, stripped on every write, never authorable. + */ +export const RELATED_LISTS_ARRANGEMENT_DECORATION = '_relatedListsArrangement' as const satisfies MetadataReadDecoration; + +/** + * [ADR-0146 D10] What the served `relatedLists` cannot say about a tab list + * the paired `.custom` package declares. + * + * The served `relatedLists` keeps the meaning it has on every object: the + * lists it names are the tabs, in its order. The registry fold writes the + * `.custom` arrangement into it (the entries it shows, then the entries of + * the arrangement it replaces that it does not name). Two things are left for + * the reader, because only the reader knows which lists exist for the user: + * + * - `hidden` — the lists the arrangement hides, as entry names (`task`, or + * `task.account`). A list one of them names is not drawn, also a list + * another package brings, which a served `relatedLists` never hides by + * leaving it out; + * - `unlisted` — what happens to a related list no served entry names. + * `'shown'`: it follows the listed tabs, and so does the attachments tab + * (where the object enables files); set where the arrangement replaced the + * AUTOMATIC tab list, in which every list shows. `'hidden'`: the served + * list's own rule (a list of the object's own package shows only when + * named, another package's shows at the end); set where the arrangement + * replaced a DECLARED tab list, whose unnamed entries the fold already + * appended. The rule holds for an EMPTY served list too: where the + * arrangement hides every tab of a declared list, nothing is left to + * serve, and an empty `relatedLists` on its own reads as "none declared, + * every list shows". Beside `'hidden'` it is a declared list that names + * nothing, so a list the owner hid by leaving it out stays hidden. + */ +export interface RelatedListsArrangement { + /** The `.custom` package whose object extension declares the tab list. */ + readonly packageId: string; + /** The lists the arrangement hides, as entry names (a child object, or object.field). */ + readonly hidden: readonly string[]; + /** Whether a related list no served entry names is shown after the listed tabs, or follows the served list's own rule (also where that list is empty). */ + readonly unlisted: 'shown' | 'hidden'; +} + +/** + * [ADR-0146 D10] The {@link RelatedListsArrangement} a served object carries, + * or `undefined` when no `.custom` package arranges its tabs (or the value is + * not the decoration's shape). The ONE reading of the decoration, for the + * record page (objectui `deriveRelatedLists` and the synthesized page's tab + * list): with `undefined`, a reader behaves exactly as it did before the + * decoration existed. + */ +export function readRelatedListsArrangement(object: unknown): RelatedListsArrangement | undefined { + if (typeof object !== 'object' || object === null || Array.isArray(object)) return undefined; + const value = (object as Record)[RELATED_LISTS_ARRANGEMENT_DECORATION]; + if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined; + const { packageId, hidden, unlisted } = value as { packageId?: unknown; hidden?: unknown; unlisted?: unknown }; + if (typeof packageId !== 'string' || packageId === '') return undefined; + return { + packageId, + hidden: Array.isArray(hidden) ? hidden.filter((name): name is string => typeof name === 'string' && name !== '') : [], + unlisted: unlisted === 'shown' ? 'shown' : 'hidden', + }; +} diff --git a/packages/spec/src/integration/connector-credential-redaction.test.ts b/packages/spec/src/integration/connector-credential-redaction.test.ts index 6cefef9df26..658ac01d5e5 100644 --- a/packages/spec/src/integration/connector-credential-redaction.test.ts +++ b/packages/spec/src/integration/connector-credential-redaction.test.ts @@ -338,7 +338,12 @@ describe('the connector redactor — top-level keys the entry does not declare', }); it('the read decorations are the response\'s and are left alone', () => { - const item = { ...base, _draft: true, _withheldFields: { crm_project: { packageId: 'com.vendor.projects' } } }; + const item = { + ...base, + _draft: true, + _withheldFields: { crm_project: { packageId: 'com.vendor.projects' } }, + _relatedListsArrangement: { packageId: 'com.vendor.custom', hidden: [], unlisted: 'hidden' }, + }; for (const key of METADATA_READ_DECORATIONS) expect(item).toHaveProperty(key); expect(redactConnectorItem(item)).toEqual({ item, redactedKeys: [] }); }); diff --git a/packages/spec/src/kernel/metadata-read-decorations.ts b/packages/spec/src/kernel/metadata-read-decorations.ts index 2f0a0d25163..c3515f045cb 100644 --- a/packages/spec/src/kernel/metadata-read-decorations.ts +++ b/packages/spec/src/kernel/metadata-read-decorations.ts @@ -42,6 +42,13 @@ * package (`{ FIELD: { packageId } }`). Derived from which packages are * disabled at read time, so a copy saved into a body would be a stale * verdict the next enable or disable contradicts. + * - `_relatedListsArrangement` — on a served `object` read, what the paired + * `.custom` package's tab list says that the served `relatedLists` cannot: + * the lists it hides, and whether a list no entry names is shown after the + * listed tabs (`{ packageId, hidden, unlisted }`, ADR-0146 D10; + * `RelatedListsArrangement` in `@objectstack/spec/data`). Derived from the + * packages that extend the object at read time, so a copy saved into a + * body would outlive the `.custom` arrangement it describes. * * Deliberately NOT members, though they share the underscore spelling: the * ADR-0010 protection envelope (`_lock`, `_lockReason`, `_lockSource`, @@ -50,7 +57,7 @@ * legitimately carries and merges, and the closed metadata schemas allowlist * them precisely so a served document keeps its provenance on re-parse. */ -export const METADATA_READ_DECORATIONS = ['_diagnostics', '_draft', '_withheldFields'] as const; +export const METADATA_READ_DECORATIONS = ['_diagnostics', '_draft', '_withheldFields', '_relatedListsArrangement'] as const; /** Union of the keys in {@link METADATA_READ_DECORATIONS}. */ export type MetadataReadDecoration = (typeof METADATA_READ_DECORATIONS)[number]; diff --git a/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.customArrangement-36498.test.ts b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.customArrangement-36498.test.ts new file mode 100644 index 00000000000..5b504b58e7f --- /dev/null +++ b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.customArrangement-36498.test.ts @@ -0,0 +1,180 @@ +/** + * objectstack#36498 (ADR-0146 D10) — the tab list the base's paired `.custom` + * package declares for an installed object. The server writes it into the + * served `relatedLists` and says two more things beside it, in the served + * read's `_relatedListsArrangement` decoration, because only this derivation + * knows which lists exist for the reader: + * + * - `hidden`: the lists the arrangement hides (`{ list, hidden: true }`), a + * list another package brings included, which a served `relatedLists` + * never hides by leaving it out; + * - `unlisted: 'shown'`: the arrangement replaced the AUTOMATIC tab list, so + * a list no entry names still shows, after the listed ones; + * - `unlisted: 'hidden'`: it replaced a DECLARED one, and the served list is + * still a declared one when it is empty (every tab of it hidden). + * + * With no decoration this derivation answers exactly what it answered before + * the decoration existed (the last block pins that against literal values). + * Each row's control differs from it by the decoration alone. + */ +import { describe, it, expect } from 'vitest'; +import { deriveRelatedLists } from '../deriveRelatedLists'; + +const BASE = 'com.vendor.crm'; +const PAIR = 'com.vendor.crm.custom'; + +const lead = { name: 'lead', label: 'Lead', _packageId: BASE, fields: { name: { type: 'text' } } }; +const childOf = (name: string, packageId: string, fields?: Record) => ({ + name, + label: name, + _packageId: packageId, + fields: fields ?? { lead_id: { type: 'lookup', reference: 'lead' } }, +}); +const task = childOf('task', BASE); +const note = childOf('note', BASE); +const event = childOf('event', BASE, { + who_id: { type: 'lookup', reference: 'lead', label: 'Who' }, + related_to: { type: 'lookup', reference: 'lead', label: 'Related To' }, +}); +const audit = childOf('audit', 'com.acme.audit'); +const registry = [lead, task, note, event, audit]; + +const arranged = (hidden: string[], unlisted: 'shown' | 'hidden') => ({ + _relatedListsArrangement: { packageId: PAIR, hidden, unlisted }, +}); +const ids = (parent: Record, objects: unknown[] = registry, includeHidden = false) => + deriveRelatedLists(parent, objects as never, { includeHidden }).map((r) => `${r.childObject}.${r.referenceField}`); + +describe('the environment hides a tab (`hidden`)', () => { + const declared = { ...lead, relatedLists: ['note', 'task', 'event'] }; + + it('a list the arrangement hides is not derived; the others keep their order', () => { + expect(ids({ ...declared, relatedLists: ['note', 'event'], ...arranged(['task'], 'hidden') })).toEqual([ + 'note.lead_id', 'event.who_id', 'event.related_to', 'audit.lead_id', + ]); + }); + + it('control: without the decoration nothing is hidden by name', () => { + expect(ids(declared)).toEqual(['note.lead_id', 'task.lead_id', 'event.who_id', 'event.related_to', 'audit.lead_id']); + }); + + it('a list ANOTHER package brings is hidden too, which leaving it out of `relatedLists` never does', () => { + expect(ids({ ...declared, ...arranged(['audit'], 'hidden') })).toEqual([ + 'note.lead_id', 'task.lead_id', 'event.who_id', 'event.related_to', + ]); + }); + + it('a bare child name hides every list of that child; `object.field` hides the one relationship', () => { + expect(ids({ ...declared, ...arranged(['event'], 'hidden') })).toEqual(['note.lead_id', 'task.lead_id', 'audit.lead_id']); + expect(ids({ ...declared, ...arranged(['event.who_id'], 'hidden') })).toEqual([ + 'note.lead_id', 'task.lead_id', 'event.related_to', 'audit.lead_id', + ]); + }); + + it('it hides on an object that declares no `relatedLists` as well (the arrangement only hides)', () => { + expect(ids({ ...lead, ...arranged(['task'], 'shown') })).toEqual([ + 'note.lead_id', 'event.who_id', 'event.related_to', 'audit.lead_id', + ]); + }); + + it('the authoring surface keeps the hidden list, flagged `isUnlisted`', () => { + const lists = deriveRelatedLists({ ...declared, ...arranged(['audit', 'task'], 'hidden') }, registry as never, { includeHidden: true }); + expect(lists.filter((r) => r.isUnlisted).map((r) => r.childObject)).toEqual(['task', 'audit']); + }); + + it('a body table stays at its group and loses the tab it keeps: the arrangement hides tabs, groups place tables', () => { + const line = childOf('line', BASE, { lead_id: { type: 'master_detail', reference: 'lead' } }); + const parent = { ...lead, fieldGroups: [{ key: 'lines', label: 'Lines', relatedList: 'line' }] }; + const shown = deriveRelatedLists(parent, [lead, line] as never)[0]; + expect([shown.isPrimary, shown.keepsTab]).toEqual([true, true]); + const hidden = deriveRelatedLists({ ...parent, ...arranged(['line'], 'shown') }, [lead, line] as never)[0]; + expect([hidden.isPrimary, hidden.keepsTab]).toEqual([true, undefined]); + }); +}); + +describe('a tab the environment\'s list does not name still shows (`unlisted`)', () => { + it('`shown`: an unnamed list of the object\'s own package is kept after the listed ones', () => { + expect(ids({ ...lead, relatedLists: ['event'], ...arranged([], 'shown') })).toEqual([ + 'event.who_id', 'event.related_to', 'task.lead_id', 'note.lead_id', 'audit.lead_id', + ]); + }); + + it('control — `hidden`: the served list\'s own rule (an own-package list shows only when named)', () => { + expect(ids({ ...lead, relatedLists: ['event'], ...arranged([], 'hidden') })).toEqual([ + 'event.who_id', 'event.related_to', 'audit.lead_id', + ]); + }); + + it('`shown` with a hidden name: every unnamed list but the hidden one', () => { + expect(ids({ ...lead, relatedLists: ['event'], ...arranged(['note'], 'shown') })).toEqual([ + 'event.who_id', 'event.related_to', 'task.lead_id', 'audit.lead_id', + ]); + }); + + it('`shown`: an unnamed group-made body table keeps the tab it had on the automatic page', () => { + const line = childOf('line', BASE, { lead_id: { type: 'master_detail', reference: 'lead' } }); + const parent = { ...lead, fieldGroups: [{ key: 'lines', label: 'Lines', relatedList: 'line' }], relatedLists: ['task'] }; + const kept = deriveRelatedLists({ ...parent, ...arranged([], 'shown') }, [lead, task, line] as never).find((r) => r.childObject === 'line')!; + expect(kept.keepsTab).toBe(true); + const control = deriveRelatedLists(parent, [lead, task, line] as never).find((r) => r.childObject === 'line')!; + expect(control.keepsTab).toBeUndefined(); + }); +}); + +describe('every tab of a declared list hidden: the served list is empty, and still a declared one', () => { + // The owner listed `task` and `event` and left its own `note` out; the + // environment hid both, so the server has no entry left to serve. + const served = { ...lead, relatedLists: [], ...arranged(['task', 'event'], 'hidden') }; + + it('the list the owner left out stays hidden; another package\'s still shows, as under any declared list', () => { + expect(ids(served)).toEqual(['audit.lead_id']); + }); + + it('control: the same empty list with no decoration is the automatic one, where every list shows', () => { + expect(ids({ ...lead, relatedLists: [] })).toEqual([ + 'task.lead_id', 'note.lead_id', 'event.who_id', 'event.related_to', 'audit.lead_id', + ]); + }); + + it('control — `shown`: an empty list over the AUTOMATIC one keeps every list but the hidden ones', () => { + expect(ids({ ...lead, relatedLists: [], ...arranged(['task', 'event'], 'shown') })).toEqual(['note.lead_id', 'audit.lead_id']); + }); + + it('the authoring surface keeps the hidden and the left-out lists, flagged `isUnlisted`', () => { + const lists = deriveRelatedLists(served, registry as never, { includeHidden: true }); + expect(lists.filter((r) => r.isUnlisted).map((r) => r.childObject)).toEqual(['task', 'note', 'event', 'event']); + expect(lists.filter((r) => !r.isUnlisted).map((r) => r.childObject)).toEqual(['audit']); + }); +}); + +describe('PIN — no `.custom` arrangement served: the derivation is what it was', () => { + const declared = { ...lead, relatedLists: ['note', { list: 'event.related_to', label: 'Meetings', columns: ['subject'] }] }; + // Literal values, as the derivation answered before the decoration existed. + const DECLARED = [ + { childObject: 'note', childLabel: 'note', referenceField: 'lead_id', isOwned: false, isPrimary: false, isPlaceable: false }, + { + childObject: 'event', childLabel: 'event', referenceField: 'related_to', isOwned: false, isPrimary: false, isPlaceable: false, + title: 'Meetings', columns: ['subject'], + }, + { childObject: 'audit', childLabel: 'audit', referenceField: 'lead_id', isOwned: false, isPrimary: false, isPlaceable: false }, + ]; + const AUTOMATIC = ['task.lead_id', 'note.lead_id', 'event.who_id', 'event.related_to', 'audit.lead_id']; + + it('a declared list: named lists in order, an own-package unnamed list dropped, another package\'s kept', () => { + expect(deriveRelatedLists(declared, registry as never)).toEqual(DECLARED); + }); + + it('an undeclared list: every list, in the derived order', () => { + expect(ids(lead)).toEqual(AUTOMATIC); + }); + + it.each([ + ['absent', {}], + ['null', { _relatedListsArrangement: null }], + ['not a record', { _relatedListsArrangement: ['task'] }], + ['without a package', { _relatedListsArrangement: { hidden: ['note'], unlisted: 'shown' } }], + ])('a decoration that is %s is no arrangement: both answers are unchanged', (_label, decoration) => { + expect(deriveRelatedLists({ ...declared, ...decoration }, registry as never)).toEqual(DECLARED); + expect(ids({ ...lead, ...decoration })).toEqual(AUTOMATIC); + }); +}); diff --git a/ui/packages/app-shell/src/utils/deriveRelatedLists.ts b/ui/packages/app-shell/src/utils/deriveRelatedLists.ts index 0e4b60b4072..a271717b4b3 100644 --- a/ui/packages/app-shell/src/utils/deriveRelatedLists.ts +++ b/ui/packages/app-shell/src/utils/deriveRelatedLists.ts @@ -76,6 +76,21 @@ * The three built-in tab names (`RECORD_PAGE_BUILTIN_TABS` in * `@objectstack/spec/data`) name the page's own tabs, never a child list; * the synthesized page places those (`buildDefaultTabs`). + * - THE ENVIRONMENT'S TAB LIST (ADR-0146 D10): where the base's paired + * `.custom` package arranges the tabs, the server writes its list into the + * served `relatedLists` and says two more things beside it, in the served + * read's `_relatedListsArrangement` decoration (read through the spec's + * `readRelatedListsArrangement`), because only this derivation knows which + * lists exist for the reader. `hidden`: a side list one of those names + * names is not derived, whichever package brings it and whether or not + * `relatedLists` is declared (the authoring surface keeps it, flagged + * `isUnlisted`); a body table stays at its group and loses the tab it + * keeps. `unlisted: 'shown'`: a list no entry names is kept after the + * listed ones, as the automatic list the arrangement replaced showed it. + * `unlisted: 'hidden'`: the served list is a DECLARED one even when it is + * empty (the environment hid every tab of it), so a list no entry names + * follows the declared rule and a list the owner left out stays hidden. + * With no decoration, nothing in this derivation changes. * - An entry's own TITLE and COLUMNS (objectstack#35899): the object form * `{ list, label, columns }` wins over the FK's `relatedListTitle` / * `relatedListColumns`, for every list that entry names first, wherever @@ -98,6 +113,7 @@ import { isBodyTableRelationship, isGroupPlaceableRelationship, isRecordPageBuiltinTab, + readRelatedListsArrangement, relatedListEntryName, } from '@objectstack/spec/data'; import { convertSortToQueryParams } from '@object-ui/core'; @@ -203,7 +219,9 @@ export interface DerivedRelatedList { * list (objectstack#35897), so the record page shows no tab for it — present * only when the caller asked for hidden relationships * ({@link DeriveRelatedListsOptions.includeHidden}), as `isHidden` is. Never - * on a list another package brings (objectstack#35901): that one shows. + * on a list another package brings (objectstack#35901): that one shows, + * unless the environment's tab list hides it (ADR-0146 D10), which flags + * any side list it names, whichever package brings it. */ isUnlisted?: true; /** @@ -249,6 +267,13 @@ interface MergedObjectLike { * name, or `{ list, label?, columns? }`; see {@link resolveRelatedListOrder}. */ relatedLists?: unknown[]; + /** + * The served read's `_relatedListsArrangement` decoration (ADR-0146 D10), + * present when the base's paired `.custom` package arranges this object's + * tabs: `{ packageId, hidden, unlisted }`. Read only through the spec's + * `readRelatedListsArrangement`. + */ + _relatedListsArrangement?: unknown; /** * The spec's optional `fieldGroups`, read when this object is the parent: a * group's `relatedList` names the related list it places (objectstack#35889). @@ -567,16 +592,44 @@ export function deriveRelatedLists( // field groups' to place, so it stays, after the listed ones. // objectstack#35899 — the naming entry's own `label` / `columns` win over // the FK's `relatedListTitle` / `relatedListColumns`. + // ADR-0146 D10 — what the paired `.custom` package's tab list says beside + // the served `relatedLists`: the lists it hides, and whether a list no + // entry names still shows. `undefined` (no such arrangement) changes nothing. + const arrangement = readRelatedListsArrangement(objectDef); + const hiddenByArrangement = (list: Working): boolean => + arrangement !== undefined && arrangement.hidden.some((name) => relatedListEntryNames(name, list)); + const unlistedShown = arrangement?.unlisted === 'shown'; const derived = [...owned, ...referenced]; - const naming = relatedListNamingEntries(derived, objectDef.relatedLists); + // An empty `relatedLists` reads as "none declared". Beside `unlisted: + // 'hidden'` it is a declared list whose every tab the environment hid: no + // entry names a list, so the declared rule decides each one. + const naming = relatedListNamingEntries(derived, objectDef.relatedLists) + ?? (arrangement?.unlisted === 'hidden' ? new Map() : null); const all: Working[] = []; for (const list of resolveRelatedListOrder(derived, objectDef.relatedLists)) { + if (hiddenByArrangement(list)) { + // The environment hides this list's tab: a body table stays at its + // group with no tab, a side list is not derived, whichever package + // brings it. The authoring surface keeps it, flagged. + if (list.isPrimary) { + const { keepsTab: _hiddenTab, ...bodyOnly } = list; + all.push(bodyOnly); + } else if (options?.includeHidden) all.push({ ...list, isUnlisted: true }); + continue; + } if (!naming) { all.push(list); continue; } const entry = naming.get(list); if (!naming.has(list)) { + // ADR-0146 D10 — the environment's list replaced the AUTOMATIC one, in + // which every list shows: a list it does not name still does, after + // the listed ones, with the tab it had. + if (unlistedShown) { + all.push(list); + continue; + } // A body table no entry names stays at its group, with no tab: a // declared `relatedLists` decides the tabs, so the tab a group-placed // `master_detail` table keeps on the default page goes (the seat's diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.customArrangement-36498.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.customArrangement-36498.test.ts new file mode 100644 index 00000000000..e5a7cb537b0 --- /dev/null +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.customArrangement-36498.test.ts @@ -0,0 +1,103 @@ +/** + * objectstack#36498 (ADR-0146 D10) — the tab list the base's paired `.custom` + * package declares, laid over an object that declared none. Every tab the + * automatic list showed still shows, so the one thing the synthesized page + * reads from the served read's `_relatedListsArrangement` decoration is + * `unlisted: 'shown'`: an unlisted attachments tab is still drawn, at the end + * of the tabs. Which related lists exist is the host's (`deriveRelatedLists`). + * Laid over a DECLARED list (`unlisted: 'hidden'`), the served list is still a + * declared one when it is empty (every tab of it hidden): no attachments tab. + * + * With no decoration the tab row is what it was: each row's control differs + * from it by the decoration alone, and the last block pins the declared and + * the undeclared row against literal values. + */ +import { describe, it, expect } from 'vitest'; +import { buildDefaultTabs, type ObjectDefLike } from '../buildDefaultPageSchema'; + +/** A page component's props live in the node's `properties` bag (ADR-0089 D3a); no flat fallback. */ +const props = (node: any): Record => node?.properties ?? {}; +const tabItems = (node: any): any[] => props(node).items ?? []; + +const def = (relatedLists: unknown[] | undefined, decoration: Record = {}): ObjectDefLike => ({ + name: 'lead', + label: 'Lead', + fields: { name: { type: 'text', label: 'Name' } }, + enable: { files: true }, + ...(relatedLists ? { relatedLists } : {}), + ...decoration, +} as ObjectDefLike); + +const arranged = (unlisted: 'shown' | 'hidden') => ({ + _relatedListsArrangement: { packageId: 'com.vendor.crm.custom', hidden: [], unlisted }, +}); + +const related = [ + { objectName: 'task', relationshipField: 'lead_id' }, + { objectName: 'note', relationshipField: 'lead_id' }, +]; +const values = (d: ObjectDefLike) => + tabItems(buildDefaultTabs(d, { related, approvals: { count: 1 } })).map((t: any) => t.value); + +describe('the `.custom` tab list over the automatic one (`unlisted: shown`)', () => { + it('an unlisted attachments tab is still drawn, after the unlisted related tabs', () => { + expect(values(def(['note'], arranged('shown')))).toEqual([ + 'details', 'related:note.lead_id', 'related:task.lead_id', 'attachments', 'approvals', 'timeline', + ]); + }); + + it('control — no decoration: leaving `sys_attachment` out removes the attachments tab, as before', () => { + expect(values(def(['note']))).toEqual([ + 'details', 'related:note.lead_id', 'related:task.lead_id', 'approvals', 'timeline', + ]); + }); + + it('control — `unlisted: hidden` (the arrangement replaced a declared list): the served list\'s own rule', () => { + expect(values(def(['note'], arranged('hidden')))).toEqual([ + 'details', 'related:note.lead_id', 'related:task.lead_id', 'approvals', 'timeline', + ]); + }); + + it('a listed attachments tab sits at its entry either way', () => { + const listed = ['sys_attachment', 'note']; + const expected = ['details', 'attachments', 'related:note.lead_id', 'related:task.lead_id', 'approvals', 'timeline']; + expect(values(def(listed, arranged('shown')))).toEqual(expected); + expect(values(def(listed))).toEqual(expected); + }); + + it('the unlisted tabs sit before a trailing listed approvals / stream run', () => { + expect(values(def(['note', 'sys_activity'], arranged('shown')))).toEqual([ + 'details', 'related:note.lead_id', 'related:task.lead_id', 'attachments', 'timeline', 'approvals', + ]); + }); +}); + +describe('every tab of a declared list hidden: an empty served list beside `unlisted: hidden`', () => { + // The host passes the lists that still show: here one another package brings. + const host = [{ objectName: 'audit', relationshipField: 'lead_id' }]; + const row = (d: ObjectDefLike) => + tabItems(buildDefaultTabs(d, { related: host, approvals: { count: 1 } })).map((t: any) => t.value); + + it('the row follows the declared rules: no attachments tab, approvals and the stream close it', () => { + expect(row(def([], arranged('hidden')))).toEqual(['details', 'related:audit.lead_id', 'approvals', 'timeline']); + }); + + it('control: the same empty list with no decoration is the automatic row, attachments drawn', () => { + expect(row(def([]))).toEqual(['details', 'related:audit.lead_id', 'attachments', 'approvals', 'timeline']); + }); +}); + +describe('PIN — no `.custom` arrangement served: the tab row is what it was', () => { + const AUTOMATIC = ['details', 'related:task.lead_id', 'related:note.lead_id', 'attachments', 'approvals', 'timeline']; + const DECLARED = ['details', 'related:note.lead_id', 'related:task.lead_id', 'approvals', 'timeline']; + + it.each([ + ['absent', {}], + ['null', { _relatedListsArrangement: null }], + ['without a package', { _relatedListsArrangement: { hidden: [], unlisted: 'shown' } }], + ])('a decoration that is %s: the undeclared and the declared row are unchanged', (_label, decoration) => { + expect(values(def(undefined, decoration))).toEqual(AUTOMATIC); + expect(values(def([], decoration))).toEqual(AUTOMATIC); + expect(values(def(['note'], decoration))).toEqual(DECLARED); + }); +}); diff --git a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts index d69a1493ed0..3db3a357625 100644 --- a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts +++ b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts @@ -23,7 +23,7 @@ * the existing DetailView output. */ -import { deriveFieldGroupLayout, isRecordPageBuiltinTab, relatedListEntryName, type RecordPageBuiltinTab } from '@objectstack/spec/data'; +import { deriveFieldGroupLayout, isRecordPageBuiltinTab, readRelatedListsArrangement, relatedListEntryName, type RecordPageBuiltinTab } from '@objectstack/spec/data'; import { RECORD_HIGHLIGHTS_MAX } from '@objectstack/spec/ui'; import type { SelectOptionKind, ServiceObject } from '@objectstack/spec/data'; import { detectStatusField } from '@object-ui/types'; @@ -111,6 +111,14 @@ export interface ObjectDefLike { * columns) is the host's `related` option. See {@link buildDefaultTabs}. */ relatedLists?: readonly unknown[]; + /** + * The served read's `_relatedListsArrangement` decoration (ADR-0146 D10), + * present when the base's paired `.custom` package arranges this object's + * tabs. Read only through the spec's `readRelatedListsArrangement`, for + * `unlisted` (whether an unlisted attachments tab is still drawn, and + * whether an empty `relatedLists` is a declared list with every tab hidden). + */ + _relatedListsArrangement?: unknown; // NOTE: the per-surface `detail` hints block was REMOVED from the spec by // ADR-0085 — presentation intent is declared via the top-level semantic // roles above (stageField / highlightFields / fieldGroups). Per-page @@ -1092,7 +1100,9 @@ function synthTabs( } // objectstack#34590 — the 动态 tab closes the strip. if (timeline.length > 0) items.push({ label: 'Activity stream', value: 'timeline', children: timeline }); - return componentNode('page:tabs', { items: arrangeDeclaredTabs(def?.relatedLists, items) }); + return componentNode('page:tabs', { + items: arrangeDeclaredTabs(def?.relatedLists, items, readRelatedListsArrangement(def)?.unlisted), + }); } /** The tab value each built-in tab name draws (objectstack#35897). */ @@ -1105,7 +1115,8 @@ const BUILTIN_TAB_VALUES: Readonly> = { /** * objectstack#35897 — the object's declared `relatedLists` arranges the tabs * after the overview. Absent or empty: `items` exactly as built (every list, - * then attachments, approvals, the stream). Declared: + * then attachments, approvals, the stream), unless `unlistedTabs` is + * `'hidden'`, which says the empty list is a declared one. Declared: * * - each tab sits at the first entry naming it: a related tab at the entry * naming its relationship (`related:.`), a built-in at its @@ -1119,13 +1130,26 @@ const BUILTIN_TAB_VALUES: Readonly> = { * the end of the tabs: after the listed tabs, before a trailing run of * listed approvals / stream tabs, in the order passed. * + * `unlistedTabs` (ADR-0146 D10, `unlisted` of the served read's + * `_relatedListsArrangement` decoration; `undefined` for every object + * without it). `'shown'`: the list is the base's paired `.custom` package's, + * laid over an object that declared none, so every tab the automatic list + * showed still shows. The one difference here: an unlisted attachments tab is + * drawn too, at the end of the tabs after the unlisted related ones. + * `'hidden'`: the list is laid over a declared one, and stays a declared list + * when it is EMPTY (the environment hid every tab of it): the tabs follow the + * declared rules above with no entry naming any, so an unlisted attachments + * tab is not drawn. + * * Which related lists exist is the host's: `deriveRelatedLists` drops the * unlisted side lists. A pure, stable reorder of the tabs already built. */ -function arrangeDeclaredTabs(declared: readonly unknown[] | undefined, items: any[]): any[] { - if (!Array.isArray(declared) || declared.length === 0) return items; +function arrangeDeclaredTabs(declared: readonly unknown[] | undefined, items: any[], unlistedTabs?: 'shown' | 'hidden'): any[] { + const entries = Array.isArray(declared) ? declared : []; + if (entries.length === 0 && unlistedTabs !== 'hidden') return items; + const unlistedShown = unlistedTabs === 'shown'; const [overview, ...tabs] = items; - const names = declared.map((entry) => relatedListEntryName(entry)); + const names = entries.map((entry) => relatedListEntryName(entry)); const unlisted = names.length; // objectstack#35901 — the end of the tabs, for a related tab no entry names // (a list another package brings and does not place): before a trailing run @@ -1140,7 +1164,7 @@ function arrangeDeclaredTabs(declared: readonly unknown[] | undefined, items: an if (builtin) { const at = names.indexOf(builtin); if (at !== -1) return at; - if (builtin === 'sys_attachment') return null; + if (builtin === 'sys_attachment') return unlistedShown ? unlistedRelated : null; return builtin === 'sys_activity' ? unlisted + 1 : unlisted; } if (value.startsWith('related:')) {