From 62c5bd0a9f456b63410038ef3a6797e401a46449 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:33:53 +0000 Subject: [PATCH 1/9] feat(spec): an object extension places the fields, groups and child lists it brings (place) An objectExtensions entry gains `place`: { field, group, after|before }, { group: {...}, after|before } and { list, after|before, label?, columns? }. The parse refuses a placement of a field the extension does not add, both anchors at once, an item placed twice or next to itself, and a field whose own group disagrees with its placement. defineStack refuses a list (or a placed group's relatedList) that is not a child object of the extension's own package pointing at the target, and a group key the target declares. Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf Co-Authored-By: Claude --- .../src/data/object-extension-place.test.ts | 126 ++++++++ packages/spec/src/data/object.zod.ts | 290 +++++++++++++++++- .../spec/src/stack-extension-place.test.ts | 134 ++++++++ packages/spec/src/stack.zod.ts | 126 ++++++++ 4 files changed, 668 insertions(+), 8 deletions(-) create mode 100644 packages/spec/src/data/object-extension-place.test.ts create mode 100644 packages/spec/src/stack-extension-place.test.ts diff --git a/packages/spec/src/data/object-extension-place.test.ts b/packages/spec/src/data/object-extension-place.test.ts new file mode 100644 index 00000000000..e9d13d3153e --- /dev/null +++ b/packages/spec/src/data/object-extension-place.test.ts @@ -0,0 +1,126 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35901] `ObjectExtensionSchema.place` — an extension says where the + * fields, groups and child lists it brings go. The shape is judged here; an + * extension places only what it brings, so a placement naming a field outside + * its own `fields` is refused at the entry, naming whose the field is. Every + * refusal row differs from its control by one key alone. + */ +import { describe, it, expect } from 'vitest'; +import { ObjectExtensionSchema } from './object.zod'; + +const extension = (extra: Record = {}) => ({ + extend: 'account', + fields: { + tax_id: { type: 'text', label: 'Tax ID' }, + tax_region: { type: 'text', label: 'Tax region' }, + }, + ...extra, +}); + +const issuesAt = (input: unknown, path: string) => { + const parsed = ObjectExtensionSchema.safeParse(input); + if (parsed.success) return []; + return parsed.error.issues.filter((issue) => issue.path.join('.') === path).map((issue) => issue.message); +}; + +describe('ObjectExtensionSchema.place — the three entry forms', () => { + it('accepts a field, a group and a list placement (control)', () => { + const parsed = ObjectExtensionSchema.safeParse(extension({ + place: [ + { field: 'tax_id', group: 'basic', after: 'industry' }, + { group: { key: 'tax', label: 'Tax', fields: ['tax_region'] }, after: 'basic' }, + { list: 'contract', before: 'sys_activity', label: 'Contracts', columns: ['name', 'amount'] }, + ], + })); + expect(parsed.success).toBe(true); + }); + + it('accepts an entry with no anchor (the end)', () => { + expect(ObjectExtensionSchema.safeParse(extension({ place: [{ field: 'tax_id', group: 'basic' }] })).success).toBe(true); + expect(ObjectExtensionSchema.safeParse(extension({ place: [{ list: 'contract.account_id' }] })).success).toBe(true); + }); + + it.each([ + ['an unknown key on a field placement', { field: 'tax_id', group: 'basic', afer: 'industry' }], + ['a field placement with no group', { field: 'tax_id', after: 'industry' }], + ['a list placement naming a built-in tab', { list: 'sys_attachment' }], + ['a list placement whose name is no entry name', { list: 'Contract' }], + ['a group placement whose group has no label', { group: { key: 'tax' } }], + ])('refuses %s', (_label, entry) => { + expect(ObjectExtensionSchema.safeParse(extension({ place: [entry] })).success).toBe(false); + }); +}); + +describe('ObjectExtensionSchema.place — an extension places only what it brings', () => { + it('refuses a field of the extended object, at the entry, saying whose it is', () => { + const messages = issuesAt(extension({ place: [{ field: 'industry', group: 'other' }] }), 'place.0.field'); + expect(messages).toHaveLength(1); + expect(messages[0]).toContain('`industry` is not a field this extension adds'); + expect(messages[0]).toContain('A field of the extended object, or of another package\'s extension, is arranged by its owner'); + }); + + it('refuses a group whose fields name a field the extension does not add', () => { + const messages = issuesAt( + extension({ place: [{ group: { key: 'tax', label: 'Tax', fields: ['tax_id', 'industry'] } }] }), + 'place.0.group.fields.1', + ); + expect(messages).toHaveLength(1); + expect(messages[0]).toContain('`industry` is not a field this extension adds'); + }); + + it('refuses an entry that writes both after and before', () => { + const messages = issuesAt( + extension({ place: [{ field: 'tax_id', group: 'basic', after: 'industry', before: 'phone' }] }), + 'place.0.before', + ); + expect(messages).toEqual(['A placement writes `after` or `before`, not both: name the one item it sits next to.']); + }); + + it('refuses a field placed twice, by two entries or by an entry and its group\'s fields', () => { + expect(issuesAt( + extension({ place: [{ field: 'tax_id', group: 'basic' }, { field: 'tax_id', group: 'other' }] }), + 'place.1.field', + )).toHaveLength(1); + expect(issuesAt( + extension({ place: [{ field: 'tax_id', group: 'basic' }, { group: { key: 'tax', label: 'Tax', fields: ['tax_id'] } }] }), + 'place.1.group.fields.0', + )).toHaveLength(1); + }); + + it('refuses a list or a group placed twice, and an item anchored at itself', () => { + expect(issuesAt(extension({ place: [{ list: 'contract' }, { list: 'contract' }] }), 'place.1.list')).toHaveLength(1); + expect(issuesAt( + extension({ place: [{ group: { key: 'tax', label: 'Tax' } }, { group: { key: 'tax', label: 'Tax 2' } }] }), + 'place.1.group.key', + )).toHaveLength(1); + expect(issuesAt(extension({ place: [{ list: 'contract', after: 'contract' }] }), 'place.0.after')).toHaveLength(1); + }); + + it('refuses a field whose own group names another group than its placement', () => { + const input = extension({ + fields: { tax_id: { type: 'text', label: 'Tax ID', group: 'finance' } }, + place: [{ field: 'tax_id', group: 'basic' }], + }); + const messages = issuesAt(input, 'place.0.group'); + expect(messages).toHaveLength(1); + expect(messages[0]).toContain("declares `group: 'finance'` and this placement puts it in `basic`"); + // Control: the same group on both sides is one answer. + const agreeing = extension({ + fields: { tax_id: { type: 'text', label: 'Tax ID', group: 'basic' } }, + place: [{ field: 'tax_id', group: 'basic' }], + }); + expect(ObjectExtensionSchema.safeParse(agreeing).success).toBe(true); + }); +}); + +describe('ObjectExtensionSchema — the owner\'s arrangement keys point to place', () => { + 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`'); + }); +}); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 93200a9e3a9..f7d42a0a65b 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -4746,10 +4746,14 @@ const ObjectSchemaBase = strictObject( * that list its own title and columns on the parent; the two forms mix. A * built-in takes only the bare name. * - * A child list another package adds is no exception: once this list is - * declared, it shows no tab until an entry names it, and `defineStack` - * accepts that name only when the package is in the stack. Letting an - * extension package place its own list is epic #35896's child card #35901. + * [#35901] A child list another package brings is the exception: this + * list does not hide it. That package places it with its object + * extension's `place` (`{ list, after | before }`), which the registry merge + * splices into this list; an unplaced one shows after the listed tabs + * (before unlisted approvals and the stream). This object may also name it + * (`defineStack` accepts that name only when the package is in the stack), + * and then this object's position wins. A child of THIS object's package, + * or one no package owns, still shows only when an entry names it. * * The FK's `relatedList: false` still hides a list whatever this says. Body * tables a field group places in the overview (`fieldGroups[].relatedList`) @@ -4782,7 +4786,7 @@ const ObjectSchemaBase = strictObject( * (`ui/packages/app-shell/src/utils/deriveRelatedLists.ts`) and the * synthesized page's tab list (`buildDefaultTabs`). */ - relatedLists: z.array(RelatedListEntrySchema).optional().describe('The record page\'s tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be { list, label?, columns? } to give that list its own title and child-field columns (wins over the child FK\'s relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child\'s relationships, as relatedListColumns is) is refused.'), + relatedLists: z.array(RelatedListEntrySchema).optional().describe('The record page\'s tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension\'s place entry (an { list, after | before } entry), and an unplaced one shows after the listed tabs; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be { list, label?, columns? } to give that list its own title and child-field columns (wins over the child FK\'s relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child\'s relationships, as relatedListColumns is) is refused.'), /** * [ADR-0085] Semantic role: the field that represents the record's LINEAR * lifecycle (an ordered pipeline / stage progression). A string names the @@ -6370,6 +6374,253 @@ function fieldPatchesDescription(): string { ); } +// ================================================================= +// Extension placement (#35901, epic #35896) +// ================================================================= + +/** + * [#35901] Place ONE field this extension adds (a key of its own `fields`) + * into a field group of the extended object, after or before another member + * of that group. The group may be the target's own (`basic`) or one this + * extension adds with a group placement. + */ +export const ObjectExtensionFieldPlacementSchema = lazySchema(() => strictObject({ + surface: 'this field placement', + history: + 'A placement key nobody reads would be dropped silently: the field would still arrive, at the end of ' + + 'its group, and the author would believe the position they wrote had been applied.', + aliases: { name: 'field', fieldName: 'field', section: 'group', fieldGroup: 'group', below: 'after', above: 'before' }, +}, { + field: FieldNameKeySchema.describe('A field this extension adds: a key of its own `fields`. An extension places only what it brings.'), + group: z.string().regex(FIELD_GROUP_KEY_PATTERN, { + message: 'A field placement\'s group is a field group key of the extended object (snake_case, e.g. "basic")', + }).describe('The field group it joins: a group key of the extended object, or of a group this extension adds.'), + after: FieldNameKeySchema.optional().describe('Place it right after this member of the group (any field of the group, whoever declares it).'), + before: FieldNameKeySchema.optional().describe('Place it right before this member of the group. Write `after` or `before`, not both.'), +})); + +/** + * [#35901] Add ONE field group of this extension's own to the extended + * object, after or before one of its groups. The group is a whole + * {@link ObjectFieldGroupSchema}: its `fields` may name only fields this + * extension adds, and its `relatedList` only a child list this extension's + * package brings (judged where the package's objects are known). + */ +export const ObjectExtensionGroupPlacementSchema = lazySchema(() => strictObject({ + surface: 'this group placement', + history: + 'A placement key nobody reads would be dropped silently: the group would still arrive, last, and the ' + + 'author would believe the position they wrote had been applied.', + aliases: { fieldGroup: 'group', section: 'group', below: 'after', above: 'before' }, +}, { + group: ObjectFieldGroupSchema.describe('The field group this extension adds (key, label, and optionally fields or relatedList).'), + after: z.string().regex(FIELD_GROUP_KEY_PATTERN).optional().describe('Place it right after this group of the extended object (a group key).'), + before: z.string().regex(FIELD_GROUP_KEY_PATTERN).optional().describe('Place it right before this group. Write `after` or `before`, not both.'), +})); + +/** + * [#35901] Place ONE child list this extension's package brings (a child + * object of the package that points at the extended object, or + * `object.field` for one of its relationships) among the extended object's + * record-page tabs, after or before one of them, with that list's own title + * and columns as a `relatedLists` entry carries them. + */ +export const ObjectExtensionListPlacementSchema = lazySchema(() => strictObject({ + surface: 'this list placement', + history: + 'A placement key nobody reads would be dropped silently: the list would still show, in the automatic ' + + 'order, and the author would believe the position they wrote had been applied.', + aliases: { name: 'list', object: 'list', relationship: 'list', title: 'label', fields: 'columns', below: 'after', above: 'before' }, +}, { + list: z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: RELATED_LIST_ENTRY_NAME_MESSAGE }) + .regex(RELATED_LIST_OBJECT_ENTRY_NAME_PATTERN, { + message: + `${RECORD_PAGE_BUILTIN_TABS.map((n) => `'${n}'`).join(', ')} are the record page's built-in tabs, placed by ` + + 'the extended object itself: a list placement names a child list this package brings.', + }) + .describe('The child list this package brings: a child object of this package that points at the extended object, or object.field.'), + after: z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: RELATED_LIST_ENTRY_NAME_MESSAGE }).optional() + .describe('Place it right after this tab: a relatedLists entry name of the extended object (a child object, object.field, or a built-in tab).'), + before: z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: RELATED_LIST_ENTRY_NAME_MESSAGE }).optional() + .describe('Place it right before this tab. Write `after` or `before`, not both.'), + label: z.string().min(1).optional().describe("This list's title on the record page, as a relatedLists entry's label."), + columns: z.array(z.string().min(1)).min(1).optional() + .describe("This list's columns, as field names of the child object, as a relatedLists entry's columns."), +})); + +/** + * [#35901] One `place` entry of an object extension: a field, a group or a + * child list this extension brings, and where it goes. Told apart by its + * subject key: `field`, `list`, or `group` (an object). + */ +export const ObjectExtensionPlacementSchema = lazySchema(() => z.union([ + ObjectExtensionFieldPlacementSchema, + ObjectExtensionListPlacementSchema, + ObjectExtensionGroupPlacementSchema, +])); +/** One `place` entry as an author writes it. */ +export type ObjectExtensionPlacement = z.input; +/** One `place` entry after parse. */ +export type ObjectExtensionPlacementParsed = z.infer; + +/** A plain (non-array) object, as a placement entry or a field map is read before the root refinement. */ +function isPlacementRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** + * [#35901] The `place` description: what each entry form says, where an item + * lands when its anchor is missing, how several items at one anchor order, + * what applies when the extended object declares no arrangement of its own, + * and the one rule that an extension arranges only what it brings. + */ +function objectExtensionPlaceDescription(): string { + return ( + '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. Write `after` or `before`, or neither for the end. An anchor that ' + + 'does not exist 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, the field among the ungrouped ones); the boot log and `os validate` name each placement that ' + + 'did not apply. A child list another package brings shows even when the extended object\'s `relatedLists` ' + + 'does not name it: placed, at its place; unplaced, after the listed tabs. An extension places only its own ' + + 'items: a field outside its own `fields`, a group key the extended object or another package already ' + + 'declares, or a list that is not a child object of its package is refused (here, or at `defineStack` where ' + + 'the package\'s objects are known) and skipped by the merge with a warning naming whose item it is. 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\'] }]`.' + ); +} + +/** + * [#35901] Refuse a placement this extension may not write, located at the + * entry: one naming a field outside the extension's own `fields` (an + * extension places only what it brings; a field of the extended object or of + * another package's extension is its owner's to arrange), a group whose + * `fields` names such a field, an entry writing both `after` and `before`, an + * item placed twice (a field by two entries, or by an entry and its group's + * `fields`), an item anchored at itself, and a field whose own `group` names + * another group than its placement (two answers to one question, the rule the + * object parse holds for a group's `fields`). + * + * Shape only: whether a group key is already the extended object's, and + * whether a list is a child of this package, are judged where the other + * objects are known (`defineStack`; the registry merge for every door). + * Judged on the extension's root refinement, where `ObjectExtensionSchema` + * already carries one, so the published JSON Schema gains no + * dropped-refinement site. + */ +function refuseForeignPlacements(fields: unknown, place: unknown, ctx: z.RefinementCtx): void { + if (!Array.isArray(place)) return; + const own = isPlacementRecord(fields) ? fields : {}; + const isOwn = (name: string): boolean => Object.prototype.hasOwnProperty.call(own, name); + const placedField = new Set(); + const placedGroup = new Set(); + const placedList = new Set(); + const foreignField = (name: string): string => + `\`${name}\` is not a field this extension adds, so it cannot place it: an extension places only what it ` + + 'brings (a key of its own `fields`). A field of the extended object, or of another package\'s extension, is ' + + 'arranged by its owner. Add the field to this extension\'s `fields`, or remove the placement.'; + const twice = (what: string): string => + `${what} is placed twice: place each item this extension brings once.`; + place.forEach((entry: unknown, i: number) => { + if (!isPlacementRecord(entry)) return; + if (entry.after !== undefined && entry.before !== undefined) { + ctx.addIssue({ + code: 'custom', + path: ['place', i, 'before'], + message: 'A placement writes `after` or `before`, not both: name the one item it sits next to.', + }); + } + const anchoredAtItself = (name: string): boolean => entry.after === name || entry.before === name; + if (typeof entry.field === 'string') { + const name = entry.field; + if (!isOwn(name)) { + ctx.addIssue({ code: 'custom', path: ['place', i, 'field'], message: foreignField(name) }); + return; + } + if (placedField.has(name)) { + ctx.addIssue({ code: 'custom', path: ['place', i, 'field'], message: twice(`Field \`${name}\``) }); + } + placedField.add(name); + if (anchoredAtItself(name)) { + ctx.addIssue({ + code: 'custom', + path: ['place', i, entry.after === name ? 'after' : 'before'], + message: `Field \`${name}\` is placed next to itself: name another member of the group, or leave the anchor out for the end.`, + }); + } + const declared = own[name]; + const ownGroup = isPlacementRecord(declared) && typeof declared.group === 'string' ? declared.group : undefined; + if (ownGroup !== undefined && typeof entry.group === 'string' && ownGroup !== entry.group) { + ctx.addIssue({ + code: 'custom', + path: ['place', i, 'group'], + message: + `Field \`${name}\` declares \`group: '${ownGroup}'\` and this placement puts it in \`${entry.group}\`: ` + + 'write its group once, in the placement, and drop the field\'s own `group`.', + }); + } + return; + } + if (typeof entry.list === 'string') { + const name = entry.list; + if (placedList.has(name)) { + ctx.addIssue({ code: 'custom', path: ['place', i, 'list'], message: twice(`List \`${name}\``) }); + } + placedList.add(name); + if (anchoredAtItself(name)) { + ctx.addIssue({ + code: 'custom', + path: ['place', i, entry.after === name ? 'after' : 'before'], + message: `List \`${name}\` is placed next to itself: name another tab, or leave the anchor out for the end.`, + }); + } + return; + } + if (isPlacementRecord(entry.group)) { + const key = typeof entry.group.key === 'string' ? entry.group.key : undefined; + if (key !== undefined) { + if (placedGroup.has(key)) { + ctx.addIssue({ code: 'custom', path: ['place', i, 'group', 'key'], message: twice(`Group \`${key}\``) }); + } + placedGroup.add(key); + if (anchoredAtItself(key)) { + ctx.addIssue({ + code: 'custom', + path: ['place', i, entry.after === key ? 'after' : 'before'], + message: `Group \`${key}\` is placed next to itself: name another group, or leave the anchor out for the end.`, + }); + } + } + const members = Array.isArray(entry.group.fields) ? entry.group.fields : []; + members.forEach((member: unknown, j: number) => { + if (typeof member !== 'string') return; + if (!isOwn(member)) { + ctx.addIssue({ code: 'custom', path: ['place', i, 'group', 'fields', j], message: foreignField(member) }); + return; + } + if (placedField.has(member)) { + ctx.addIssue({ code: 'custom', path: ['place', i, 'group', 'fields', j], message: twice(`Field \`${member}\``) }); + } + placedField.add(member); + }); + } + }); +} + /** * Object Extension Entry — used in `objectExtensions` array. * Declares fields/config to merge into an existing object owned by another package. @@ -6432,10 +6683,17 @@ 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` cannot be contributed through an object extension — the merge does ' + - 'not carry them. Add the fields here and declare the groups on the owning object, ' + - 'or assign a Page for the layout.', + '`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.', // 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: @@ -6525,6 +6783,20 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ /** Additional indexes to add */ indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'), + /** + * [#35901] Where the fields, groups and child lists this extension brings go + * on the extended object's record page and forms: each entry names ONE item + * of this extension's own and an anchor (`after` or `before`). An extension + * places only what it brings — a field of its own `fields`, a group it adds, + * a child list of its own package — and never moves or hides the extended + * object's items or another package's (refused here, at `defineStack`, and + * skipped with a warning by the registry merge). Applied once, by the + * registry merge (`foldExtendersOntoDefinition` in `@objectstack/objectql`), + * so every reader of the object gets one arrangement. See + * {@link objectExtensionPlaceDescription} for the rules. + */ + place: z.array(ObjectExtensionPlacementSchema).optional().describe(objectExtensionPlaceDescription()), + /** 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) => { @@ -6535,6 +6807,8 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ refuseExtensionFieldPatchKeys(extension.fieldPatches, ctx); // …and a field the extension takes over in `fields` is not one either. 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); }).overwrite((extension) => { // [#23065] …and the object a referenceless `tree` field references. See // {@link materializeTreeSelfReferences}. diff --git a/packages/spec/src/stack-extension-place.test.ts b/packages/spec/src/stack-extension-place.test.ts new file mode 100644 index 00000000000..2bcdebe838d --- /dev/null +++ b/packages/spec/src/stack-extension-place.test.ts @@ -0,0 +1,134 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35901] `defineStack` judges the two placement questions that need a + * package's OBJECTS: a list placement (and a placed group's `relatedList`) + * names a child object the extension's own package body defines and that + * points at the extended object, and a placed group's key is not one of the + * extended object's own. Refusals assert the ADR-0112 envelope and the named + * subjects; every refusal row's control differs from it by one entry alone. + */ +import { describe, it, expect } from 'vitest'; +import { defineStack } from './stack.zod'; + +type Refusal = Error & { code?: string; status?: number; issues?: readonly string[] }; + +const manifest = { + id: 'com.example.xpl', + namespace: 'xpl', + name: 'xpl', + version: '1.0.0', + type: 'module' as const, +}; + +const account = { + name: 'xpl_account', + label: 'Account', + fields: { + name: { type: 'text' as const, label: 'Name', group: 'basic' }, + industry: { type: 'text' as const, label: 'Industry', group: 'basic' }, + }, + fieldGroups: [{ key: 'basic', label: 'Basic' }], +}; +const opportunity = { + name: 'xpl_opportunity', + label: 'Opportunity', + fields: { account_id: { type: 'lookup' as const, label: 'Account', reference: 'xpl_account' } }, +}; + +/** The extension package: its own child object, and its extension of the account. */ +const contract = { + name: 'xplx_contract', + label: 'Contract', + fields: { + account_id: { type: 'lookup' as const, label: 'Account', reference: 'xpl_account' }, + title: { type: 'text' as const, label: 'Title' }, + }, +}; +const memo = { name: 'xplx_memo', label: 'Memo', fields: { title: { type: 'text' as const, label: 'Title' } } }; + +const extensionPackage = (place: unknown[], objects: unknown[] = [contract, memo]) => ({ + manifest: { + id: 'com.example.xpl-ext', + namespace: 'xplx', + name: 'xpl_ext', + version: '1.0.0', + type: 'module' as const, + objects, + objectExtensions: [{ + extend: 'xpl_account', + fields: { tax_id: { type: 'text' as const, label: 'Tax ID' } }, + place, + }], + }, +}); + +const stackWith = (place: unknown[], objects?: unknown[]) => + ({ manifest, objects: [account, opportunity], packages: [extensionPackage(place, objects)] }) as any; + +const refusalOf = (fn: () => unknown): Refusal | undefined => { + try { + fn(); + return undefined; + } catch (e) { + return e as Refusal; + } +}; + +describe('defineStack — an extension places only a child list its own package brings', () => { + it('accepts a list placement naming its own child that points at the extended object (control)', () => { + expect(() => defineStack(stackWith([ + { field: 'tax_id', group: 'basic', after: 'industry' }, + { list: 'xplx_contract', after: 'xpl_opportunity' }, + { list: 'xplx_contract.account_id', before: 'sys_activity' }, + ]))).not.toThrow(); + }); + + it('refuses a list of the extended object\'s package, naming it as not this package\'s', () => { + const refusal = refusalOf(() => defineStack(stackWith([{ list: 'xpl_opportunity' }]))); + expect(refusal?.code).toBe('STACK_CROSS_REFERENCE_INVALID'); + expect(typeof refusal?.status).toBe('number'); + expect(refusal?.issues).toHaveLength(1); + expect(refusal?.issues?.[0]).toContain("place[0].list names 'xpl_opportunity', which is not a child object this package defines"); + expect(refusal?.issues?.[0]).toContain("The lists of 'xpl_account' and of other packages are arranged by their owners"); + }); + + it('refuses its own object that does not point at the extended object, and a field that is not the FK', () => { + const refusal = refusalOf(() => defineStack(stackWith([{ list: 'xplx_memo' }, { list: 'xplx_contract.title' }]))); + expect(refusal?.code).toBe('STACK_CROSS_REFERENCE_INVALID'); + expect(refusal?.issues).toHaveLength(2); + expect(refusal?.issues?.[0]).toContain("'xplx_memo' has no lookup / master_detail field whose reference is 'xpl_account'"); + expect(refusal?.issues?.[1]).toContain("'xplx_contract.title' is not a lookup / master_detail field"); + }); + + it('judges a placed group\'s relatedList the same way', () => { + const refusal = refusalOf(() => defineStack(stackWith([ + { group: { key: 'deals', label: 'Deals', relatedList: 'xpl_opportunity' }, after: 'basic' }, + ]))); + expect(refusal?.issues).toHaveLength(1); + expect(refusal?.issues?.[0]).toContain("place[0].group.relatedList names 'xpl_opportunity'"); + }); +}); + +describe('defineStack — an extension adds a group of its own', () => { + it('accepts a new group key (control)', () => { + expect(() => defineStack(stackWith([{ group: { key: 'tax', label: 'Tax' }, after: 'basic' }]))).not.toThrow(); + }); + + it('refuses a group key the extended object declares itself', () => { + const refusal = refusalOf(() => defineStack(stackWith([{ group: { key: 'basic', label: 'Mine' } }]))); + expect(refusal?.code).toBe('STACK_CROSS_REFERENCE_INVALID'); + expect(refusal?.issues).toHaveLength(1); + expect(refusal?.issues?.[0]).toContain("adds group 'basic', which is a group 'xpl_account' declares itself"); + }); +}); + +describe('defineStack — a missing anchor is no refusal', () => { + it('accepts anchors the extended object does not have (the merge puts the item at the end)', () => { + expect(() => defineStack(stackWith([ + { field: 'tax_id', group: 'basic', after: 'gone' }, + { list: 'xplx_contract', after: 'xpl_nowhere' }, + { group: { key: 'tax', label: 'Tax' }, before: 'missing' }, + ]))).not.toThrow(); + }); +}); diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 38ac64d7812..c85a082aca3 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -4627,6 +4627,129 @@ function collectRelatedListNameErrors( return errors; } +/** + * [#35901] An object extension places only what its own package brings + * (`ObjectExtensionSchema.place`). The parse judges fields and the entry's + * shape; the two questions that need the package's OBJECTS are judged here, + * per package body (the top level is one package, each + * `packages[i].manifest` another, ADR-0130 D4): + * + * - a list placement (`{ list }`), and a placed group's `relatedList`, must + * name a child object THIS body defines that points at the extended + * object (a `lookup` / `master_detail` field whose `reference` is it, or + * the one `object.field`). A child the body does not define belongs to the + * extended object's package or to another one, and is that owner's to + * arrange; + * - a placed group's `key` must not be one of the extended object's own + * group keys, where this stack defines that object: the group would be + * the owner's, which an extension does not arrange. + * + * Anchors are not judged here: a missing anchor puts the item at the end and + * is a `@objectstack/lint` warning, never a refusal, so removing a field from + * the extended object never makes its extensions unbuildable. + */ +function collectExtensionPlacementErrors(config: ObjectStackDefinition): string[] { + const asRecord = (value: unknown): Record | undefined => + isRecord(value) ? value : undefined; + const top = config as { objects?: unknown; objectExtensions?: unknown; packages?: unknown }; + const bodies: Array<{ body: { objects?: unknown; objectExtensions?: unknown }; at: string }> = [ + { body: top, at: '' }, + ...(Array.isArray(top.packages) + ? (top.packages as unknown[]).map((entry, i) => ({ + body: (asRecord(asRecord(entry)?.manifest) ?? {}) as { objects?: unknown; objectExtensions?: unknown }, + at: `packages[${i}].manifest.`, + })) + : []), + ]; + // Every object this stack defines, by name: the extended object's own group keys are read here. + const definedAnywhere = new Map>(); + for (const { body } of bodies) { + if (!Array.isArray(body.objects)) continue; + for (const obj of body.objects) { + const record = asRecord(obj); + if (record && typeof record.name === 'string' && !definedAnywhere.has(record.name)) { + definedAnywhere.set(record.name, record); + } + } + } + + const errors: string[] = []; + for (const { body, at } of bodies) { + if (!Array.isArray(body.objectExtensions)) continue; + // This body's own objects, with the fields its own extensions add to them. + const own = new Map>(); + if (Array.isArray(body.objects)) { + for (const obj of body.objects) { + const record = asRecord(obj); + if (record && typeof record.name === 'string') { + own.set(record.name, { ...own.get(record.name), ...asRecord(record.fields) }); + } + } + } + for (const ext of body.objectExtensions) { + const record = asRecord(ext); + if (!record || typeof record.extend !== 'string' || !own.has(record.extend)) continue; + own.set(record.extend, { ...own.get(record.extend), ...asRecord(record.fields) }); + } + + body.objectExtensions.forEach((ext: unknown, j: number) => { + const record = asRecord(ext); + if (!record || typeof record.extend !== 'string' || !Array.isArray(record.place)) return; + const target = record.extend; + const targetGroups = new Set( + (Array.isArray(definedAnywhere.get(target)?.fieldGroups) ? definedAnywhere.get(target)!.fieldGroups as unknown[] : []) + .map((g) => asRecord(g)?.key) + .filter((key): key is string => typeof key === 'string'), + ); + const judgeList = (name: string, where: string): void => { + const dot = name.indexOf('.'); + const child = dot === -1 ? name : name.slice(0, dot); + const field = dot === -1 ? undefined : name.slice(dot + 1); + const fields = own.get(child); + if (!fields) { + errors.push( + `${at}objectExtensions[${j}] (extending '${target}') ${where} names '${name}', which is not a child ` + + 'object this package defines: an extension places only a child list its own package brings. The ' + + `lists of '${target}' and of other packages are arranged by their owners. Define '${child}' in this ` + + 'package, or remove the placement.', + ); + return; + } + const points = Object.entries(fields).some(([fieldName, def]) => { + const fieldDef = asRecord(def); + return (field === undefined || fieldName === field) && fieldDef !== undefined + && (fieldDef.type === 'lookup' || fieldDef.type === 'master_detail') && fieldDef.reference === target; + }); + if (!points) { + errors.push( + `${at}objectExtensions[${j}] (extending '${target}') ${where} names '${name}', but ` + + `${field === undefined ? `'${child}' has no` : `'${child}.${field}' is not a`} lookup / master_detail ` + + `field whose reference is '${target}', so it is no child list of '${target}'. Point a field of ` + + `'${child}' at '${target}', or remove the placement.`, + ); + } + }; + (record.place as unknown[]).forEach((entry: unknown, k: number) => { + const placement = asRecord(entry); + if (!placement) return; + if (typeof placement.list === 'string') judgeList(placement.list, `place[${k}].list`); + const group = asRecord(placement.group); + if (!group) return; + if (typeof group.relatedList === 'string') judgeList(group.relatedList, `place[${k}].group.relatedList`); + if (typeof group.key === 'string' && targetGroups.has(group.key)) { + errors.push( + `${at}objectExtensions[${j}] (extending '${target}') place[${k}] adds group '${group.key}', which is ` + + `a group '${target}' declares itself: an extension adds a group of its own and never rearranges the ` + + `owner's. Give the group another key, or place the fields into '${group.key}' with ` + + `{ field, group: '${group.key}' } entries.`, + ); + } + }); + }); + } + return errors; +} + /** * [#20901] Inline grid columns whose TYPE comes from the child field, judged by * the column contract's own rules against the type they will render as. @@ -6019,6 +6142,9 @@ function validateCrossReferences( config, artifactObjects && artifactObjects.size > 0 ? new Set([...objectNames, ...artifactObjects]) : objectNames, )); + // Same placement: an extension's `place` resolves against its own package + // body's objects, whether or not the stack defines the extended object (#35901). + errors.push(...collectExtensionPlacementErrors(config)); if (objectNames.size === 0) return errors; From d78eba11623d4a9733886c3dec59ba278a3e7c2a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:47:48 +0000 Subject: [PATCH 2/9] feat(objectql,lint): the registry fold applies an object extension's place, and os validate names a placement that will not land The fold places each extension's own fields, groups and child lists after every contributor's fields are merged, in ascending priority then package name, so the record page, the forms and Studio read one arrangement. Where the extended object declares no relatedLists / fieldGroups the automatic arrangement stays and the boot log names the placement (Sales ruling 7073014077, arm (a), one switch). An item that is not the extension's own is skipped and named. The manifest loop carries place onto the extension def. os validate warns on a placement not applied and on a missing anchor. Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf Co-Authored-By: Claude --- packages/lint/src/index.ts | 12 + .../src/reference-integrity-suite.test.ts | 3 + .../lint/src/reference-integrity-suite.ts | 8 + packages/lint/src/rule-explanations.ts | 31 ++ .../src/validate-extension-placement.test.ts | 96 ++++ .../lint/src/validate-extension-placement.ts | 237 ++++++++++ packages/objectql/src/engine-registration.ts | 4 + .../src/registry-extension-placement.test.ts | 330 ++++++++++++++ .../src/registry-extension-placement.ts | 418 ++++++++++++++++++ .../src/registry-object-registration.ts | 32 +- packages/objectql/src/registry.ts | 16 + packages/spec/src/data/object.zod.ts | 13 +- 12 files changed, 1194 insertions(+), 6 deletions(-) create mode 100644 packages/lint/src/validate-extension-placement.test.ts create mode 100644 packages/lint/src/validate-extension-placement.ts create mode 100644 packages/objectql/src/registry-extension-placement.test.ts create mode 100644 packages/objectql/src/registry-extension-placement.ts diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index bb437de7c7a..6be2d24111f 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -672,6 +672,18 @@ export { RELATED_LIST_ATTACHMENTS_OFF, RELATED_LIST_STREAM_PART, } from './validate-related-list-refs.js'; + +// [#35901] Where an object extension's `place` will not land as written: +// the extended object declares no `relatedLists` / `fieldGroups` +// (`extension-placement-not-applied`), or an anchor it does not have +// (`extension-placement-anchor-missing`). Warnings; the boot log names the +// same placements, and is the channel for a target in another package. +export { + validateExtensionPlacement, + EXTENSION_PLACEMENT_NOT_APPLIED, + EXTENSION_PLACEMENT_ANCHOR_MISSING, +} from './validate-extension-placement.js'; +export type { ExtensionPlacementFinding } from './validate-extension-placement.js'; export type { RelatedListRefFinding, RelatedListRefOptions, diff --git a/packages/lint/src/reference-integrity-suite.test.ts b/packages/lint/src/reference-integrity-suite.test.ts index 85bd747b1e8..249acb0456e 100644 --- a/packages/lint/src/reference-integrity-suite.test.ts +++ b/packages/lint/src/reference-integrity-suite.test.ts @@ -35,6 +35,9 @@ describe('reference-integrity suite — membership', () => { // inbound relationships of its children: the door's copy of the verdict // `defineStack` gives on the CLI. 'validateRelatedListRefs', + // [#35901] Where an object extension's `place` will not land as written: + // warnings on the same objects' tabs and groups. + 'validateExtensionPlacement', 'validateActionNameRefs', // [#17319] The same action name, one question on: the name-ref member // above asks whether the selection bar's name resolves to an action; this diff --git a/packages/lint/src/reference-integrity-suite.ts b/packages/lint/src/reference-integrity-suite.ts index 0454c139cb9..93bd20d55df 100644 --- a/packages/lint/src/reference-integrity-suite.ts +++ b/packages/lint/src/reference-integrity-suite.ts @@ -107,6 +107,7 @@ import { validateSortableFields } from './validate-sortable-fields.js'; import { validateListViewFieldRefs } from './validate-list-view-field-refs.js'; import { validateObjectFieldRefs } from './validate-object-field-refs.js'; import { validateRelatedListRefs } from './validate-related-list-refs.js'; +import { validateExtensionPlacement } from './validate-extension-placement.js'; import { validateActionNameRefs } from './validate-action-name-refs.js'; import { validateActionDispatchContract } from './validate-action-dispatch-contract.js'; import { validatePageFieldBindings } from './validate-page-field-bindings.js'; @@ -492,6 +493,13 @@ export const REFERENCE_INTEGRITY_RULES: readonly ReferenceIntegrityRule[] = [ ctx?.runtimeWriteType !== undefined && !ctx?.packageScope ? { wholeCollection: true } : undefined, ), }, + // [#35901] The same object's tabs and groups, one question on: where an + // object extension's `place` will not land as written (the object declares + // no tab list or groups, or an anchor it does not have). Warnings only: the + // registry merge still places the item, and the boot log names it too. + // Default `runtimeTypes`: it reads `objectExtensions`, which a per-write + // object snapshot does not carry. + { name: 'validateExtensionPlacement', run: validateExtensionPlacement }, { name: 'validateActionNameRefs', run: validateActionNameRefs }, // [#17319] The same action name, one question on: `validateActionNameRefs` // asks whether the name a list view's selection bar writes resolves to an diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 0789d815581..cd66abd6d23 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -4784,6 +4784,35 @@ const RELATED_LIST_STREAM_PART_EXPLANATION: RuleExplanation = { ], }; +const EXTENSION_PLACEMENT_NOT_APPLIED_EXPLANATION: RuleExplanation = { + rule: 'extension-placement-not-applied', + covers: 'an object extension placement the target does not arrange', + paragraphs: [ + "An object extension's `place` arranges what the extended object declares: a list placement applies when " + + 'it declares `relatedLists`, a group or field placement when it declares `fieldGroups`. Where it declares ' + + 'none, its automatic arrangement stays: the list shows in the automatic tab order and the field among the ' + + 'fields, after the object\'s own. Nothing is dropped.', + "A list entry's `label` and `columns` are not applied either. To title the list and choose its columns on " + + "every parent, write `relatedListTitle` / `relatedListColumns` on the child object's lookup field.", + 'A warning: the placement applies, unchanged, once the extended object declares its tab list or groups. ' + + 'This check sees the extended object only when it is in the same stack; the boot log names the same ' + + 'placement wherever the object comes from.', + ], +}; + +const EXTENSION_PLACEMENT_ANCHOR_MISSING_EXPLANATION: RuleExplanation = { + rule: 'extension-placement-anchor-missing', + covers: 'an object extension placement whose anchor is missing', + paragraphs: [ + "A placement's `after` / `before` names a tab, group or group member of the extended object. One the " + + 'object does not have (and no extension of it in the stack places) puts the item at the end of the tabs ' + + '(before the approvals and activity-stream tabs), of the groups, or of the group. A field placed in a ' + + 'group the object does not have shows among the ungrouped fields.', + 'A warning: the item still shows. Name an anchor the object has, or drop the anchor to place the item at ' + + 'the end on purpose.', + ], +}; + // ── Object-name references (`validate-object-references.ts`) ──────────────── /** The sites judged — both object-reference ids. */ @@ -6644,6 +6673,8 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [RELATED_LIST_COLUMN_UNKNOWN_EXPLANATION.rule]: RELATED_LIST_COLUMN_UNKNOWN_EXPLANATION, [RELATED_LIST_ATTACHMENTS_OFF_EXPLANATION.rule]: RELATED_LIST_ATTACHMENTS_OFF_EXPLANATION, [RELATED_LIST_STREAM_PART_EXPLANATION.rule]: RELATED_LIST_STREAM_PART_EXPLANATION, + [EXTENSION_PLACEMENT_NOT_APPLIED_EXPLANATION.rule]: EXTENSION_PLACEMENT_NOT_APPLIED_EXPLANATION, + [EXTENSION_PLACEMENT_ANCHOR_MISSING_EXPLANATION.rule]: EXTENSION_PLACEMENT_ANCHOR_MISSING_EXPLANATION, [OBJECT_REFERENCE_UNKNOWN_EXPLANATION.rule]: OBJECT_REFERENCE_UNKNOWN_EXPLANATION, [OBJECT_REFERENCE_UNREGISTERED_PLATFORM_EXPLANATION.rule]: OBJECT_REFERENCE_UNREGISTERED_PLATFORM_EXPLANATION, [CAPABILITY_REFERENCE_UNKNOWN_EXPLANATION.rule]: CAPABILITY_REFERENCE_UNKNOWN_EXPLANATION, diff --git a/packages/lint/src/validate-extension-placement.test.ts b/packages/lint/src/validate-extension-placement.test.ts new file mode 100644 index 00000000000..242ebacd752 --- /dev/null +++ b/packages/lint/src/validate-extension-placement.test.ts @@ -0,0 +1,96 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35901] `os validate` names an object extension's placement that will not + * land as written, when the extended object is in the stack: not applied (the + * object declares no tab list / groups), or an anchor it does not have. + * Warnings only. Each finding row differs from the control by one key. + */ + +import { describe, it, expect } from 'vitest'; +import { + EXTENSION_PLACEMENT_ANCHOR_MISSING, + EXTENSION_PLACEMENT_NOT_APPLIED, + validateExtensionPlacement, +} from './validate-extension-placement.js'; +import { validateReferenceIntegrity } from './reference-integrity-suite.js'; + +const account = (extra: Record = {}) => ({ + name: 'account', + fields: { + name: { type: 'text', group: 'basic' }, + industry: { type: 'text', group: 'basic' }, + }, + fieldGroups: [{ key: 'basic', label: 'Basic' }], + relatedLists: ['opportunity'], + ...extra, +}); + +const stackWith = (place: unknown[], target: Record = account()) => ({ + objects: [target], + objectExtensions: [{ extend: 'account', fields: { tax_id: { type: 'text' } }, place }], +}); + +const CONTROL = [ + { field: 'tax_id', group: 'basic', after: 'industry' }, + { group: { key: 'tax', label: 'Tax' }, after: 'basic' }, + { list: 'contract', after: 'opportunity' }, + { list: 'contract.account_id', before: 'sys_activity' }, +]; + +const rules = (stack: Record) => validateExtensionPlacement(stack).map((f) => `${f.rule}@${f.path}`); + +describe('validateExtensionPlacement', () => { + it('names nothing for placements whose anchors the object has (control)', () => { + expect(validateExtensionPlacement(stackWith(CONTROL))).toEqual([]); + }); + + it('names a list placement on an object with no relatedLists, and its inert label / columns', () => { + const findings = validateExtensionPlacement(stackWith([{ list: 'contract', label: 'Contracts' }], account({ relatedLists: undefined }))); + expect(findings.map((f) => f.rule)).toEqual([EXTENSION_PLACEMENT_NOT_APPLIED]); + expect(findings[0].severity).toBe('warning'); + expect(findings[0].message).toContain("declares no `relatedLists`"); + expect(findings[0].message).toContain('label / columns are not applied either'); + expect(findings[0].hint).toContain('relatedListTitle / relatedListColumns'); + }); + + it('names group and field placements on an object with no fieldGroups, the field\'s after included', () => { + const findings = validateExtensionPlacement(stackWith(CONTROL.slice(0, 2), account({ fieldGroups: undefined }))); + expect(findings.map((f) => f.rule)).toEqual([EXTENSION_PLACEMENT_NOT_APPLIED, EXTENSION_PLACEMENT_NOT_APPLIED]); + expect(findings[0].message).toContain("field `tax_id` in group 'basic' after 'industry'"); + }); + + it.each([ + ['a list anchor', { list: 'contract', after: 'invoice' }], + ['a group anchor', { group: { key: 'tax', label: 'Tax' }, before: 'finance' }], + ['a field anchor', { field: 'tax_id', group: 'basic', after: 'phone' }], + ['a field\'s group', { field: 'tax_id', group: 'finance' }], + ])('names %s the object does not have', (_label, entry) => { + expect(rules(stackWith([entry]))).toEqual([`${EXTENSION_PLACEMENT_ANCHOR_MISSING}@objectExtensions[0].place[0]`]); + }); + + it('accepts an anchor another extension of the same object places', () => { + const stack = { + objects: [account()], + objectExtensions: [ + { extend: 'account', fields: { tax_id: { type: 'text' } }, place: [{ group: { key: 'tax', label: 'Tax' } }] }, + { extend: 'account', fields: { vat: { type: 'text' } }, place: [{ field: 'vat', group: 'tax' }, { group: { key: 'audit', label: 'Audit' }, after: 'tax' }] }, + ], + }; + expect(validateExtensionPlacement(stack)).toEqual([]); + }); + + it('judges a package body\'s extensions against the stack\'s objects, and skips a target outside the stack', () => { + const inPackage = { + objects: [account({ relatedLists: undefined })], + packages: [{ manifest: { objectExtensions: [{ extend: 'account', place: [{ list: 'contract' }] }] } }], + }; + expect(rules(inPackage)).toEqual([`${EXTENSION_PLACEMENT_NOT_APPLIED}@packages[0].manifest.objectExtensions[0].place[0]`]); + expect(validateExtensionPlacement({ objects: [], objectExtensions: [{ extend: 'account', place: [{ list: 'contract' }] }] })).toEqual([]); + }); + + it('runs in the reference-integrity suite', () => { + const findings = validateReferenceIntegrity(stackWith([{ list: 'contract', after: 'invoice' }]) as never); + expect(findings.some((f) => f.rule === EXTENSION_PLACEMENT_ANCHOR_MISSING)).toBe(true); + }); +}); diff --git a/packages/lint/src/validate-extension-placement.ts b/packages/lint/src/validate-extension-placement.ts new file mode 100644 index 00000000000..7237a463871 --- /dev/null +++ b/packages/lint/src/validate-extension-placement.ts @@ -0,0 +1,237 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35901] Where an object extension's `place` will not land as written, said + * at `os validate` — warnings, never refusals: the registry merge places the + * item at the end (or leaves the object's automatic arrangement) and names the + * same placement in the boot log, which stays the main channel, since this + * rule sees an extension's target only when the target object is in the same + * stack (a target in another package is outside it). + * + * - `extension-placement-not-applied`: the extended object declares no + * `relatedLists` (for a list placement) or no `fieldGroups` (for a group or + * field placement), so the placement is not applied (Sales ruling + * 7073014077 on #35901, arm (a)): the list keeps the automatic tab order, + * with the entry's `label` / `columns` not applied either; the field keeps + * its place among the fields, its `after` / `before` not applied. + * - `extension-placement-anchor-missing`: the `after` / `before` names a tab, + * group or group member the extended object has not (nor any extension of + * it in this stack places), so the item goes to the end; or a field + * placement names a group the object has not, so the field shows + * ungrouped. `before` a trailing built-in tab the object leaves unlisted is + * the end of the tabs anyway, and is not named. + * + * Which items an extension may place at all (its own fields, a group key of + * its own, a child list of its own package) is `defineStack`'s refusal and the + * object extension parse's, not this rule's. + */ + +import { readFieldGroupMembership, relatedListEntryName } from '@objectstack/spec/data'; +import { recordsOf } from './object-graph.js'; + +/** A placement the extended object declares no arrangement for. */ +export const EXTENSION_PLACEMENT_NOT_APPLIED = 'extension-placement-not-applied'; + +/** A placement whose anchor (or group) the extended object does not have. */ +export const EXTENSION_PLACEMENT_ANCHOR_MISSING = 'extension-placement-anchor-missing'; + +export interface ExtensionPlacementFinding { + severity: 'warning'; + rule: string; + where: string; + path: string; + message: string; + hint: string; +} + +type AnyRec = Record; + +const isRec = (v: unknown): v is AnyRec => typeof v === 'object' && v !== null && !Array.isArray(v); +const str = (v: unknown): string | undefined => (typeof v === 'string' && v.length > 0 ? v : undefined); + +const TRAILING_BUILTIN_TABS: ReadonlySet = new Set(['sys_approval_request', 'sys_activity']); + +interface Extension { + readonly at: string; + readonly target: string; + readonly place: readonly unknown[]; + readonly fields: readonly AnyRec[]; +} + +/** Every `objectExtensions` entry of the stack and of each package body, with its path. */ +function extensionsOf(stack: AnyRec): Extension[] { + const out: Extension[] = []; + const collect = (entries: unknown, at: string): void => { + if (!Array.isArray(entries)) return; + entries.forEach((ext, i) => { + if (!isRec(ext) || typeof ext.extend !== 'string' || !Array.isArray(ext.place)) return; + out.push({ at: `${at}objectExtensions[${i}]`, target: ext.extend, place: ext.place, fields: recordsOf(ext.fields) }); + }); + }; + collect(stack.objectExtensions, ''); + if (Array.isArray(stack.packages)) { + stack.packages.forEach((entry, j) => { + const body = isRec(entry) ? entry.manifest : undefined; + if (isRec(body)) collect(body.objectExtensions, `packages[${j}].manifest.`); + }); + } + return out; +} + +/** Every object the stack declares, top level and in each package body, by name. */ +function objectsByName(stack: AnyRec): Map { + const byName = new Map(); + const add = (objects: unknown): void => { + for (const obj of recordsOf(objects)) if (typeof obj.name === 'string') byName.set(obj.name, obj); + }; + add(stack.objects); + if (Array.isArray(stack.packages)) { + for (const entry of stack.packages) { + const body = isRec(entry) ? entry.manifest : undefined; + if (isRec(body)) add(body.objects); + } + } + return byName; +} + +/** An object's fields as a record by name, whichever shape it writes, with the extensions' fields added. */ +function fieldRecord(obj: AnyRec, extensionFields: readonly AnyRec[]): Record { + const out: Record = {}; + const raw = obj.fields; + if (isRec(raw)) { + for (const [name, def] of Object.entries(raw)) if (isRec(def)) out[name] = def; + } else { + for (const def of recordsOf(raw)) if (typeof def.name === 'string') out[def.name] = def; + } + for (const def of extensionFields) if (typeof def.name === 'string' && !(def.name in out)) out[def.name] = def; + return out; +} + +/** + * Judge every `place` entry of every object extension whose target object + * the stack declares. Pure `(stack) => Finding[]`. + */ +export function validateExtensionPlacement(stack: AnyRec): ExtensionPlacementFinding[] { + const findings: ExtensionPlacementFinding[] = []; + if (!isRec(stack)) return findings; + const extensions = extensionsOf(stack); + if (extensions.length === 0) return findings; + const objects = objectsByName(stack); + + for (const ext of extensions) { + const target = objects.get(ext.target); + if (!target) continue; + // What every extension of this target in the stack places: an anchor may name one of them. + const siblings = extensions.filter((other) => other.target === ext.target); + const placedLists = new Set(); + const placedGroups = new Set(); + const placedFields = new Map>(); + for (const other of siblings) { + for (const entry of other.place) { + if (!isRec(entry)) continue; + if (typeof entry.list === 'string') placedLists.add(entry.list); + if (isRec(entry.group) && typeof entry.group.key === 'string') placedGroups.add(entry.group.key); + if (typeof entry.field === 'string' && typeof entry.group === 'string') { + const set = placedFields.get(entry.group) ?? new Set(); + set.add(entry.field); + placedFields.set(entry.group, set); + } + } + } + const tabs = Array.isArray(target.relatedLists) ? target.relatedLists : []; + const groups = Array.isArray(target.fieldGroups) ? target.fieldGroups : []; + const tabNames = new Set(tabs.map((entry) => relatedListEntryName(entry)).filter((n): n is string => n !== undefined)); + const groupKeys = new Set(groups.map((g) => (isRec(g) ? str(g.key) : undefined)).filter((k): k is string => k !== undefined)); + const membership = readFieldGroupMembership({ fields: fieldRecord(target, siblings.flatMap((other) => other.fields)), fieldGroups: groups }); + const who = `object extension of "${ext.target}"`; + + ext.place.forEach((entry, k) => { + if (!isRec(entry)) return; + const path = `${ext.at}.place[${k}]`; + const after = str(entry.after); + const before = str(entry.before); + const anchor = after ?? before; + const anchorWord = after !== undefined ? 'after' : 'before'; + const missing = (subject: string, kind: string, hint: string): void => { + findings.push({ + severity: 'warning', + rule: EXTENSION_PLACEMENT_ANCHOR_MISSING, + where: `${who} › place`, + path, + message: `${path} places ${subject} ${anchorWord} '${anchor}', but '${ext.target}' has no such ${kind}, so the item goes to the end.`, + hint, + }); + }; + const notApplied = (subject: string, key: 'relatedLists' | 'fieldGroups', shows: string): void => { + findings.push({ + severity: 'warning', + rule: EXTENSION_PLACEMENT_NOT_APPLIED, + where: `${who} › place`, + path, + message: + `${path} places ${subject}, which is not applied: '${ext.target}' declares no \`${key}\`, so ${shows}. ` + + `It applies once '${ext.target}' declares \`${key}\`.`, + hint: + key === 'relatedLists' + ? `Ask the owner of '${ext.target}' to declare relatedLists; to title the list and choose its columns on every parent, write relatedListTitle / relatedListColumns on your child object's lookup field.` + : `Ask the owner of '${ext.target}' to declare fieldGroups; until then your fields show after its own, in declaration order.`, + }); + }; + + if (typeof entry.list === 'string') { + const list = entry.list; + if (tabs.length === 0) { + const inert = entry.label !== undefined || entry.columns !== undefined; + notApplied( + `list '${list}'`, + 'relatedLists', + `its tabs keep the automatic order and the list shows there${inert ? ', and this entry\'s label / columns are not applied either' : ''}`, + ); + return; + } + if (anchor === undefined || tabNames.has(anchor) || placedLists.has(anchor)) return; + if (before !== undefined && TRAILING_BUILTIN_TABS.has(before)) return; + missing(`list '${list}'`, 'tab in its relatedLists', `Name a relatedLists entry of '${ext.target}', or drop the anchor to place the list at the end of the tabs.`); + return; + } + if (isRec(entry.group)) { + const key = str(entry.group.key) ?? '?'; + if (groups.length === 0) { + notApplied(`field group '${key}'`, 'fieldGroups', 'its fields show ungrouped, and the fields this group lists show among them'); + return; + } + if (anchor === undefined || groupKeys.has(anchor) || placedGroups.has(anchor)) return; + missing(`field group '${key}'`, 'field group', `Name a fieldGroups key of '${ext.target}', or drop the anchor to place the group last.`); + return; + } + if (typeof entry.field === 'string' && typeof entry.group === 'string') { + const field = entry.field; + const group = entry.group; + if (groups.length === 0) { + notApplied( + `field \`${field}\` in group '${group}'${anchor !== undefined ? ` ${anchorWord} '${anchor}'` : ''}`, + 'fieldGroups', + 'the field shows among its fields in declaration order, after the object\'s own', + ); + return; + } + if (!groupKeys.has(group) && !placedGroups.has(group)) { + findings.push({ + severity: 'warning', + rule: EXTENSION_PLACEMENT_ANCHOR_MISSING, + where: `${who} › place`, + path, + message: `${path} places field \`${field}\` in group '${group}', but '${ext.target}' has no such field group, so the field shows among the ungrouped fields.`, + hint: `Name a fieldGroups key of '${ext.target}', or add the group with a { group: { key: '${group}', label } } entry.`, + }); + return; + } + if (anchor === undefined) return; + const members = membership.members.get(group) ?? []; + if (members.includes(anchor) || placedFields.get(group)?.has(anchor)) return; + missing(`field \`${field}\``, `member in group '${group}'`, `Name a field of group '${group}', or drop the anchor to place the field last in the group.`); + } + }); + } + return findings; +} diff --git a/packages/objectql/src/engine-registration.ts b/packages/objectql/src/engine-registration.ts index bf1ca203f5c..7707d899968 100644 --- a/packages/objectql/src/engine-registration.ts +++ b/packages/objectql/src/engine-registration.ts @@ -411,6 +411,10 @@ export class RegistrationFacet { description: ext.description, validations: ext.validations, indexes: ext.indexes, + // [#35901] Where its own fields, groups and child lists go — + // applied by the registry fold after every contributor's + // fields are merged (`applyExtensionPlacements`). + place: ext.place, }; // Register as extension (namespace is undefined since we're targeting by FQN) this._registry.registerObject(stampPackage(extDef, id, version), id, undefined, 'extend', priority); diff --git a/packages/objectql/src/registry-extension-placement.test.ts b/packages/objectql/src/registry-extension-placement.test.ts new file mode 100644 index 00000000000..4bc79b1af36 --- /dev/null +++ b/packages/objectql/src/registry-extension-placement.test.ts @@ -0,0 +1,330 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35901] The registry fold applies each object extension's `place` once, + * after every contributor's fields are merged: a field it adds lands after + * the member it names, a group it adds after the group it names, a child list + * of its package after the tab it names. Two packages at one anchor order by + * priority, then package name, whatever order they registered in. Uninstalling + * or disabling the package takes its items off and leaves the owner's order + * as it was. Where the extended object declares no tab list (no field groups), + * its automatic arrangement stays and the placement is named once in the log + * (Sales ruling 7073014077: arm (a)). An item that is not the extension's own + * is skipped, named. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { SchemaRegistry } from './registry.js'; +import { ObjectQL } from './engine.js'; +import { PLACEMENT_ARRANGES_DECLARED_ONLY, applyExtensionPlacements } from './registry-extension-placement.js'; + +const OWNER_PKG = 'com.vendor.crm'; +const EXT_PKG = 'com.acme.contracts'; +const OBJ = 'crm_account'; + +/** The vendor's account: one group whose members come from each field's own `group`. */ +function vendorAccount(extra: Record = {}): any { + return { + name: OBJ, + label: 'Account', + fields: { + name: { name: 'name', type: 'text', label: 'Name', group: 'basic' }, + industry: { name: 'industry', type: 'text', label: 'Industry', group: 'basic' }, + phone: { name: 'phone', type: 'text', label: 'Phone', group: 'basic' }, + notes: { name: 'notes', type: 'textarea', label: 'Notes', group: 'more' }, + }, + fieldGroups: [{ key: 'basic', label: 'Basic' }, { key: 'more', label: 'More' }], + relatedLists: ['crm_contact', 'crm_opportunity'], + ...extra, + }; +} + +const child = (name: string, label: string) => ({ + name, + label, + fields: { account_id: { name: 'account_id', type: 'lookup', label: 'Account', reference: OBJ } }, +}); + +function registry(): SchemaRegistry { + const reg = new SchemaRegistry({ multiTenant: false, searchCompanion: false } as never); + reg.logLevel = 'silent'; + return reg; +} + +function withVendor(account: any = vendorAccount(), reg = registry()): SchemaRegistry { + reg.registerObject(account, OWNER_PKG, undefined, 'own'); + reg.registerObject(child('crm_contact', 'Contact') as any, OWNER_PKG, undefined, 'own'); + reg.registerObject(child('crm_opportunity', 'Opportunity') as any, OWNER_PKG, undefined, 'own'); + return reg; +} + +const TAX_ID = { name: 'tax_id', type: 'text', label: 'Tax ID' }; + +function extend(reg: SchemaRegistry, place: unknown[], options: { pkg?: string; priority?: number; fields?: Record } = {}): void { + reg.registerObject( + { name: OBJ, fields: options.fields ?? { tax_id: TAX_ID }, place } as any, + options.pkg ?? EXT_PKG, + undefined, + 'extend', + options.priority ?? 200, + ); +} + +const served = (reg: SchemaRegistry): any => reg.getObject(OBJ); +const groupFields = (body: any, key: string): unknown => body.fieldGroups.find((g: any) => g.key === key)?.fields; + +afterEach(() => vi.restoreAllMocks()); + +describe('#35901 — a field the extension adds lands where it says', () => { + it('tax_id after industry: in the group, between industry and phone, its group set', () => { + const reg = withVendor(); + extend(reg, [{ field: 'tax_id', group: 'basic', after: 'industry' }]); + const body = served(reg); + expect(groupFields(body, 'basic')).toEqual(['name', 'industry', 'tax_id', 'phone']); + expect(body.fields.tax_id.group).toBe('basic'); + // The other group, and the order of the object's fields, are untouched. + expect(groupFields(body, 'more')).toBeUndefined(); + const authored = new Set(['name', 'industry', 'phone', 'notes', 'tax_id']); + expect(Object.keys(body.fields).filter((f) => authored.has(f))).toEqual(['name', 'industry', 'phone', 'notes', 'tax_id']); + }); + + it('before an anchor, and with no anchor at the end of the group', () => { + const reg = withVendor(); + extend(reg, [{ field: 'tax_id', group: 'basic', before: 'name' }]); + expect(groupFields(served(reg), 'basic')).toEqual(['tax_id', 'name', 'industry', 'phone']); + + const end = withVendor(); + extend(end, [{ field: 'tax_id', group: 'more' }]); + expect(groupFields(served(end), 'more')).toEqual(['notes', 'tax_id']); + }); + + it('a group that lists its members keeps its list and takes the field in it', () => { + const account = vendorAccount({ fieldGroups: [{ key: 'basic', label: 'Basic', fields: ['phone', 'name', 'industry'] }, { key: 'more', label: 'More' }] }); + const reg = withVendor(account); + extend(reg, [{ field: 'tax_id', group: 'basic', after: 'name' }]); + expect(groupFields(served(reg), 'basic')).toEqual(['phone', 'name', 'tax_id', 'industry']); + }); + + it('an anchor the object no longer has puts the field last in the group, named once', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const account = vendorAccount(); + delete account.fields.industry; + const reg = withVendor(account); + extend(reg, [{ field: 'tax_id', group: 'basic', after: 'industry' }]); + expect(groupFields(served(reg), 'basic')).toEqual(['name', 'phone', 'tax_id']); + served(reg); + reg.foldObjectExtendersOnto(OBJ, account); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes("after 'industry'")); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(`from package "${EXT_PKG}"`); + expect(lines[0]).toContain('placed last in the group'); + }); +}); + +describe('#35901 — a group the extension adds lands where it says', () => { + it('after basic, holding the fields it lists; a field placed into it joins it', () => { + const reg = withVendor(); + extend( + reg, + [ + { group: { key: 'tax', label: 'Tax', fields: ['tax_region'] }, after: 'basic' }, + { field: 'tax_id', group: 'tax', before: 'tax_region' }, + ], + { fields: { tax_id: TAX_ID, tax_region: { name: 'tax_region', type: 'text', label: 'Tax region' } } }, + ); + const body = served(reg); + expect(body.fieldGroups.map((g: any) => g.key)).toEqual(['basic', 'tax', 'more']); + expect(groupFields(body, 'tax')).toEqual(['tax_id', 'tax_region']); + }); +}); + +describe('#35901 — a child list of the extension\'s package lands among the tabs', () => { + const contract = () => child('acme_contract', 'Contract'); + + it('relatedLists [contact, opportunity] + contract after opportunity', () => { + const reg = withVendor(); + reg.registerObject(contract() as any, EXT_PKG, undefined, 'own'); + extend(reg, [{ list: 'acme_contract', after: 'crm_opportunity' }]); + expect(served(reg).relatedLists).toEqual(['crm_contact', 'crm_opportunity', 'acme_contract']); + }); + + it('before a tab, with its own title and columns as the object form', () => { + const reg = withVendor(); + reg.registerObject(contract() as any, EXT_PKG, undefined, 'own'); + extend(reg, [{ list: 'acme_contract.account_id', before: 'crm_opportunity', label: 'Contracts', columns: ['name'] }]); + expect(served(reg).relatedLists).toEqual([ + 'crm_contact', + { list: 'acme_contract.account_id', label: 'Contracts', columns: ['name'] }, + 'crm_opportunity', + ]); + }); + + it('with no anchor, at the end of the tabs, before a trailing approvals / stream tab', () => { + const reg = withVendor(vendorAccount({ relatedLists: ['crm_contact', 'sys_approval_request', 'sys_activity'] })); + extend(reg, [{ list: 'acme_contract' }]); + expect(served(reg).relatedLists).toEqual(['crm_contact', 'acme_contract', 'sys_approval_request', 'sys_activity']); + }); + + it('the owner already naming the list keeps the owner\'s position', () => { + const reg = withVendor(vendorAccount({ relatedLists: ['acme_contract', 'crm_contact', 'crm_opportunity'] })); + extend(reg, [{ list: 'acme_contract', after: 'crm_opportunity' }]); + expect(served(reg).relatedLists).toEqual(['acme_contract', 'crm_contact', 'crm_opportunity']); + }); +}); + +describe('#35901 — several packages at one anchor order by priority, then package name', () => { + const A = 'com.alpha.ext'; + const B = 'com.beta.ext'; + const place = (reg: SchemaRegistry, pkg: string, list: string, priority: number) => { + reg.registerObject(child(list, list) as any, pkg, undefined, 'own'); + extend(reg, [{ list, after: 'crm_contact' }], { pkg, priority, fields: {} }); + }; + + it.each([ + ['alpha first', [A, B]], + ['beta first', [B, A]], + ])('equal priority: package name decides (%s)', (_label, order) => { + const reg = withVendor(); + for (const pkg of order) place(reg, pkg, pkg === A ? 'alpha_list' : 'beta_list', 200); + expect(served(reg).relatedLists).toEqual(['crm_contact', 'alpha_list', 'beta_list', 'crm_opportunity']); + }); + + it('lower priority first, whatever the names', () => { + const reg = withVendor(); + place(reg, A, 'alpha_list', 300); + place(reg, B, 'beta_list', 210); + expect(served(reg).relatedLists).toEqual(['crm_contact', 'beta_list', 'alpha_list', 'crm_opportunity']); + }); +}); + +describe('#35901 — uninstalling or disabling the package leaves the owner\'s order as it was', () => { + const placeAll = (reg: SchemaRegistry) => { + reg.registerObject(child('acme_contract', 'Contract') as any, EXT_PKG, undefined, 'own'); + extend(reg, [ + { field: 'tax_id', group: 'basic', after: 'industry' }, + { group: { key: 'tax', label: 'Tax' }, after: 'basic' }, + { list: 'acme_contract', after: 'crm_contact' }, + ]); + }; + + it('uninstall: the items go, the owner\'s groups and tabs are as before', () => { + const before = withVendor(); + const ownerOnly = served(before); + const reg = withVendor(); + placeAll(reg); + expect(served(reg).relatedLists).toContain('acme_contract'); + reg.unregisterObjectsByPackage(EXT_PKG); + const after = served(reg); + expect(after.relatedLists).toEqual(ownerOnly.relatedLists); + expect(after.fieldGroups).toEqual(ownerOnly.fieldGroups); + expect(after.fields.tax_id).toBeUndefined(); + }); + + it('disable: the served object carries none of the placements', () => { + const reg = withVendor(); + reg.installPackage({ id: EXT_PKG, name: EXT_PKG, version: '1.0.0', type: 'app', namespace: 'acme' } as never, 'code'); + placeAll(reg); + reg.disablePackage(EXT_PKG); + const body = served(reg); + expect(body.relatedLists).toEqual(['crm_contact', 'crm_opportunity']); + expect(body.fieldGroups.map((g: any) => g.key)).toEqual(['basic', 'more']); + expect(groupFields(body, 'basic')).toBeUndefined(); + }); + + it('a body that already carries the placements folds to itself', () => { + const reg = withVendor(); + placeAll(reg); + 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); + }); +}); + +describe('#35901 — arm (a): where the object declares no arrangement, it stays, and the log says so', () => { + it('pins the ruled arm', () => { + expect(PLACEMENT_ARRANGES_DECLARED_ONLY).toBe(true); + }); + + it('no relatedLists: no tab list is made, the note names the object, the package and the FK keys', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const account = vendorAccount(); + delete account.relatedLists; + const reg = withVendor(account); + extend(reg, [{ list: 'acme_contract', after: 'crm_opportunity', label: 'Contracts' }]); + expect(served(reg).relatedLists).toBeUndefined(); + const line = warn.mock.calls.map((c) => String(c[0])).find((l) => l.includes("places list 'acme_contract'")); + expect(line).toContain(`object "${OBJ}" from package "${EXT_PKG}"`); + expect(line).toContain('declares no `relatedLists`'); + expect(line).toContain('`relatedListTitle` / `relatedListColumns`'); + }); + + it('no fieldGroups: no group is made, the field keeps its place among the fields, both named', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const account = vendorAccount(); + delete account.fieldGroups; + const reg = withVendor(account); + extend(reg, [{ field: 'tax_id', group: 'basic', after: 'industry' }, { group: { key: 'tax', label: 'Tax' } }]); + const body = served(reg); + expect(body.fieldGroups).toBeUndefined(); + expect(body.fields.tax_id).toEqual(TAX_ID); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('declares no `fieldGroups`')); + expect(lines).toHaveLength(2); + expect(lines.find((l) => l.includes('`tax_id`'))).toContain("after 'industry'"); + }); +}); + +describe('#35901 — an extension places only its own items', () => { + it('a list whose object another package owns is not placed, named', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(vendorAccount({ relatedLists: ['crm_contact'] })); + extend(reg, [{ list: 'crm_opportunity', after: 'crm_contact' }]); + expect(served(reg).relatedLists).toEqual(['crm_contact']); + expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain(`package "${OWNER_PKG}"'s, not a child object this package defines`); + }); + + it('a child not registered (yet) is no verdict: the list is placed', () => { + const reg = withVendor(); + extend(reg, [{ list: 'acme_later', after: 'crm_contact' }]); + expect(served(reg).relatedLists).toEqual(['crm_contact', 'acme_later', 'crm_opportunity']); + }); + + it('a group key the object declares is not added again, and a foreign field is not moved', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + extend(reg, [{ group: { key: 'basic', label: 'Mine' } }, { field: 'industry', group: 'more' }]); + const body = served(reg); + expect(body.fieldGroups).toEqual(vendorAccount().fieldGroups); + expect(body.fields.industry.group).toBe('basic'); + const text = warn.mock.calls.map((c) => String(c[0])).join('\n'); + expect(text).toContain("which is a group \"crm_account\" declares itself"); + expect(text).toContain('`industry` (place[1]), which is not a field this extension adds'); + }); +}); + +describe('#35901 — the manifest loop carries place onto the extension def', () => { + it('a package\'s objectExtensions entry places its field through ObjectQL.registerApp', () => { + const ql = new ObjectQL(); + (ql.registry as SchemaRegistry).logLevel = 'silent'; + ql.registerApp({ id: OWNER_PKG, name: 'CRM', version: '1.0.0', objects: [vendorAccount()] }); + ql.registerApp({ + id: EXT_PKG, + name: 'Contracts', + version: '1.0.0', + objectExtensions: [{ extend: OBJ, fields: { tax_id: TAX_ID }, place: [{ field: 'tax_id', group: 'basic', after: 'industry' }] }], + }); + expect(groupFields(ql.registry.getObject(OBJ), 'basic')).toEqual(['name', 'industry', 'tax_id', 'phone']); + expect((ql.registry as SchemaRegistry).getObjectExtensionsOf(EXT_PKG)[0].place).toEqual([ + { field: 'tax_id', group: 'basic', after: 'industry' }, + ]); + }); +}); + +describe('#35901 — applyExtensionPlacements is pure and returns the object by reference when nothing applies', () => { + it('no placements: same reference, no notes', () => { + const object = vendorAccount(); + const out = applyExtensionPlacements(object, [], { objectName: OBJ, ownerGroupKeys: new Set(), childPackageOf: () => undefined }); + expect(out.object).toBe(object); + expect(out.notes).toEqual([]); + }); +}); diff --git a/packages/objectql/src/registry-extension-placement.ts b/packages/objectql/src/registry-extension-placement.ts new file mode 100644 index 00000000000..49f18309b02 --- /dev/null +++ b/packages/objectql/src/registry-extension-placement.ts @@ -0,0 +1,418 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35901, epic #35896] Where an object extension's own items go: the one + * application of `ObjectExtensionSchema.place`, run by the registry fold + * (`foldExtendersOntoDefinition`) after every contributor's fields are merged, + * so the record page, the forms and Studio read one arrangement. + * + * Three passes, in this order, each over the extensions in ascending + * `priority` and then package id (so two packages at one anchor come out in + * the same order on every build): + * + * 1. groups — a field group the extension adds, spliced into the object's + * `fieldGroups` after / before one of its groups, or last; + * 2. fields — a field the extension adds, spliced into a group's member list + * after / before a member, or last in the group. A group that lists no + * `fields` gets its current members (the fields whose `group` names it, + * in declaration order) written out on the served copy first, so its own + * order does not move; the placed field's `group` is set to the group; + * 3. lists — a child list of the extension's package, spliced into the + * object's `relatedLists` after / before a tab, or at the end of the tabs + * (before a trailing approvals / activity-stream tab). + * + * Several items at one anchor keep reading order: after an anchor they follow + * it lowest priority first; before an anchor they precede it lowest priority + * first. An anchor the object does not have puts the item at the end and is + * named. An item the object (or the base the fold starts from) already + * arranges keeps that position, silently: the owner's position wins, and a + * body that already carries the placements re-folds to itself. + * + * Nothing here drops an item from the object: a placement that does not apply + * leaves the item where the merge put it (the field among the fields, the + * list in the automatic tab order) and is named once. + */ + +import { readFieldGroupMembership, relatedListEntryName } from '@objectstack/spec/data'; +import type { ServiceObject } from '@objectstack/spec/data'; +import type { ObjectContributor } from './registry-top-level.js'; + +/** + * [#35901, Sales ruling 7073014077 on F1 / F2] The ONE switch for what + * placement arranges. `true`: list placements apply only where the extended + * object declares a non-empty `relatedLists`, and group and field placements + * only where it declares a non-empty `fieldGroups`; elsewhere its automatic + * arrangement stays, and each placement is named as not applied. Read only by + * {@link arrangementDeclared}. + */ +export const PLACEMENT_ARRANGES_DECLARED_ONLY = true; + +/** The record-page tabs a trailing run of which an end-placed list goes before. */ +const TRAILING_BUILTIN_TABS: ReadonlySet = new Set(['sys_approval_request', 'sys_activity']); + +/** One extension's placements, as the fold hands them over. */ +export interface PlacementContributor { + readonly packageId: string | undefined; + readonly priority: number; + /** The extension's `place` entries, as registered (un-parsed tolerant read). */ + readonly place: readonly unknown[]; + /** The field names this extension's own `fields` declares. */ + readonly ownFields: ReadonlySet; +} + +/** What the fold knows beyond the object itself. */ +export interface PlacementContext { + /** The extended object's name, for the notes. */ + readonly objectName: string; + /** The group keys the extended object's OWNER declares (the packaged body, not a tenant base). */ + readonly ownerGroupKeys: ReadonlySet; + /** + * The package that owns a registered child object: a package id, `null` + * when it is registered with no package, `undefined` when it is not + * registered (yet). Only a registered child owned by ANOTHER package skips a + * list placement; an absent one is never a verdict, since its package may + * register it later in the same boot. + */ + readonly childPackageOf: (childObject: string) => string | null | undefined; +} + +/** One placement that did not apply as written, named once by the fold. */ +export interface ExtensionPlacementNote { + /** Dedup key: object, package, entry. */ + readonly key: string; + readonly packageId: string | undefined; + readonly message: string; +} + +type AnyRecord = Record; + +/** One ordered item a pass splices into: its name, and the anchor that placed it there. */ +interface Slot { + readonly name: string; + readonly value: T; + readonly placedAfter?: string; +} + +function isRecord(value: unknown): value is AnyRecord { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function stringOrUndefined(value: unknown): string | undefined { + return typeof value === 'string' && value.length > 0 ? value : undefined; +} + +/** + * [#35901] Does the extended object declare the arrangement a placement of + * `kind` arranges? The arm switch {@link PLACEMENT_ARRANGES_DECLARED_ONLY} + * is read here and nowhere else. + */ +export function arrangementDeclared(kind: 'lists' | 'groups', object: unknown): boolean { + if (!PLACEMENT_ARRANGES_DECLARED_ONLY) return true; + const value = isRecord(object) ? object[kind === 'lists' ? 'relatedLists' : 'fieldGroups'] : undefined; + return Array.isArray(value) && value.length > 0; +} + +/** + * Splice `slot` into `slots` after / before its anchor, or at `endIndex()` + * when it names none. Returns false when it names an anchor `slots` does not + * hold (the item then goes to the end). + */ +function splice(slots: Slot[], name: string, value: T, after: string | undefined, before: string | undefined, endIndex: () => number): boolean { + if (after !== undefined) { + const at = slots.findIndex((slot) => slot.name === after); + if (at !== -1) { + let index = at + 1; + while (index < slots.length && slots[index].placedAfter === after) index += 1; + slots.splice(index, 0, { name, value, placedAfter: after }); + return true; + } + } else if (before !== undefined) { + const at = slots.findIndex((slot) => slot.name === before); + if (at !== -1) { + slots.splice(at, 0, { name, value }); + return true; + } + } + slots.splice(endIndex(), 0, { name, value }); + return after === undefined && before === undefined; +} + +/** The extensions in placement order: ascending priority, then package id. */ +function inPlacementOrder(extensions: readonly PlacementContributor[]): PlacementContributor[] { + return extensions + .map((extension, index) => ({ extension, index })) + .sort((a, b) => { + if (a.extension.priority !== b.extension.priority) return a.extension.priority - b.extension.priority; + const pa = a.extension.packageId ?? ''; + const pb = b.extension.packageId ?? ''; + if (pa !== pb) return pa < pb ? -1 : 1; + return a.index - b.index; + }) + .map(({ extension }) => extension); +} + +function anchorOf(entry: AnyRecord): { after?: string; before?: string } { + return { after: stringOrUndefined(entry.after), before: stringOrUndefined(entry.before) }; +} + +function anchorText(after: string | undefined, before: string | undefined): string { + return after !== undefined ? `after '${after}'` : `before '${before}'`; +} + +/** The child object a list name (`child` or `child.field`) names. */ +function childOf(list: string): string { + const dot = list.indexOf('.'); + return dot === -1 ? list : list.slice(0, dot); +} + +/** + * Does the running tab list already arrange `list`? An entry of the same + * name, a bare child entry covering every list of that child, or (for a bare + * child placement) an entry naming one of that child's relationships. + */ +function tabsArrange(names: readonly string[], list: string): boolean { + const child = childOf(list); + const bare = list === child; + return names.some((name) => name === list || name === child || (bare && childOf(name) === child)); +} + +/** + * [#35901] The `extend` contributors that carry placements, in the fold's + * hands: each one's `place` and the names of its own `fields`. + */ +export function placementContributorsOf(contributors: readonly ObjectContributor[]): PlacementContributor[] { + const out: PlacementContributor[] = []; + for (const contributor of contributors) { + if (contributor.ownership !== 'extend') continue; + const body = contributor.definition as unknown as AnyRecord; + if (!Array.isArray(body.place) || body.place.length === 0) continue; + out.push({ + packageId: contributor.packageId, + priority: contributor.priority, + place: body.place, + ownFields: new Set(isRecord(body.fields) ? Object.keys(body.fields) : []), + }); + } + return out; +} + +/** The group keys an object body declares in `fieldGroups` (none for `undefined`). */ +export function fieldGroupKeysOf(object: unknown): ReadonlySet { + const groups = isRecord(object) ? object.fieldGroups : undefined; + const keys = new Set(); + if (Array.isArray(groups)) { + for (const group of groups) { + const key = isRecord(group) ? stringOrUndefined(group.key) : undefined; + if (key !== undefined) keys.add(key); + } + } + return keys; +} + +/** + * [#35901] Apply every extension's `place` to `object` (the fold's merged + * body). Returns the object to serve (by reference when nothing applies) and + * the notes to name. Pure: the caller names the notes, once. + */ +export function applyExtensionPlacements( + object: ServiceObject, + extensions: readonly PlacementContributor[], + context: PlacementContext, +): { object: ServiceObject; notes: ExtensionPlacementNote[] } { + const notes: ExtensionPlacementNote[] = []; + const placing = inPlacementOrder(extensions.filter((extension) => extension.place.length > 0)); + if (placing.length === 0) return { object, notes }; + + const objectName = context.objectName; + const from = (packageId: string | undefined): string => (packageId ? ` from package "${packageId}"` : ''); + const note = (extension: PlacementContributor, entry: number, subject: string, message: string): void => { + const text = `[Registry] An extension of object "${objectName}"${from(extension.packageId)} ${message}`; + notes.push({ key: `${entry}|${subject}|${text}`, packageId: extension.packageId, message: text }); + }; + + const groupsDeclared = arrangementDeclared('groups', object); + const listsDeclared = arrangementDeclared('lists', object); + const record = object as unknown as AnyRecord; + let fields = isRecord(record.fields) ? record.fields : {}; + let fieldsChanged = false; + + // ── 1. groups ─────────────────────────────────────────────────────────── + const groupSlots: Slot[] = (Array.isArray(record.fieldGroups) ? record.fieldGroups : []) + .map((group) => ({ name: isRecord(group) ? stringOrUndefined(group.key) ?? '' : '', value: group })); + const groupAddedBy = new Map(); + let groupsChanged = false; + for (const extension of placing) { + extension.place.forEach((entry, index) => { + if (!isRecord(entry) || !isRecord(entry.group)) return; + const key = stringOrUndefined(entry.group.key); + if (key === undefined) return; + const { after, before } = anchorOf(entry); + if (!groupsDeclared) { + note(extension, index, `group:${key}`, + `places field group '${key}' (place[${index}]), which is not applied: "${objectName}" declares no ` + + '`fieldGroups`, so its fields show ungrouped, in declaration order, and the fields this group lists ' + + 'show among them. It applies once the object declares `fieldGroups`.'); + return; + } + if (context.ownerGroupKeys.has(key)) { + note(extension, index, `group:${key}`, + `adds field group '${key}' (place[${index}]), which is a group "${objectName}" declares itself, so ` + + 'the group is not added. An extension adds groups of its own: give it a key of its own, or place ' + + `its fields into the object's '${key}' with { field, group: '${key}' }.`); + return; + } + if (groupAddedBy.has(key)) { + const other = groupAddedBy.get(key); + note(extension, index, `group:${key}`, + `adds field group '${key}' (place[${index}]), which package "${other ?? '(none)'}" already adds to ` + + 'this object, so the group is not added again. Give it a key of its own.'); + return; + } + // A base that already carries the key (a body that carries these + // placements, or a tenant base) keeps its own position. + if (groupSlots.some((slot) => slot.name === key)) return; + const anchored = splice(groupSlots, key, { ...entry.group }, after, before, () => groupSlots.length); + groupAddedBy.set(key, extension.packageId); + groupsChanged = true; + if (!anchored) { + note(extension, index, `group:${key}`, + `places field group '${key}' ${anchorText(after, before)} (place[${index}]), but "${objectName}" has ` + + 'no such group, so it is placed after the last group.'); + } + }); + } + + // ── 2. fields ─────────────────────────────────────────────────────────── + // Members of each group the pass touches, read once from the running + // groups (so a group's `fields`, then the fields whose `group` names it). + const memberSlots = new Map[]>(); + const groupsNow = (): AnyRecord[] => groupSlots.map((slot) => slot.value).filter(isRecord); + const listedSomewhere = (field: string): boolean => + groupsNow().some((group) => Array.isArray(group.fields) && group.fields.includes(field)); + for (const extension of placing) { + extension.place.forEach((entry, index) => { + if (!isRecord(entry) || typeof entry.field !== 'string') return; + const field = entry.field; + const key = stringOrUndefined(entry.group); + if (key === undefined) return; + const { after, before } = anchorOf(entry); + if (!extension.ownFields.has(field)) { + note(extension, index, `field:${field}`, + `places field \`${field}\` (place[${index}]), which is not a field this extension adds, so it is not ` + + 'moved: a field of the extended object, or of another package\'s extension, is arranged by its owner.'); + return; + } + if (!isRecord(fields[field])) return; + if (!groupsDeclared) { + note(extension, index, `field:${field}`, + `places field \`${field}\` in group '${key}'${after !== undefined || before !== undefined ? ` ${anchorText(after, before)}` : ''} ` + + `(place[${index}]), which is not applied: "${objectName}" declares no \`fieldGroups\`, so the field ` + + 'shows among its fields in declaration order, after the object\'s own. It applies once the object ' + + 'declares `fieldGroups`.'); + return; + } + const group = groupsNow().find((candidate) => candidate.key === key); + if (group === undefined) { + note(extension, index, `field:${field}`, + `places field \`${field}\` in group '${key}' (place[${index}]), but "${objectName}" has no such group, ` + + 'so the field shows among the ungrouped fields.'); + return; + } + if (typeof group.relatedList === 'string' || isRecord(group.relatedList)) { + note(extension, index, `field:${field}`, + `places field \`${field}\` in group '${key}' (place[${index}]), which places a related list and holds ` + + 'no fields, so the field shows among the ungrouped fields.'); + return; + } + // The object (or the base the fold starts from) already lists it: its position wins. + if (listedSomewhere(field)) return; + let slots = memberSlots.get(key); + if (slots === undefined) { + const membership = readFieldGroupMembership({ fields, fieldGroups: groupsNow() }); + slots = (membership.members.get(key) ?? []).map((name) => ({ name, value: name })); + memberSlots.set(key, slots); + } + const at = slots.findIndex((slot) => slot.name === field); + if (at !== -1) slots.splice(at, 1); + const anchored = splice(slots, field, field, after, before, () => slots!.length); + if (fields[field] && (fields[field] as AnyRecord).group !== key) { + fields = { ...fields, [field]: { ...(fields[field] as AnyRecord), group: key } }; + fieldsChanged = true; + } + if (!anchored) { + note(extension, index, `field:${field}`, + `places field \`${field}\` ${anchorText(after, before)} in group '${key}' (place[${index}]), but that ` + + 'group has no such member, so the field is placed last in the group.'); + } + }); + } + if (memberSlots.size > 0) { + for (let index = 0; index < groupSlots.length; index += 1) { + const slot = groupSlots[index]; + const members = memberSlots.get(slot.name); + if (members === undefined || !isRecord(slot.value)) continue; + groupSlots[index] = { ...slot, value: { ...slot.value, fields: members.map((member) => member.name) } }; + } + groupsChanged = true; + } + + // ── 3. lists ──────────────────────────────────────────────────────────── + const tabSlots: Slot[] = (Array.isArray(record.relatedLists) ? record.relatedLists : []) + .map((entry) => ({ name: relatedListEntryName(entry) ?? '', value: entry })); + const tabsEnd = (): number => { + let end = tabSlots.length; + while (end > 0 && TRAILING_BUILTIN_TABS.has(tabSlots[end - 1].name)) end -= 1; + return end; + }; + let tabsChanged = false; + for (const extension of placing) { + extension.place.forEach((entry, index) => { + if (!isRecord(entry) || typeof entry.list !== 'string') return; + const list = entry.list; + const { after, before } = anchorOf(entry); + const label = stringOrUndefined(entry.label); + const columns = Array.isArray(entry.columns) && entry.columns.length > 0 ? entry.columns : undefined; + const owner = context.childPackageOf(childOf(list)); + if (owner !== undefined && (owner ?? undefined) !== extension.packageId) { + note(extension, index, `list:${list}`, + `places list '${list}' (place[${index}]), whose object '${childOf(list)}' is ` + + `${owner === null ? 'registered with no package' : `package "${owner}"'s`}, not a child object this ` + + 'package defines, so it is not placed: the lists of the extended object and of other packages are ' + + 'arranged by their owners.'); + return; + } + if (!listsDeclared) { + note(extension, index, `list:${list}`, + `places list '${list}' (place[${index}]), which is not applied: "${objectName}" declares no ` + + '`relatedLists`, so its tabs keep the automatic order and the list shows there' + + (label !== undefined || columns !== undefined + ? ', and this entry\'s `label` / `columns` are not applied either (write `relatedListTitle` / ' + + '`relatedListColumns` on the child\'s lookup field, which apply on every parent)' + : '') + + '. It applies once the object declares `relatedLists`.'); + return; + } + if (tabsArrange(tabSlots.map((slot) => slot.name), list)) return; + const value = label !== undefined || columns !== undefined + ? { list, ...(label !== undefined ? { label } : {}), ...(columns !== undefined ? { columns: [...columns] } : {}) } + : list; + const anchored = splice(tabSlots, list, value, after, before, tabsEnd); + tabsChanged = true; + // Before a trailing built-in tab the object leaves unlisted is the end + // of the tabs anyway (the approvals and the stream follow every listed + // tab), so that miss is the position asked for and is not named. + if (!anchored && !(before !== undefined && TRAILING_BUILTIN_TABS.has(before))) { + note(extension, index, `list:${list}`, + `places list '${list}' ${anchorText(after, before)} (place[${index}]), but "${objectName}" has no such ` + + 'tab in its `relatedLists`, so the list is placed at the end of the tabs.'); + } + }); + } + + if (!groupsChanged && !tabsChanged && !fieldsChanged) return { object, notes }; + const out = { ...record } as AnyRecord; + if (groupsChanged) out.fieldGroups = groupSlots.map((slot) => slot.value); + if (tabsChanged) out.relatedLists = tabSlots.map((slot) => slot.value); + if (fieldsChanged) out.fields = fields; + return { object: out as unknown as ServiceObject, notes }; +} diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index fa4c14cb923..784828facaf 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -51,6 +51,8 @@ import { QUEUE_FIELD_DEF, applyAuditFieldGovernance, fieldPatchTargetMisses, isC 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 { applyProtection } from '@objectstack/spec/shared'; import { isObjectLessActionKey, standaloneActionOwnerKey } from './action-governance.js'; import { recordCurrencyFollowRefusal, recordCurrencySummaryRefusal } from './record-currency-aggregate-door.js'; @@ -95,6 +97,7 @@ export interface ObjectRegistrationHost { declinedBaseLayerStamps: SchemaRegistry['declinedBaseLayerStamps']; readonly deploymentPlatformGlobalObjects: SchemaRegistry['deploymentPlatformGlobalObjects']; extensionTargetKey: SchemaRegistry['extensionTargetKey']; + readonly extensionPlacementNotesWarned: SchemaRegistry['extensionPlacementNotesWarned']; readonly fieldPatchMissesWarned: SchemaRegistry['fieldPatchMissesWarned']; finishServedObject: SchemaRegistry['finishServedObject']; foldExtenders: SchemaRegistry['foldExtenders']; @@ -123,6 +126,7 @@ export interface ObjectRegistrationHost { refusePicklistItemArrival: SchemaRegistry['refusePicklistItemArrival']; registerNamespace: SchemaRegistry['registerNamespace']; reportChangedRuleCopies: SchemaRegistry['reportChangedRuleCopies']; + reportExtensionPlacements: SchemaRegistry['reportExtensionPlacements']; reportFieldPatchMisses: SchemaRegistry['reportFieldPatchMisses']; reportRedeclaredFields: SchemaRegistry['reportRedeclaredFields']; readonly reportedRuleCopyChanges: SchemaRegistry['reportedRuleCopyChanges']; @@ -861,7 +865,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 @@ -938,6 +942,24 @@ export class ObjectRegistrationFacet { } } this.reportRedeclaredFields(String(merged.name ?? baseDefinition.name ?? ''), contributors, ownFields, folded); + // [#35901] Where each extension's own fields, groups and child lists go: + // applied once, here, after every contributor's fields are merged, so the + // anchors an extension names are the object's as served. + const placing = placementContributorsOf(contributors); + if (placing.length > 0) { + const placed = applyExtensionPlacements(merged, placing, { + objectName: String(merged.name ?? baseDefinition.name ?? ''), + ownerGroupKeys: fieldGroupKeysOf(owner), + childPackageOf: (child) => { + const fqn = this.resolveObjectKey(child); + const childOwner = fqn === undefined ? undefined : this.getObjectOwner(fqn); + if (childOwner === undefined) return undefined; + return childOwner.packageId ?? null; + }, + }); + merged = placed.object; + this.reportExtensionPlacements(placed.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 @@ -1023,6 +1045,14 @@ export class ObjectRegistrationFacet { * reads*). At `warn`: the object is visibly unpatched, and nothing durable * is lost. */ + static reportExtensionPlacements(this: Pick, notes: readonly ExtensionPlacementNote[]): void { + for (const placementNote of notes) { + if (this.extensionPlacementNotesWarned.has(placementNote.key)) continue; + this.extensionPlacementNotesWarned.add(placementNote.key); + console.warn(placementNote.message); + } + } + static reportFieldPatchMisses(this: Pick, misses: readonly FieldPatchTargetMiss[], packageId: string | undefined): void { for (const miss of misses) { const object = miss.object; diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 239c9c0f46d..2069c721cac 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -35,6 +35,7 @@ import { import { resolveTenancyPosture, resolveSearchPinyinEnabled } from '@objectstack/types'; import { postureEnforcesWall } from '@objectstack/spec/security'; import { provisionSearchCompanion } from './search-companion.js'; +import type { ExtensionPlacementNote } from './registry-extension-placement.js'; import { ObjectStackManifest, InstalledPackage, type InstalledPackageSource, customizationBasePackageId, type NamespaceObjectNameClash } from '@objectstack/spec/kernel'; import { applyProtection } from '@objectstack/spec/shared'; // [ADR-0130 D1] The ONE derivation of the key a package is installed under @@ -2986,6 +2987,19 @@ export class SchemaRegistry { */ private fieldPatchMissesWarned = new Set(); + /** + * [#35901] Placement notes already named (a placement not applied, an + * anchor missing, an item that is not the extension's own), keyed by the + * note. Per registry, for the reason {@link shadowedExtensionQueueWarned} + * gives. + */ + private extensionPlacementNotesWarned = new Set(); + + private reportExtensionPlacements(notes: readonly ExtensionPlacementNote[]): void { + // The body lives in `registry-object-registration.ts` (see `ObjectRegistrationHost`). + return ObjectRegistrationFacet.reportExtensionPlacements.call(objectRegistrationHost.of(this), notes); + } + /** * [#28835] Field names already named as declared by more than one * contributor, keyed `object|field|packages` (the packages in fold order). @@ -6117,6 +6131,7 @@ export class SchemaRegistry { declinedBaseLayerStamps: (...a) => registry.declinedBaseLayerStamps(...a), get deploymentPlatformGlobalObjects() { return registry.deploymentPlatformGlobalObjects; }, extensionTargetKey: (...a) => registry.extensionTargetKey(...a), + get extensionPlacementNotesWarned() { return registry.extensionPlacementNotesWarned; }, get fieldPatchMissesWarned() { return registry.fieldPatchMissesWarned; }, finishServedObject: (...a) => registry.finishServedObject(...a), foldExtenders: (...a) => registry.foldExtenders(...a), @@ -6145,6 +6160,7 @@ export class SchemaRegistry { refusePicklistItemArrival: (...a) => registry.refusePicklistItemArrival(...a), registerNamespace: (...a) => registry.registerNamespace(...a), reportChangedRuleCopies: (...a) => registry.reportChangedRuleCopies(...a), + reportExtensionPlacements: (...a) => registry.reportExtensionPlacements(...a), reportFieldPatchMisses: (...a) => registry.reportFieldPatchMisses(...a), reportRedeclaredFields: (...a) => registry.reportRedeclaredFields(...a), get reportedRuleCopyChanges() { return registry.reportedRuleCopyChanges; }, diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index f7d42a0a65b..b557d11c334 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -4786,7 +4786,7 @@ const ObjectSchemaBase = strictObject( * (`ui/packages/app-shell/src/utils/deriveRelatedLists.ts`) and the * synthesized page's tab list (`buildDefaultTabs`). */ - relatedLists: z.array(RelatedListEntrySchema).optional().describe('The record page\'s tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension\'s place entry (an { list, after | before } entry), and an unplaced one shows after the listed tabs; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be { list, label?, columns? } to give that list its own title and child-field columns (wins over the child FK\'s relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child\'s relationships, as relatedListColumns is) is refused.'), + relatedLists: z.array(RelatedListEntrySchema).optional().describe('The record page\'s tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension\'s place entry (an { list, after | before } entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be { list, label?, columns? } to give that list its own title and child-field columns (wins over the child FK\'s relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child\'s relationships, as relatedListColumns is) is refused.'), /** * [ADR-0085] Semantic role: the field that represents the record's LINEAR * lifecycle (an ordered pipeline / stage progression). A string names the @@ -6490,10 +6490,13 @@ function objectExtensionPlaceDescription(): string { '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, the field among the ungrouped ones); the boot log and `os validate` name each placement that ' + - 'did not apply. A child list another package brings shows even when the extended object\'s `relatedLists` ' + - 'does not name it: placed, at its place; unplaced, after the listed tabs. An extension places only its own ' + + '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`, a group key the extended object or another package already ' + 'declares, or a list that is not a child object of its package is refused (here, or at `defineStack` where ' + 'the package\'s objects are known) and skipped by the merge with a warning naming whose item it is. Applied ' + From 326a42d2c1ffedf5d54c7864d4de581024a0ac9f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:52:18 +0000 Subject: [PATCH 3/9] feat(console): a child list another package brings is not hidden by the parent's relatedLists, and Studio shows it with its source Flips the hiding #35923 shipped (Sales ruling 7073014077): an unplaced list whose child belongs to another package than the parent shows at the end of the tabs, before a trailing approvals / stream run; a placed one sits at the entry the server splices in. A child of the parent's own package, or one no package owns, is still the parent's to list. Studio's tab-list editor shows such a list read-only with a from-package badge and previews it where the record page draws it. Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf Co-Authored-By: Claude --- packages/objectql/src/registry.ts | 6 +- ...iveRelatedLists.otherPackage-35901.test.ts | 68 ++++++++++++++++ .../app-shell/src/utils/deriveRelatedLists.ts | 63 ++++++++++++++- ...el.relatedListsOtherPackage-35901.test.tsx | 80 +++++++++++++++++++ .../studio-design/RelatedListsEditor.tsx | 36 +++++++-- .../studio-design/relatedListVocabulary.ts | 12 ++- ui/packages/i18n/src/namespaces/studio/en.ts | 1 + ui/packages/i18n/src/namespaces/studio/zh.ts | 1 + .../__tests__/buildDefaultPageSchema.test.ts | 11 +++ .../src/synth/buildDefaultPageSchema.ts | 14 +++- 10 files changed, 274 insertions(+), 18 deletions(-) create mode 100644 ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.otherPackage-35901.test.ts create mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsOtherPackage-35901.test.tsx diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 2069c721cac..8e971fb04dc 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -216,6 +216,10 @@ export { * tenant authored it — the same D9.2a rule as the scalars. A patch reaches * the owner's own fields only (`ownFields`): one naming any other field, * a field an extension adds included, is skipped here; the fold names it. + * - `place` [#35901] is not read here: the fold applies every extension's + * placements once, after this merge has run for all of them + * (`applyExtensionPlacements`, registry-extension-placement.ts), so an + * anchor names the object as served. * * **Every other top-level prop on `extension` is silently discarded.** * `merged` starts as `{ ...base }` and nothing outside the list above is ever @@ -228,7 +232,7 @@ export { * Declarative authors never reach that silence, though: `ObjectExtensionSchema` * (`packages/spec/src/data/object.zod.ts`) is `.strict()` — its shape is * exactly `extend` / `fields` / `fieldPatches` / `label` / `pluralLabel` / - * `description` / `validations` / `indexes` / `priority`, so an `objectExtensions` entry + * `description` / `validations` / `indexes` / `place` / `priority`, so an `objectExtensions` entry * naming `tenancy`, `permissions`, or any other key outside that list fails * LOUDLY at authoring time with a prescription (#4001; the same rule is * documented at `content/docs/data-modeling/object-extensions.mdx`). This diff --git a/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.otherPackage-35901.test.ts b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.otherPackage-35901.test.ts new file mode 100644 index 00000000000..ca13a8a87ee --- /dev/null +++ b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.otherPackage-35901.test.ts @@ -0,0 +1,68 @@ +/** + * objectstack#35901 — a declared `relatedLists` does not hide a child list + * ANOTHER package brings (Sales ruling 7073014077, flipping the hiding + * objectstack#35897 shipped under ruling 7072511859): the package places it + * with its object extension's `place`, which the server splices into the + * parent's `relatedLists`; an unplaced one is kept after the listed lists, so + * the page draws it at the end of the tabs. A child of the parent's own + * package, or one no package owns, is still the parent's to list. Each row's + * control differs from it by one `_packageId`. + */ +import { describe, it, expect } from 'vitest'; +import { deriveRelatedLists } from '../deriveRelatedLists'; + +const account = { name: 'account', label: 'Account', _packageId: 'com.vendor.crm', fields: { name: { type: 'text' } } }; +const childOf = (name: string, packageId?: string) => ({ + name, + label: name, + ...(packageId !== undefined ? { _packageId: packageId } : {}), + fields: { account_id: { type: 'lookup', reference: 'account' } }, +}); +const contact = childOf('contact', 'com.vendor.crm'); +const opportunity = childOf('opportunity', 'com.vendor.crm'); + +const names = (parent: Record, objects: unknown[], includeHidden = false) => + deriveRelatedLists(parent, objects as never, { includeHidden }).map((r) => r.childObject); + +describe('relatedLists — a child list another package brings (objectstack#35901)', () => { + const declared = { ...account, relatedLists: ['opportunity', 'contact'] }; + + it('an unplaced one is kept, after the listed lists', () => { + expect(names(declared, [account, contact, childOf('contract', 'com.acme.contracts'), opportunity])).toEqual([ + 'opportunity', 'contact', 'contract', + ]); + }); + + it('control: a child of the parent\'s own package is hidden, as objectstack#35897 shipped', () => { + expect(names(declared, [account, contact, childOf('contract', 'com.vendor.crm'), opportunity])).toEqual([ + 'opportunity', 'contact', + ]); + }); + + it('control: a child no package owns (absent or bound to none) is hidden too', () => { + expect(names(declared, [account, contact, childOf('contract'), opportunity])).toEqual(['opportunity', 'contact']); + expect(names(declared, [account, contact, childOf('contract', 'sys_metadata'), opportunity])).toEqual(['opportunity', 'contact']); + }); + + it('a placed one (the server spliced it into relatedLists) sits at its entry', () => { + const placed = { ...account, relatedLists: ['opportunity', 'contract', 'contact'] }; + expect(names(placed, [account, contact, childOf('contract', 'com.acme.contracts'), opportunity])).toEqual([ + 'opportunity', 'contract', 'contact', + ]); + }); + + it('the authoring surface carries its source package, and never flags it unlisted', () => { + const lists = deriveRelatedLists(declared, [account, contact, childOf('contract', 'com.acme.contracts'), opportunity] as never, { includeHidden: true }); + const contract = lists.find((r) => r.childObject === 'contract')!; + expect(contract.fromPackage).toBe('com.acme.contracts'); + expect(contract.isUnlisted).toBeUndefined(); + // The record page asks for no hidden relationships, so no source rides along. + expect(deriveRelatedLists(declared, [account, childOf('contract', 'com.acme.contracts')] as never)[0].fromPackage).toBeUndefined(); + }); + + it('undeclared: every list shows, as before', () => { + expect(names(account, [account, contact, childOf('contract', 'com.acme.contracts'), opportunity])).toEqual([ + 'contact', 'contract', 'opportunity', + ]); + }); +}); diff --git a/ui/packages/app-shell/src/utils/deriveRelatedLists.ts b/ui/packages/app-shell/src/utils/deriveRelatedLists.ts index 15f3a647a91..805b289a557 100644 --- a/ui/packages/app-shell/src/utils/deriveRelatedLists.ts +++ b/ui/packages/app-shell/src/utils/deriveRelatedLists.ts @@ -68,7 +68,12 @@ * `isUnlisted`). A body table (`isPrimary`) is the field groups' to place * and is kept, after the listed ones, with no tab of its own (no * `keepsTab`) unless an entry names it. Undeclared or empty: every list, as - * before. The three built-in tab names (`RECORD_PAGE_BUILTIN_TABS` in + * before. A side list ANOTHER package brings (the child and the parent + * belong to different packages, objectstack#35901) is the exception: the + * declared list does not hide it; that package places it (the server + * splices its `place` into `relatedLists`), and an unplaced one is kept + * after the listed ones, so the page draws it at the end of the tabs. + * 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`). * - An entry's own TITLE and COLUMNS (objectstack#35899): the object form @@ -197,9 +202,19 @@ export interface DerivedRelatedList { * True when the parent DECLARES `relatedLists` and no entry names this side * 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. + * ({@link DeriveRelatedListsOptions.includeHidden}), as `isHidden` is. Never + * on a list another package brings (objectstack#35901): that one shows. */ isUnlisted?: true; + /** + * The package the child object belongs to, when it is another package than + * the parent's (objectstack#35901): a list that package brings, which the + * parent's `relatedLists` does not hide and the package places itself. + * Present only for the authoring surface + * ({@link DeriveRelatedListsOptions.includeHidden}), which shows it read-only + * with its source. + */ + fromPackage?: string; } /** @@ -261,6 +276,34 @@ interface MergedObjectLike { * records can never be read on any record page. */ enable?: { apiEnabled?: boolean }; + /** + * The package that owns the object, as the server serves it (the registry + * stamps its owner's package id; `'sys_metadata'` marks a definition bound + * to no package). Read to tell a child list another package brings + * (objectstack#35901). + */ + _packageId?: unknown; +} + +/** The package an object belongs to, or `undefined` for none (absent, empty, or bound to no package). */ +function packageOf(object: MergedObjectLike | null | undefined): string | undefined { + const id = object?._packageId; + return typeof id === 'string' && id !== '' && id !== NO_PACKAGE ? id : undefined; +} + +/** The `_packageId` the server stamps on a definition bound to no package. */ +const NO_PACKAGE = 'sys_metadata'; + +/** + * objectstack#35901 — does `child` come from another package than `parent`? + * Both must belong to a package, and the two differ. A child of the parent's + * own package, or one no package owns, is not: those stay the parent's to + * list (objectstack#35897). + */ +function isOtherPackageChild(child: MergedObjectLike, parent: MergedObjectLike): boolean { + const childPackage = packageOf(child); + const parentPackage = packageOf(parent); + return childPackage !== undefined && parentPackage !== undefined && childPackage !== parentPackage; } /** @@ -429,7 +472,7 @@ export function deriveRelatedLists( // Working entries carry the FK label and the list's name so we can // disambiguate multi-FK children after the full sweep; both are stripped // from the returned descriptors. - type Working = DerivedRelatedList & { _fkLabel: string; _listLabel: string }; + type Working = DerivedRelatedList & { _fkLabel: string; _listLabel: string; _otherPackage: boolean }; const owned: Working[] = []; const referenced: Working[] = []; @@ -454,6 +497,8 @@ export function deriveRelatedLists( // rather than once per FK. const inheritedSort = inheritedListViewSort(child.list); const childLabel = child.label || child.name; + // objectstack#35901 — a list another package brings is not the parent's to hide. + const otherPackage = isOtherPackageChild(child, objectDef); const childListLabel = (listLabel && listLabel(child as MergedObjectLike & { name: string })) || childLabel; for (const [fieldName, fieldDef] of fieldEntries(child.fields)) { if (!fieldDef) continue; @@ -492,6 +537,8 @@ export function deriveRelatedLists( ...(hidden ? { isHidden: true as const } : {}), _fkLabel: (typeof fieldDef.label === 'string' && fieldDef.label) || fieldName, _listLabel: childListLabel, + _otherPackage: otherPackage, + ...(otherPackage && options?.includeHidden ? { fromPackage: packageOf(child) } : {}), ...(typeof fieldDef.relatedListTitle === 'string' && fieldDef.relatedListTitle ? { title: fieldDef.relatedListTitle } : {}), @@ -537,6 +584,14 @@ export function deriveRelatedLists( if (list.isPrimary) { const { keepsTab: _unlistedTab, ...bodyOnly } = list; all.push(bodyOnly); + } else if (list._otherPackage) { + // objectstack#35901 — a side list another package brings is not + // hidden by the parent's list: that package places it with its object + // extension's `place` (which the server splices into `relatedLists`, + // so a placed one is named above); unplaced, it shows at the end of + // the tabs (`arrangeDeclaredTabs`). Sales ruling 7073014077 flips the + // hiding objectstack#35897 shipped (ruling 7072511859). + all.push(list); } else if (options?.includeHidden) all.push({ ...list, isUnlisted: true }); continue; } @@ -557,7 +612,7 @@ export function deriveRelatedLists( const counts: Record = {}; for (const r of all) counts[r.childObject] = (counts[r.childObject] || 0) + 1; - return all.map(({ _fkLabel, _listLabel, ...rest }) => { + return all.map(({ _fkLabel, _listLabel, _otherPackage, ...rest }) => { if (!rest.title && counts[rest.childObject] > 1) { return { ...rest, title: `${_listLabel} · ${_fkLabel}` }; } diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsOtherPackage-35901.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsOtherPackage-35901.test.tsx new file mode 100644 index 00000000000..c310e77875a --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsOtherPackage-35901.test.tsx @@ -0,0 +1,80 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35901 — the object settings panel shows a child list ANOTHER + * package brings read-only, with its source: it is not one of this object's + * entries (its package places it), so it stays in the unlisted rows with a + * "from " badge, and the preview draws it at the end of the tabs, + * before a trailing activity-stream tab. Control: a child of this object's + * own package carries no badge and the preview leaves it out. + */ + +import '@testing-library/jest-dom/vitest'; +import React from 'react'; +import { describe, it, expect, afterEach } from 'vitest'; +import { render, screen, cleanup, within } from '@testing-library/react'; +import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; +import { ObjectSettingsPanel } from './ObjectSettingsPanel'; + +afterEach(cleanup); + +type Row = Record; + +const account: Row = { name: 'account', label: 'Account', _packageId: 'com.vendor.crm', fields: { name: { type: 'text', label: 'Name' } } }; +const child = (name: string, label: string, packageId: string): Row => ({ + name, + label, + _packageId: packageId, + fields: { account_id: { type: 'lookup', reference: 'account', label: 'Account' } }, +}); + +function store(objects: Row[]): MetadataContextValue { + return { + apps: [], + objects, + dashboards: [], + reports: [], + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: () => [], + getTypeStatus: () => 'ready', + }; +} + +function renderPanel(objects: Row[], draft: Row) { + const value = store(objects); + return render( + + {}} locale="en-US" /> + , + ); +} + +describe('objectstack#35901 — a child list another package brings, in the settings panel', () => { + const draft: Row = { name: 'account', label: 'Account', fields: account.fields, relatedLists: ['contact', 'sys_activity'] }; + + it('shows it unlisted with its source, and previews it at the end of the tabs', () => { + renderPanel([account, child('contact', 'Contact', 'com.vendor.crm'), child('contract', 'Contract', 'com.acme.contracts')], draft); + const row = screen.getByTestId('related-lists-tail-row-contract.account_id'); + expect(within(row).getByTestId('related-lists-from-package')).toHaveTextContent('from com.acme.contracts'); + expect(screen.getByTestId('related-lists-preview-side')).toHaveTextContent('Contact · Contract · Activity · Approvals'); + }); + + it('control: a child of this object\'s own package has no badge and does not show', () => { + renderPanel([account, child('contact', 'Contact', 'com.vendor.crm'), child('contract', 'Contract', 'com.vendor.crm')], draft); + const row = screen.getByTestId('related-lists-tail-row-contract.account_id'); + expect(within(row).queryByTestId('related-lists-from-package')).toBeNull(); + expect(screen.getByTestId('related-lists-preview-side')).not.toHaveTextContent('Contract'); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/RelatedListsEditor.tsx b/ui/packages/app-shell/src/views/studio-design/RelatedListsEditor.tsx index 26f41609d88..80c8f2d5a56 100644 --- a/ui/packages/app-shell/src/views/studio-design/RelatedListsEditor.tsx +++ b/ui/packages/app-shell/src/views/studio-design/RelatedListsEditor.tsx @@ -67,11 +67,22 @@ import { function Badges({ named, locale }: { named: readonly DerivedRelatedList[]; locale?: SupportedLocale }) { const hidden = named.length > 0 && named.every((r) => r.isHidden); const primary = !hidden && named.length > 0 && named.every((r) => r.isPrimary); - if (!hidden && !primary) return null; + // objectstack#35901 — a list another package brings: shown read-only with its source. + const fromPackage = named.find((r) => r.fromPackage !== undefined)?.fromPackage; + if (!hidden && !primary && fromPackage === undefined) return null; return ( - - {hidden ? t('engine.studio.settings.relatedListsHidden', locale) : t('engine.studio.settings.relatedListsPrimary', locale)} - + <> + {(hidden || primary) && ( + + {hidden ? t('engine.studio.settings.relatedListsHidden', locale) : t('engine.studio.settings.relatedListsPrimary', locale)} + + )} + {fromPackage !== undefined && ( + + {tFormat('engine.studio.settings.relatedListsFromPackage', locale, { package: fromPackage })} + + )} + ); } @@ -227,8 +238,14 @@ export function RelatedListsEditor({ }), ]; - // What the record page will draw: its own derivation, over what a write keeps. - const preview = deriveRelatedLists({ ...draft, name, relatedLists: listed }, catalog as never[]); + // What the record page will draw: its own derivation, over what a write keeps + // (with the served object's package, so a list another package brings shows + // as it will, objectstack#35901). + const servedPackage = catalog.find((o) => (o as { name?: unknown }).name === name)?._packageId; + const preview = deriveRelatedLists( + { ...draft, name, relatedLists: listed, ...(servedPackage !== undefined ? { _packageId: servedPackage } : {}) }, + catalog as never[], + ); const body = preview.filter((r) => r.isPrimary); const side = preview.filter((r) => !r.isPrimary); // The tab strip after the overview: the listed tabs in order, then @@ -236,9 +253,13 @@ export function RelatedListsEditor({ // show only when listed and the object enables files. const tabs: string[] = []; const placedSide = new Set(); + // Where the unlisted side lists go (objectstack#35901: before a trailing run + // of listed approvals / stream tabs, as the record page arranges them). + let unlistedAt = 0; for (const entry of listedNames) { if (isRecordPageBuiltinTab(entry)) { if (entry !== 'sys_attachment' || filesOn) tabs.push(builtinLabel(entry)); + if (entry !== 'sys_approval_request' && entry !== 'sys_activity') unlistedAt = tabs.length; continue; } for (const r of side) { @@ -246,8 +267,9 @@ export function RelatedListsEditor({ placedSide.add(r); tabs.push(relationshipLabel(r)); } + unlistedAt = tabs.length; } - for (const r of side) if (!placedSide.has(r)) tabs.push(relationshipLabel(r)); + tabs.splice(unlistedAt, 0, ...side.filter((r) => !placedSide.has(r)).map(relationshipLabel)); if (listedNames.length === 0 && filesOn) tabs.push(builtinLabel('sys_attachment')); for (const tab of ['sys_approval_request', 'sys_activity'] as const) { if (!listedNames.includes(tab)) tabs.push(builtinLabel(tab)); diff --git a/ui/packages/app-shell/src/views/studio-design/relatedListVocabulary.ts b/ui/packages/app-shell/src/views/studio-design/relatedListVocabulary.ts index 4e76a172311..977adb6daf3 100644 --- a/ui/packages/app-shell/src/views/studio-design/relatedListVocabulary.ts +++ b/ui/packages/app-shell/src/views/studio-design/relatedListVocabulary.ts @@ -49,13 +49,16 @@ type ObjectDoc = Record; * the draft adds is an inbound relationship too. */ export function catalogWithDraft(objects: readonly unknown[], name: string, draft: ObjectDoc): ObjectDoc[] { - const own = { ...draft, name }; + const own: ObjectDoc = { ...draft, name }; let replaced = false; const out: ObjectDoc[] = []; for (const o of objects) { if (!o || typeof o !== 'object') continue; if ((o as ObjectDoc).name === name) { - out.push(own); + // objectstack#35901 — the served object's package rides along, so a + // child list another package brings is told apart (`fromPackage`). + const served = (o as ObjectDoc)._packageId; + out.push(own._packageId === undefined && served !== undefined ? { ...own, _packageId: served } : own); replaced = true; } else { out.push(o as ObjectDoc); @@ -69,7 +72,10 @@ export function catalogWithDraft(objects: readonly unknown[], name: string, draf export function inboundRelationships(name: string, catalog: readonly ObjectDoc[]): DerivedRelatedList[] { // The derived order is the order with NO declared entries: the stored // `relatedLists` must not reorder the vocabulary it is judged against. - return deriveRelatedLists({ name }, catalog as never[], { includeHidden: true }); + // objectstack#35901 — the parent's package (as the catalog holds it) tells a + // child list another package brings, which the editor shows with its source. + const packageId = catalog.find((o) => o.name === name)?._packageId; + return deriveRelatedLists({ name, ...(packageId !== undefined ? { _packageId: packageId } : {}) }, catalog as never[], { includeHidden: true }); } /** diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 9a2314c9e6a..6a640babe40 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -2373,6 +2373,7 @@ const STUDIO_EN: Record = { 'engine.studio.settings.relatedListsUnmatched': '“{entry}” names no relationship that points at this object, so the next change to this list leaves it out.', 'engine.studio.settings.relatedListsHidden': 'hidden', 'engine.studio.settings.relatedListsPrimary': 'in body', + 'engine.studio.settings.relatedListsFromPackage': 'from {package} · that package places it; unplaced, it shows at the end of the tabs', 'engine.studio.settings.relatedListsPreview': 'Record page order', 'engine.studio.settings.relatedListsPreviewBody': 'In the body', 'engine.studio.settings.relatedListsPreviewSide': 'Tabs', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 05d4a4743d9..cd288d78f54 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -2158,6 +2158,7 @@ const STUDIO_ZH: Record = { 'engine.studio.settings.relatedListsUnmatched': '“{entry}”不对应任何指向本对象的关系,下次修改此列表时会被去掉。', 'engine.studio.settings.relatedListsHidden': '已隐藏', 'engine.studio.settings.relatedListsPrimary': '正文', + 'engine.studio.settings.relatedListsFromPackage': '来自 {package} · 由该包自己摆放位置;没摆的排在页签末尾', 'engine.studio.settings.relatedListsPreview': '记录页顺序', 'engine.studio.settings.relatedListsPreviewBody': '正文', 'engine.studio.settings.relatedListsPreviewSide': '页签', diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts index 861893ef18b..842eca5293c 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts @@ -1051,4 +1051,15 @@ describe('declared relatedLists arranges the tabs (objectstack#35897)', () => { it('a related tab the host passed but no entry names follows the listed tabs, in the order passed', () => { expect(values(def(['contact']))).toEqual(['details', 'related:contact.account_id', 'related:task.account_id', 'approvals', 'timeline']); }); + + // objectstack#35901 — an unplaced list another package brings sits at the end of the tabs. + it('…and before a trailing run of listed approvals / stream tabs, which close the strip', () => { + expect(values(def(['contact', 'sys_approval_request', 'sys_activity']))).toEqual([ + 'details', 'related:contact.account_id', 'related:task.account_id', 'approvals', 'timeline', + ]); + // Control: a stream listed before a related entry is no trailing run. + expect(values(def(['sys_activity', 'contact']))).toEqual([ + 'details', 'timeline', 'related:contact.account_id', 'related:task.account_id', 'approvals', + ]); + }); }); diff --git a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts index d2865751016..d69a1493ed0 100644 --- a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts +++ b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts @@ -1114,8 +1114,10 @@ const BUILTIN_TAB_VALUES: Readonly> = { * `enable.files`, decided above); * - an unlisted approvals tab follows every listed tab, and an unlisted * stream closes the strip, so leaving either out never hides it; - * - a related tab no entry names (a host that did not filter it) follows - * the listed tabs, in the order passed. + * - a related tab no entry names (a list another package brings and does + * not place, objectstack#35901, or a host that did not filter it) sits at + * the end of the tabs: after the listed tabs, before a trailing run of + * listed approvals / stream tabs, in the order passed. * * Which related lists exist is the host's: `deriveRelatedLists` drops the * unlisted side lists. A pure, stable reorder of the tabs already built. @@ -1125,6 +1127,12 @@ function arrangeDeclaredTabs(declared: readonly unknown[] | undefined, items: an const [overview, ...tabs] = items; const names = declared.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 + // of listed approvals / stream tabs, which close the strip. + let tail = names.length; + while (tail > 0 && (names[tail - 1] === 'sys_approval_request' || names[tail - 1] === 'sys_activity')) tail -= 1; + const unlistedRelated = tail < names.length ? tail - 0.5 : unlisted; const rank = (tab: any): number | null => { const value = typeof tab?.value === 'string' ? tab.value : ''; const builtin = (Object.keys(BUILTIN_TAB_VALUES) as RecordPageBuiltinTab[]) @@ -1140,7 +1148,7 @@ function arrangeDeclaredTabs(declared: readonly unknown[] | undefined, items: an const dot = id.indexOf('.'); const list = { childObject: id.slice(0, dot), referenceField: id.slice(dot + 1) }; const at = names.findIndex((name) => name !== undefined && !isRecordPageBuiltinTab(name) && relatedListEntryNames(name, list)); - return at === -1 ? unlisted : at; + return at === -1 ? unlistedRelated : at; } return unlisted; }; From 0185c0d3b37f03f07402628302fc2b51e39e917e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:03:19 +0000 Subject: [PATCH 4/9] docs(spec): place's migration entry, changeset, ADR-0085 and ADR-0146 D10 notes, and regenerated artifacts The semantic entry object-extension-place-and-cross-package-lists states the flip of #35897's hiding for a child list another package brings; the #35897 entry's later-change clause now points to it. Type aliases for the three placement schemas, so the reference docs import them. Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf Co-Authored-By: Claude --- .changeset/35901-object-extension-place.md | 37 ++++ content/docs/references/api/metadata.mdx | 2 +- content/docs/references/data/object.mdx | 160 +++++++++++++++++- content/docs/references/index.mdx | 10 +- content/docs/references/system/migration.mdx | 4 +- ...semantic-roles-over-surface-hint-blocks.md | 14 ++ ...ditor-per-item-paired-customize-package.md | 14 ++ .../data.md | 10 +- packages/spec/api-surface/data.json | 9 + packages/spec/authorable-surface/data.json | 13 ++ packages/spec/declaration-map/data.json | 8 + packages/spec/export-origins/data.json | 9 + packages/spec/json-schema.manifest/data.json | 4 + packages/spec/src/data/object.zod.ts | 6 + ...extension-place-and-cross-package-lists.ts | 48 ++++++ .../18.related-lists-declared-is-tab-list.ts | 2 +- 16 files changed, 332 insertions(+), 18 deletions(-) create mode 100644 .changeset/35901-object-extension-place.md create mode 100644 packages/spec/src/migrations/entries/semantic/18.object-extension-place-and-cross-package-lists.ts diff --git a/.changeset/35901-object-extension-place.md b/.changeset/35901-object-extension-place.md new file mode 100644 index 00000000000..9c5f33008d8 --- /dev/null +++ b/.changeset/35901-object-extension-place.md @@ -0,0 +1,37 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': minor +'@objectstack/lint': minor +'@object-ui/app-shell': minor +'@object-ui/plugin-detail': minor +'@object-ui/i18n': minor +--- + +feat(spec): an object extension says where the fields, groups and child lists it brings go (`place`), and a child list another package brings is no longer hidden by the parent's `relatedLists` + +Clause-②: yes (widening) +Metadata-protocol: semantic + +An `objectExtensions` entry can now place what it brings on the object it extends: + +```ts +objectExtensions: [{ + extend: 'account', + fields: { tax_id: { type: 'text', label: 'Tax ID' } }, + place: [ + { field: 'tax_id', group: 'basic', after: 'industry' }, + { group: { key: 'tax', label: 'Tax' }, after: 'basic' }, + { list: 'contract', after: 'opportunity', label: 'Contracts', columns: ['name', 'amount'] }, + ], +}], +``` + +- **No `place`: nothing moves.** Fields still arrive after the object's own, and an extension that writes no `place` serves exactly what it served before. +- **One merge, every reader.** The registry fold applies the placements once, after every contributor's fields are merged, so the record page, the forms and Studio show one arrangement. Uninstalling or disabling the package takes its items off and leaves the object's own order as it was. +- **Placement arranges what the parent declares.** A list placement applies when the extended object declares `relatedLists`; a group or field placement when it declares `fieldGroups`. On a parent that declares neither, its automatic arrangement stays and nothing is dropped: the list shows in the automatic tab order, and its entry's `label` / `columns` are not applied either (write `relatedListTitle` / `relatedListColumns` on your child object's lookup field to title it on every parent); the field shows among the fields, its `after` / `before` not applied. The boot log names each placement that did not apply, with the object and the package. It is the main channel: `os validate` names it too (`extension-placement-not-applied`, warning) only when the extended object is in the same stack. +- **Anchors and order.** `after` or `before`, not both; neither means the end. An anchor the object does not have puts the item at the end of its group, of the groups, or of the tabs (before a trailing approvals / activity-stream run), and `os validate` warns (`extension-placement-anchor-missing`). Several packages at one anchor follow ascending `priority`, then package name, so every build gives the same order. When the object itself already names the list or lists the field, its own position wins. +- **An extension places only its own items.** A field outside its own `fields`, a group key the extended object already declares, or a list that is not a child object of its package pointing at the extended object is refused at parse or at `defineStack`, and skipped by the merge with a warning naming whose item it is. The extension keys `fieldGroups` and `relatedLists` are refused with a prescription naming `place`. +- **Shipped behaviour change (flips #35897's hiding):** a child list another package brings is no longer hidden by the parent's declared `relatedLists`. Placed, it sits where its package puts it; unplaced, it shows at the end of the tabs. "Another package" means the child and the parent both belong to a package and the two differ; a child of the parent's own package, or one no package owns, is still hidden until an entry names it. This narrows the #35897 note "A child list another package adds is hidden too until the parent names it … letting a package place its own list is a later change": that change is this one. +- **Studio** (object settings, Record page tabs) shows such a list read-only among the unlisted rows with a "from " badge, and the preview draws it where the record page does. + +What to check in an app: on an object that declares `relatedLists`, every installed package's child lists of it now show, at the end of the tabs unless placed; name one in the parent's `relatedLists` to put it elsewhere, or set `relatedList: false` on that package's FK to hide it. To use `place` on HotCRM's objects, the parent object first declares its `relatedLists` (follow-up #35902). ADR-0087 semantic entry `object-extension-place-and-cross-package-lists`; ADR-0146 D10 and ADR-0085 notes. diff --git a/content/docs/references/api/metadata.mdx b/content/docs/references/api/metadata.mdx index a14aa3feba7..f4ffb39f848 100644 --- a/content/docs/references/api/metadata.mdx +++ b/content/docs/references/api/metadata.mdx @@ -963,7 +963,7 @@ Metadata query with filtering, sorting, and pagination | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | -| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | +| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index ca2cc3ea134..54bb35a10a9 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 15 more — each property with its type, default and a TypeScript example." +description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOperation, Index and 19 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, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RelatedListEntrySchema, RelatedListEntryObjectSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; -import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, 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, 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'; // Validate data const result = ApiMethod.parse(data); @@ -175,7 +175,7 @@ const result = ApiMethod.parse(data); | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | -| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | +| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | @@ -614,6 +614,7 @@ const result = ApiMethod.parse(data); | **description** | `string` | optional | Override description for the extended object | | **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. Write `after` or `before`, or neither for the end. An anchor that does not exist 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`, a group key the extended object or another package already declares, or a list that is not a child object of its package is refused (here, or at `defineStack` where the package's objects are known) and skipped by the merge with a warning naming whose item it is. 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'] }]`. | | **priority** | `integer` | optional (default: `200`) | Merge priority (higher = applied later) | ### Nested Shape: `ObjectExtension.fields[string]` @@ -723,6 +724,157 @@ const result = ApiMethod.parse(data); | **fields** | `string[]` | ✅ | Fields included in the index | | **unique** | `false \| 'global' \| 'organization'` | optional (default: `false`) | Whether the index enforces uniqueness, and at which scope (ADR-0120). 'global' = materialized over exactly `fields`, no organization column injected — one holder across the whole installation; 'organization' = the driver prepends the NULL-safe organization key part (COALESCE(organization_id, '__global__')) at registration — one holder per organization; false/omitted = not unique. Bare true is refused (retired at protocol 18 — it was the positional spelling of 'global'): state the scope. 'tenant'/'org' are rejected — the word is 'organization' | +### Nested Shape: `ObjectExtension.place[number][option 1]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | A field this extension adds: a key of its own `fields`. An extension places only what it brings. | +| **group** | `string` | ✅ | The field group it joins: a group key of the extended object, or of a group this extension adds. | +| **after** | `string` | optional | Place it right after this member of the group (any field of the group, whoever declares it). | +| **before** | `string` | optional | Place it right before this member of the group. Write `after` or `before`, not both. | + +### Nested Shape: `ObjectExtension.place[number][option 2]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The child list this package brings: a child object of this package that points at the extended object, or object.field. | +| **after** | `string` | optional | Place it right after this tab: a relatedLists entry name of the extended object (a child object, object.field, or a built-in tab). | +| **before** | `string` | optional | Place it right before this tab. Write `after` or `before`, not both. | +| **label** | `string` | optional | This list's title on the record page, as a relatedLists entry's label. | +| **columns** | `string[]` | optional | This list's columns, as field names of the child object, as a relatedLists entry's columns. | + +### Nested Shape: `ObjectExtension.place[number][option 3]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **group** | `{ key: string; label: string; fields?: string[]; icon?: string; … }` | ✅ | The field group this extension adds (key, label, and optionally fields or relatedList). | +| **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. | + + +--- + +## ObjectExtensionFieldPlacement + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | A field this extension adds: a key of its own `fields`. An extension places only what it brings. | +| **group** | `string` | ✅ | The field group it joins: a group key of the extended object, or of a group this extension adds. | +| **after** | `string` | optional | Place it right after this member of the group (any field of the group, whoever declares it). | +| **before** | `string` | optional | Place it right before this member of the group. Write `after` or `before`, not both. | + + +--- + +## ObjectExtensionGroupPlacement + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **group** | `{ key: string; label: string; fields?: string[]; icon?: string; … }` | ✅ | The field group this extension adds (key, label, and optionally fields or relatedList). | +| **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: `ObjectExtensionGroupPlacement.group` + +| 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. | + + +--- + +## ObjectExtensionListPlacement + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The child list this package brings: a child object of this package that points at the extended object, or object.field. | +| **after** | `string` | optional | Place it right after this tab: a relatedLists entry name of the extended object (a child object, object.field, or a built-in tab). | +| **before** | `string` | optional | Place it right before this tab. Write `after` or `before`, not both. | +| **label** | `string` | optional | This list's title on the record page, as a relatedLists entry's label. | +| **columns** | `string[]` | optional | This list's columns, as field names of the child object, as a relatedLists entry's columns. | + + +--- + +## ObjectExtensionPlacement + +### Union Options + +This schema accepts one of the following structures: + +#### Option 1 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | A field this extension adds: a key of its own `fields`. An extension places only what it brings. | +| **group** | `string` | ✅ | The field group it joins: a group key of the extended object, or of a group this extension adds. | +| **after** | `string` | optional | Place it right after this member of the group (any field of the group, whoever declares it). | +| **before** | `string` | optional | Place it right before this member of the group. Write `after` or `before`, not both. | + +--- + +#### Option 2 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The child list this package brings: a child object of this package that points at the extended object, or object.field. | +| **after** | `string` | optional | Place it right after this tab: a relatedLists entry name of the extended object (a child object, object.field, or a built-in tab). | +| **before** | `string` | optional | Place it right before this tab. Write `after` or `before`, not both. | +| **label** | `string` | optional | This list's title on the record page, as a relatedLists entry's label. | +| **columns** | `string[]` | optional | This list's columns, as field names of the child object, as a relatedLists entry's columns. | + +--- + +#### Option 3 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **group** | `{ key: string; label: string; fields?: string[]; icon?: string; … }` | ✅ | The field group this extension adds (key, label, and optionally fields or relatedList). | +| **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: `ObjectExtensionPlacement[option 3].group` + +| 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. | + +--- + --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 9e4d718f8e7..61375a5ebcd 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 — 1703 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1707 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 | 521 | 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 | 191 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 195 | 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 | 297 | 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** | **1703** | 14 protocol modules | +| **Total** | **219** | **1707** | 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, 191 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 195 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`, `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`, `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/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index f617abfe6f0..3827a1a5a5f 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -355,7 +355,7 @@ Create a new object | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | -| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | +| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | @@ -658,7 +658,7 @@ Create a new object | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | -| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | +| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused 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. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | diff --git a/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md b/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md index 523faa5e21d..c825dc5a2e5 100644 --- a/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md +++ b/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md @@ -104,6 +104,20 @@ Keys that merely hide/re-arrange correct information (`hideRelatedTab`, `showRef > stack. Letting an extension package place its own list is the epic's child card > [#35901](https://github.com/objectstack-ai/objectstack/issues/35901). +> **Note (2026-11-22, [#35901](https://github.com/objectstack-ai/objectstack/issues/35901), epic +> [#35896](https://github.com/objectstack-ai/objectstack/issues/35896)).** The previous note's last +> sentence is superseded. An extension package now says where the fields, groups and child lists it +> brings go (`ObjectExtensionSchema.place`, applied once by the registry fold, ADR-0146 D10's note of +> the same date), and a child list another package brings is **not** hidden by the parent's declared +> `relatedLists`: placed, it sits where its package puts it; unplaced, it shows at the end of the +> tabs (the maintainer: 「装了就自动排在末尾」, ruling 7073014077, flipping ruling 7072511859). The +> parent's tab list still decides everything the parent's own package and package-less metadata +> bring. Placement arranges what the parent declares (「父对象声明了才生效」): a group or field placement +> applies only where the parent declares `fieldGroups`, so §5's derivation is unchanged: an +> extension's group lands among the declared groups (after or before one of them, or last) and a +> field it places lands inside a group's member list, never above the parent's own fields on a +> parent that declares no groups. + ### 3. Deletions (all evidenced zero-author) - **`detail` block removed from `ObjectSchema`** — all three typed keys. `renderViaSchema` retires *together with* the legacy monolith renderer path in objectui (separate execution PR; the key is only that path's steering wheel, deleting it alone saves nothing). `hideReferenceRail`/`hideRelatedTab` are removed outright (the former is a proven no-op for spec authors; the latter's raison d'être — overriding rail/tab dedup — died with the rail). diff --git a/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md b/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md index a028fd27aaa..444da310d59 100644 --- a/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md +++ b/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md @@ -630,6 +630,20 @@ rules added: Studio's "add field" on a base object ([D3](#d3)'s one surface) writes exactly this: an extension in `.custom`, the name suffixed, the base untouched (N-23c). +> **Note (2026-11-22, [#35901](https://github.com/objectstack-ai/objectstack/issues/35901)).** A third rule rides on +> the extension: **it places only what it brings.** `ObjectExtensionSchema.place` puts a field of the extension's own +> `fields` into a group of the extended object after or before a member, a group of the extension's own after or before +> one of the object's groups, and a child list of the extension's own package after or before one of the object's tabs. +> A field of the base (or of another package's extension), a group key the base declares, and another package's list +> are refused at parse or at `defineStack` and skipped by the merge with a warning: the base's arrangement stays the +> base's, as its fields beyond the whitelist do. The placements are applied once, by the registry fold +> (`packages/objectql/src/registry-extension-placement.ts#applyExtensionPlacements`, after every contributor's fields are +> merged), so the record page, the forms and Studio read one arrangement, and uninstalling or disabling the package +> leaves the base's order as it was. They arrange only what the base declares (ruling 7073014077: a list placement +> where it declares `relatedLists`, a group or field placement where it declares `fieldGroups`); elsewhere the base's +> automatic arrangement stays and the boot log names the placement. Studio shows such an item read-only with its +> source package, as it shows a contributed item ([D3](#d3)). + ### D11 — Migration, then closure: package-less overlay rows become declared overrides, the package-less write closes, and the stopgaps retire {#d11} - **Migrate** (N-16, Q5). Every `sys_metadata` row with `package_id` NULL that overlays an item a code package ships 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 f6854312c89..2219905351d 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/` | 180 | 111 | 2 | 0 | 67 | +| `data/` | 183 | 114 | 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` | 27 | +| `object.zod.ts` | 30 | | `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** | **180** | +| **total** | **183** | ## `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 180**, in 11 file(s). +**67 strip of 183**, 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** | **180** | +| **total** | **67** | **183** | | Bucket | Sites | |---|---| diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 27b78134a76..f472cfe5d52 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -593,7 +593,16 @@ "ObjectDependencyNodeParsed (type)", "ObjectDependencyNodeSchema (const)", "ObjectExtension (type)", + "ObjectExtensionFieldPlacement (type)", + "ObjectExtensionFieldPlacementSchema (const)", + "ObjectExtensionGroupPlacement (type)", + "ObjectExtensionGroupPlacementSchema (const)", + "ObjectExtensionListPlacement (type)", + "ObjectExtensionListPlacementSchema (const)", "ObjectExtensionParsed (type)", + "ObjectExtensionPlacement (type)", + "ObjectExtensionPlacementParsed (type)", + "ObjectExtensionPlacementSchema (const)", "ObjectExtensionSchema (const)", "ObjectExternalBinding (type)", "ObjectExternalBindingParsed (type)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 7d98d9e3d75..b6baa09f6dc 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -740,9 +740,22 @@ "data/ObjectExtension:fields", "data/ObjectExtension:indexes", "data/ObjectExtension:label", + "data/ObjectExtension:place", "data/ObjectExtension:pluralLabel", "data/ObjectExtension:priority", "data/ObjectExtension:validations", + "data/ObjectExtensionFieldPlacement:after", + "data/ObjectExtensionFieldPlacement:before", + "data/ObjectExtensionFieldPlacement:field", + "data/ObjectExtensionFieldPlacement:group", + "data/ObjectExtensionGroupPlacement:after", + "data/ObjectExtensionGroupPlacement:before", + "data/ObjectExtensionGroupPlacement:group", + "data/ObjectExtensionListPlacement:after", + "data/ObjectExtensionListPlacement:before", + "data/ObjectExtensionListPlacement:columns", + "data/ObjectExtensionListPlacement:label", + "data/ObjectExtensionListPlacement: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 9c4f0511641..0fe438a6de8 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -227,6 +227,14 @@ "ObjectDependencyNode": "data/ObjectDependencyNode", "ObjectDependencyNodeSchema": "data/ObjectDependencyNode", "ObjectExtension": "data/ObjectExtension", + "ObjectExtensionFieldPlacement": "data/ObjectExtensionFieldPlacement", + "ObjectExtensionFieldPlacementSchema": "data/ObjectExtensionFieldPlacement", + "ObjectExtensionGroupPlacement": "data/ObjectExtensionGroupPlacement", + "ObjectExtensionGroupPlacementSchema": "data/ObjectExtensionGroupPlacement", + "ObjectExtensionListPlacement": "data/ObjectExtensionListPlacement", + "ObjectExtensionListPlacementSchema": "data/ObjectExtensionListPlacement", + "ObjectExtensionPlacement": "data/ObjectExtensionPlacement", + "ObjectExtensionPlacementSchema": "data/ObjectExtensionPlacement", "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 14d47f34402..2da6513a89d 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -582,7 +582,16 @@ "ObjectDependencyNodeParsed": "src/data/seed-loader.zod.ts#ObjectDependencyNodeParsed (type)", "ObjectDependencyNodeSchema": "src/data/seed-loader.zod.ts#ObjectDependencyNodeSchema (const)", "ObjectExtension": "src/data/object.zod.ts#ObjectExtension (type)", + "ObjectExtensionFieldPlacement": "src/data/object.zod.ts#ObjectExtensionFieldPlacement (type)", + "ObjectExtensionFieldPlacementSchema": "src/data/object.zod.ts#ObjectExtensionFieldPlacementSchema (const)", + "ObjectExtensionGroupPlacement": "src/data/object.zod.ts#ObjectExtensionGroupPlacement (type)", + "ObjectExtensionGroupPlacementSchema": "src/data/object.zod.ts#ObjectExtensionGroupPlacementSchema (const)", + "ObjectExtensionListPlacement": "src/data/object.zod.ts#ObjectExtensionListPlacement (type)", + "ObjectExtensionListPlacementSchema": "src/data/object.zod.ts#ObjectExtensionListPlacementSchema (const)", "ObjectExtensionParsed": "src/data/object.zod.ts#ObjectExtensionParsed (type)", + "ObjectExtensionPlacement": "src/data/object.zod.ts#ObjectExtensionPlacement (type)", + "ObjectExtensionPlacementParsed": "src/data/object.zod.ts#ObjectExtensionPlacementParsed (type)", + "ObjectExtensionPlacementSchema": "src/data/object.zod.ts#ObjectExtensionPlacementSchema (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)", diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index 6076e84d9df..d565e88684f 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -123,6 +123,10 @@ "data/ObjectDependencyGraph", "data/ObjectDependencyNode", "data/ObjectExtension", + "data/ObjectExtensionFieldPlacement", + "data/ObjectExtensionGroupPlacement", + "data/ObjectExtensionListPlacement", + "data/ObjectExtensionPlacement", "data/ObjectExternalBinding", "data/ObjectFieldGroup", "data/ObjectOwnershipEnum", diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index b557d11c334..aa92f4279fe 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -6458,6 +6458,12 @@ export const ObjectExtensionPlacementSchema = lazySchema(() => z.union([ ObjectExtensionListPlacementSchema, ObjectExtensionGroupPlacementSchema, ])); +/** A field placement as an author writes it. */ +export type ObjectExtensionFieldPlacement = z.input; +/** A group placement as an author writes it. */ +export type ObjectExtensionGroupPlacement = z.input; +/** A list placement as an author writes it. */ +export type ObjectExtensionListPlacement = z.input; /** One `place` entry as an author writes it. */ export type ObjectExtensionPlacement = z.input; /** One `place` entry after parse. */ diff --git a/packages/spec/src/migrations/entries/semantic/18.object-extension-place-and-cross-package-lists.ts b/packages/spec/src/migrations/entries/semantic/18.object-extension-place-and-cross-package-lists.ts new file mode 100644 index 00000000000..13383a333e1 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.object-extension-place-and-cross-package-lists.ts @@ -0,0 +1,48 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #35901 (epic #35896) — an object extension says where the fields, groups and +// child lists it brings go (`place`), applied once by the registry merge; and +// a child list another package brings is no longer hidden by the parent's +// declared `relatedLists` (Sales ruling 7073014077 on #35901, flipping the +// hiding #35897 shipped under ruling 7072511859). Semantic only, with no D2 +// conversion: where each extension's items should go is not recorded +// anywhere, and the visibility flip needs no rewrite. +export const entry: SemanticMigration = { + id: 'object-extension-place-and-cross-package-lists', + surface: + 'objectExtensions[].place (data.ObjectExtensionSchema.place), new; and objects[].relatedLists ' + + '(data.ObjectSchema.relatedLists) when DECLARED and non-empty on an object another package adds a ' + + 'child list to', + replacement: + 'an extension package that wants its fields, groups or child lists at a set position writes ' + + "place: [{ field, group, after | before }, { group: { key, label, ... }, after | before }, " + + "{ list, after | before, label?, columns? }] on its objectExtensions entry. A parent that wants another " + + "package's child list at a set position names it in its own relatedLists (its position wins); there is " + + 'no way for the parent to hide it, short of relatedList: false on that package\'s FK', + reason: + 'The maintainer asked that an extension package declare where the fields, groups and child lists it ' + + 'brings go (「排在谁后面」) and that what it brings appear there by itself; with no place written ' + + 'nothing moves (「没写就照旧」). Placement arranges what the extended object declares (ruled 「父对象声明了才生效」): ' + + 'a list placement applies when the parent declares relatedLists, a group or field placement when it ' + + "declares fieldGroups; on a parent that declares neither, the automatic arrangement stays, the entry's " + + 'label / columns and a field\'s after / before are not applied, and the boot log names each such ' + + 'placement (os validate too when the parent is in the same stack). An anchor the parent does not have ' + + 'puts the item at the end; several packages at one anchor order by priority, then package name. An ' + + 'extension places only its own items. SHIPPED BEHAVIOUR CHANGE: under #35897 a declared non-empty ' + + 'relatedLists hid a side list no entry named, a child list another package adds included, until the ' + + "parent named it. Now such a list (child and parent belong to different packages) is not hidden: placed, " + + 'it sits where its package puts it; unplaced, it shows at the end of the tabs (「装了就自动排在末尾」), ' + + 'before a trailing approvals / activity-stream run. A child of the parent\'s own package, or one no ' + + 'package owns, is still hidden until named. A STORED object row is not rewritten: its record page ' + + 'changes at the next read. In-repo census before the change: no example, platform object, dogfood ' + + 'fixture or HotCRM object declared relatedLists, and no objectExtensions entry wrote place; deployed ' + + 'metadata was NOT measured. ADR-0146 D10 / ADR-0085', + acceptanceCriteria: + 'On the record page of an object that declares relatedLists, a child list another installed package ' + + 'brings shows: at the position its extension\'s place names, or at the end of the tabs when it names ' + + 'none; on an object that declares fieldGroups, a field an extension places shows in the named group ' + + 'right after (before) the named member; an object that declares neither, and an extension that writes ' + + 'no place, shows the same as before.', +}; diff --git a/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts b/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts index 90b80d359e6..0c29c17c3a7 100644 --- a/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts +++ b/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts @@ -27,7 +27,7 @@ export const entry: SemanticMigration = { + 'approvals and stream tabs always closed the strip in a fixed order. Now, on a declared non-empty ' + 'relatedLists, a side list no entry names shows no tab, a child list another package adds included: ' + 'it is hidden until the parent names it, which a build accepts only when that package is in the ' - + 'parent\'s stack (letting a package place its own list is a later change); the attachments tab shows only when ' + + 'parent\'s stack (since #35901 such a list is no longer hidden: see object-extension-place-and-cross-package-lists); the attachments tab shows only when ' + "'sys_attachment' is listed (and the object enables files, as before); the approvals tab, when " + 'unlisted, follows the listed tabs and still shows whenever the record has requests; the stream ' + 'tab, when unlisted, still closes the strip. Body tables a field group places stay at their group; ' From a1ae9d6877a5a44d6f95fc4a7c411d13e0594608 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:06:10 +0000 Subject: [PATCH 5/9] docs: the object-extensions guide documents place, and its example is pinned to parse Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf Co-Authored-By: Claude --- .../docs/data-modeling/object-extensions.mdx | 59 ++++++++++++++++++- .../src/data/object-extension-place.test.ts | 15 +++++ 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/content/docs/data-modeling/object-extensions.mdx b/content/docs/data-modeling/object-extensions.mdx index 89393726e8c..e1adda52726 100644 --- a/content/docs/data-modeling/object-extensions.mdx +++ b/content/docs/data-modeling/object-extensions.mdx @@ -69,6 +69,7 @@ check that spelling first. | `label` | Replaces the target's label — with one exception, [below](#extensions-and-tenant-customization). A new `label` with no `pluralLabel` beside it also takes the target's plural off, since that plural names the old label: the object is served as one that declares no plural, and lists title it by its label. Set `pluralLabel` too to serve one. A plural the tenant set stays. | | `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). | | `priority` | Not merged — it *orders* the merge. `0`–`999`, default `200`. | Added fields are ordinary fields, so everything on the @@ -77,7 +78,7 @@ Added fields are ordinary fields, so everything on the ### What an extension may **not** contribute -The merge carries the eight keys above and nothing else. These four are not +The merge carries the nine keys above and nothing else. These five 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: @@ -86,13 +87,67 @@ each one by name with the alternative to use 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` | Add the fields here and declare the groups on the owning object, or assign a Page for the layout | +| `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 | 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. --- +## Placing what you bring + +Without `place`, the fields you add arrive after the target's own, and a child list of +yours shows wherever the record page's automatic order puts it. `place` names the item +each one goes next to: + +```ts +objectExtensions: [{ + extend: 'crm_account', + fields: { tax_id: { type: 'text', label: 'Tax ID' } }, + place: [ + { field: 'tax_id', group: 'basic', after: 'industry' }, + { group: { key: 'tax', label: 'Tax' }, after: 'basic' }, + { list: 'acme_contract', after: 'crm_opportunity', label: 'Contracts', columns: ['name', 'amount'] }, + ], +}], +``` + +- **`{ field, group, after | before }`** puts a field of *your* `fields` into a group of the + target (or one you add), right after or before a member of that group. +- **`{ group: { key, label, … }, after | before }`** adds a field group of your own, right + after or before one of the target's groups. Its `fields` may name only fields you add. +- **`{ list, after | before, label?, columns? }`** puts a child list of your own package (a + child object of your package with a lookup to the target, or `object.field`) right after + or before one of the target's tabs, with that tab's own title and columns. + +Write `after` or `before`, not both; neither means the end. An anchor the target does not +have puts the item at the end of its group, of the groups, or of the tabs (before the +approvals and activity-stream tabs). Several packages at one anchor follow ascending +`priority`, then package name. When the target's owner already names your list or lists +your field, the owner's position wins. + +**Placement arranges what the target declares.** A list placement applies when the target +declares `relatedLists`; a group or field placement when it declares `fieldGroups`. On a +target that declares neither, its automatic arrangement stays and nothing is dropped: your +list shows in the automatic tab order (and the entry's `label` / `columns` are not applied +either, so write `relatedListTitle` / `relatedListColumns` on your child object's lookup +field to title the list on every parent), and your field shows among the fields, its +`after` / `before` not applied. The boot log names each placement that did not apply, with +the object and your package; `os validate` names it too when the target is in the same +stack. + +A child list your package brings is shown even when the target's `relatedLists` does not +name it: placed, where you put it; unplaced, at the end of the tabs. + +**You place only what you bring.** A field of the target or of another package, a group +key the target already declares, or a list that is not a child object of your package is +refused at authoring time, and skipped by the merge with a warning naming whose item it +is. Uninstalling or disabling your package takes its items off and leaves the target's own +order as it was. + +--- + ## Relabelling a vendor field Replacing a field through `fields` takes it over whole: its type, its options and its diff --git a/packages/spec/src/data/object-extension-place.test.ts b/packages/spec/src/data/object-extension-place.test.ts index e9d13d3153e..b2804e9137e 100644 --- a/packages/spec/src/data/object-extension-place.test.ts +++ b/packages/spec/src/data/object-extension-place.test.ts @@ -115,6 +115,21 @@ describe('ObjectExtensionSchema.place — an extension places only what it bring }); }); +describe('ObjectExtensionSchema.place — the guide\'s example', () => { + it('control: `content/docs/data-modeling/object-extensions.mdx`, "Placing what you bring", parses whole', () => { + const parsed = ObjectExtensionSchema.safeParse({ + extend: 'crm_account', + fields: { tax_id: { type: 'text', label: 'Tax ID' } }, + place: [ + { field: 'tax_id', group: 'basic', after: 'industry' }, + { group: { key: 'tax', label: 'Tax' }, after: 'basic' }, + { list: 'acme_contract', after: 'crm_opportunity', label: 'Contracts', columns: ['name', 'amount'] }, + ], + }); + expect(parsed.success).toBe(true); + }); +}); + describe('ObjectExtensionSchema — the owner\'s arrangement keys point to place', () => { it.each([ ['fieldGroups', [{ key: 'tax', label: 'Tax' }]], From 33961ec5d513022019a76ac4b675a90156a84838 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:18:52 +0000 Subject: [PATCH 6/9] fix(spec): the placement aliases follow ADR-0122 The field and list placement schemas have one shape, so they are pinned isomorphic; the group placement nests ObjectFieldGroupSchema, which has a parsed shape, so it gains ObjectExtensionGroupPlacementParsed. api-surface and export-origins regenerated. Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf Co-Authored-By: Claude --- packages/spec/api-surface/data.json | 1 + packages/spec/export-origins/data.json | 1 + packages/spec/src/data/object.zod.ts | 2 ++ .../spec/src/type-alias-convention.pin.test.ts | 16 +++++++++++++--- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index f472cfe5d52..1d3ea53d301 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -596,6 +596,7 @@ "ObjectExtensionFieldPlacement (type)", "ObjectExtensionFieldPlacementSchema (const)", "ObjectExtensionGroupPlacement (type)", + "ObjectExtensionGroupPlacementParsed (type)", "ObjectExtensionGroupPlacementSchema (const)", "ObjectExtensionListPlacement (type)", "ObjectExtensionListPlacementSchema (const)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 2da6513a89d..27eba52bc46 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -585,6 +585,7 @@ "ObjectExtensionFieldPlacement": "src/data/object.zod.ts#ObjectExtensionFieldPlacement (type)", "ObjectExtensionFieldPlacementSchema": "src/data/object.zod.ts#ObjectExtensionFieldPlacementSchema (const)", "ObjectExtensionGroupPlacement": "src/data/object.zod.ts#ObjectExtensionGroupPlacement (type)", + "ObjectExtensionGroupPlacementParsed": "src/data/object.zod.ts#ObjectExtensionGroupPlacementParsed (type)", "ObjectExtensionGroupPlacementSchema": "src/data/object.zod.ts#ObjectExtensionGroupPlacementSchema (const)", "ObjectExtensionListPlacement": "src/data/object.zod.ts#ObjectExtensionListPlacement (type)", "ObjectExtensionListPlacementSchema": "src/data/object.zod.ts#ObjectExtensionListPlacementSchema (const)", diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index aa92f4279fe..c5448583069 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -6462,6 +6462,8 @@ export const ObjectExtensionPlacementSchema = lazySchema(() => z.union([ export type ObjectExtensionFieldPlacement = z.input; /** A group placement as an author writes it. */ export type ObjectExtensionGroupPlacement = z.input; +/** A group placement after parse (its group carries `ObjectFieldGroupSchema`'s parsed shape). */ +export type ObjectExtensionGroupPlacementParsed = z.infer; /** A list placement as an author writes it. */ export type ObjectExtensionListPlacement = z.input; /** One `place` entry as an author writes it. */ diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 7d7924d5ce4..3802b31db0f 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -306,7 +306,7 @@ import type * as M205 from './ai/object-query-source.zod.js'; import type * as M207 from './api/ai-answer.zod.js'; // --------------------------------------------------------------------------- -// 886 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 888 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -998,6 +998,8 @@ export type Iso_data_mapping__TransformType = Assert, z.infer< typeof M70.ApiMethod > >>; export type Iso_data_object__LifecycleClassSchema = Assert, z.infer< typeof M70.LifecycleClassSchema > >>; export type Iso_data_object__LifecycleSchema = Assert, z.infer< typeof M70.LifecycleSchema > >>; +export type Iso_data_object__ObjectExtensionFieldPlacementSchema = Assert, z.infer< typeof M70.ObjectExtensionFieldPlacementSchema > >>; +export type Iso_data_object__ObjectExtensionListPlacementSchema = Assert, z.infer< typeof M70.ObjectExtensionListPlacementSchema > >>; export type Iso_data_object__ObjectOwnershipEnum = Assert, z.infer< typeof M70.ObjectOwnershipEnum > >>; export type Iso_data_object__ObjectRequiredPermissionsSchema = Assert, z.infer< typeof M70.ObjectRequiredPermissionsSchema > >>; export type Iso_data_object__PerOperationRequiredPermissionsSchema = Assert, z.infer< typeof M70.PerOperationRequiredPermissionsSchema > >>; @@ -1865,7 +1867,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 886 isomorphic pins', () => { + it('still declares all 888 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2977,7 +2979,15 @@ describe('ADR-0122 type-alias convention', () => { // `AiConversationMessageSchema` (`api/protocol.zod.ts`), `AiMessageSchema` // plus an optional string (Iso_api_protocol__AiConversationMessageSchema). // +23 added. - expect(pins).toHaveLength(886); + // 886 -> 888 is #35901: an object extension's field and list placements, + // `ObjectExtensionFieldPlacementSchema` and + // `ObjectExtensionListPlacementSchema` (`data/object.zod.ts`), closed + // objects of strings and a string array with no default or transform + // (Iso_data_object__ObjectExtensionFieldPlacementSchema, + // Iso_data_object__ObjectExtensionListPlacementSchema). +2 added. Their + // group sibling nests `ObjectFieldGroupSchema`, which has a parsed shape, + // so it takes `ObjectExtensionGroupPlacementParsed` instead. + expect(pins).toHaveLength(888); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either From ce3ab59e98de9d671e866ee5158a3548c83898e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:51:08 +0000 Subject: [PATCH 7/9] fix(spec): the two semantic entries' printed guidance names entries, not tracker ids `os migrate meta` prints a semantic entry's reason verbatim, and its pin refuses a tracker id there. The new entry and the clause it narrows in related-lists-declared-is-tab-list now point at each other by entry id. Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf Co-Authored-By: Claude --- .../18.object-extension-place-and-cross-package-lists.ts | 2 +- .../entries/semantic/18.related-lists-declared-is-tab-list.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/spec/src/migrations/entries/semantic/18.object-extension-place-and-cross-package-lists.ts b/packages/spec/src/migrations/entries/semantic/18.object-extension-place-and-cross-package-lists.ts index 13383a333e1..af164009e14 100644 --- a/packages/spec/src/migrations/entries/semantic/18.object-extension-place-and-cross-package-lists.ts +++ b/packages/spec/src/migrations/entries/semantic/18.object-extension-place-and-cross-package-lists.ts @@ -30,7 +30,7 @@ export const entry: SemanticMigration = { + 'label / columns and a field\'s after / before are not applied, and the boot log names each such ' + 'placement (os validate too when the parent is in the same stack). An anchor the parent does not have ' + 'puts the item at the end; several packages at one anchor order by priority, then package name. An ' - + 'extension places only its own items. SHIPPED BEHAVIOUR CHANGE: under #35897 a declared non-empty ' + + 'extension places only its own items. SHIPPED BEHAVIOUR CHANGE: under related-lists-declared-is-tab-list a declared non-empty ' + 'relatedLists hid a side list no entry named, a child list another package adds included, until the ' + "parent named it. Now such a list (child and parent belong to different packages) is not hidden: placed, " + 'it sits where its package puts it; unplaced, it shows at the end of the tabs (「装了就自动排在末尾」), ' diff --git a/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts b/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts index 0c29c17c3a7..173a8374f30 100644 --- a/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts +++ b/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts @@ -27,7 +27,7 @@ export const entry: SemanticMigration = { + 'approvals and stream tabs always closed the strip in a fixed order. Now, on a declared non-empty ' + 'relatedLists, a side list no entry names shows no tab, a child list another package adds included: ' + 'it is hidden until the parent names it, which a build accepts only when that package is in the ' - + 'parent\'s stack (since #35901 such a list is no longer hidden: see object-extension-place-and-cross-package-lists); the attachments tab shows only when ' + + 'parent\'s stack (no longer hidden since object-extension-place-and-cross-package-lists); the attachments tab shows only when ' + "'sys_attachment' is listed (and the object enables files, as before); the approvals tab, when " + 'unlisted, follows the listed tabs and still shows whenever the record has requests; the stream ' + 'tab, when unlisted, still closes the strip. Body tables a field group places stay at their group; ' From c151007b05b847091183ad8ee4d18d69c182a317 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:39:03 +0000 Subject: [PATCH 8/9] fix(objectql,spec,lint): an extension places only its own items at every door, and anchors resolve in any order Review round 1 on the placement change: - The merge judges a placed group's relatedList as it judges a list placement, skipping it on a foreign owner, and drops from a placed group's fields any name the extension does not own: a manifest body reaches the registry unparsed and the stored object_extension door runs no defineStack. - A field is owned by where it comes from: an owner field an extension redeclares for its display, or a field an earlier extension declares, is not the extension's to place (skipped in the merge, refused by defineStack where the extended object is in the stack). - Each pass places in rounds, so an anchor another placement brings is found whatever the order, as os validate already assumed. - A list placement's columns are judged by validateRelatedListRefs as a relatedLists entry's are. - Prose: the place describe, the #35897 entry's history sentence, the ADR-0085 and ADR-0146 notes, the guide and the changeset's HotCRM line. Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf Co-Authored-By: Claude --- .changeset/35901-object-extension-place.md | 6 +- .../docs/data-modeling/object-extensions.mdx | 14 +- content/docs/references/data/object.mdx | 2 +- ...semantic-roles-over-surface-hint-blocks.md | 4 +- ...ditor-per-item-paired-customize-package.md | 7 +- packages/lint/src/index.ts | 3 +- packages/lint/src/rule-explanations.ts | 2 + .../src/validate-related-list-refs.test.ts | 30 +++ .../lint/src/validate-related-list-refs.ts | 98 +++++++--- .../src/registry-extension-placement.test.ts | 123 ++++++++++++ .../src/registry-extension-placement.ts | 182 ++++++++++++++---- .../src/registry-object-registration.ts | 2 +- packages/spec/src/data/object.zod.ts | 16 +- .../18.related-lists-declared-is-tab-list.ts | 7 +- .../spec/src/stack-extension-place.test.ts | 29 ++- packages/spec/src/stack.zod.ts | 18 ++ 16 files changed, 453 insertions(+), 90 deletions(-) diff --git a/.changeset/35901-object-extension-place.md b/.changeset/35901-object-extension-place.md index 9c5f33008d8..c3a864bad87 100644 --- a/.changeset/35901-object-extension-place.md +++ b/.changeset/35901-object-extension-place.md @@ -29,9 +29,9 @@ objectExtensions: [{ - **No `place`: nothing moves.** Fields still arrive after the object's own, and an extension that writes no `place` serves exactly what it served before. - **One merge, every reader.** The registry fold applies the placements once, after every contributor's fields are merged, so the record page, the forms and Studio show one arrangement. Uninstalling or disabling the package takes its items off and leaves the object's own order as it was. - **Placement arranges what the parent declares.** A list placement applies when the extended object declares `relatedLists`; a group or field placement when it declares `fieldGroups`. On a parent that declares neither, its automatic arrangement stays and nothing is dropped: the list shows in the automatic tab order, and its entry's `label` / `columns` are not applied either (write `relatedListTitle` / `relatedListColumns` on your child object's lookup field to title it on every parent); the field shows among the fields, its `after` / `before` not applied. The boot log names each placement that did not apply, with the object and the package. It is the main channel: `os validate` names it too (`extension-placement-not-applied`, warning) only when the extended object is in the same stack. -- **Anchors and order.** `after` or `before`, not both; neither means the end. An anchor the object does not have puts the item at the end of its group, of the groups, or of the tabs (before a trailing approvals / activity-stream run), and `os validate` warns (`extension-placement-anchor-missing`). Several packages at one anchor follow ascending `priority`, then package name, so every build gives the same order. When the object itself already names the list or lists the field, its own position wins. -- **An extension places only its own items.** A field outside its own `fields`, a group key the extended object already declares, or a list that is not a child object of its package pointing at the extended object is refused at parse or at `defineStack`, and skipped by the merge with a warning naming whose item it is. The extension keys `fieldGroups` and `relatedLists` are refused with a prescription naming `place`. +- **Anchors and order.** `after` or `before`, not both; neither means 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 a trailing approvals / activity-stream run), and `os validate` warns (`extension-placement-anchor-missing`). A list placement's `columns` are fields of the child, checked by `os validate` as a `relatedLists` entry's are (`related-list-column-unknown`). Several packages at one anchor follow ascending `priority`, then package name, so every build gives the same order. When the object itself already names the list or lists the field, its own position wins. +- **An extension places only its own items.** A field outside its own `fields`, a field the extended object declares (also one the extension redeclares to relabel it), a group key the extended object already declares, or a list (placed as a tab or by a group's `relatedList`) that is not a child object of its package pointing at the extended object is refused at parse or at `defineStack`, and skipped by the merge with a warning naming whose item it is, whichever door registered the extension. The extension keys `fieldGroups` and `relatedLists` are refused with a prescription naming `place`. - **Shipped behaviour change (flips #35897's hiding):** a child list another package brings is no longer hidden by the parent's declared `relatedLists`. Placed, it sits where its package puts it; unplaced, it shows at the end of the tabs. "Another package" means the child and the parent both belong to a package and the two differ; a child of the parent's own package, or one no package owns, is still hidden until an entry names it. This narrows the #35897 note "A child list another package adds is hidden too until the parent names it … letting a package place its own list is a later change": that change is this one. - **Studio** (object settings, Record page tabs) shows such a list read-only among the unlisted rows with a "from " badge, and the preview draws it where the record page does. -What to check in an app: on an object that declares `relatedLists`, every installed package's child lists of it now show, at the end of the tabs unless placed; name one in the parent's `relatedLists` to put it elsewhere, or set `relatedList: false` on that package's FK to hide it. To use `place` on HotCRM's objects, the parent object first declares its `relatedLists` (follow-up #35902). ADR-0087 semantic entry `object-extension-place-and-cross-package-lists`; ADR-0146 D10 and ADR-0085 notes. +What to check in an app: on an object that declares `relatedLists`, every installed package's child lists of it now show, at the end of the tabs unless placed; name one in the parent's `relatedLists` to put it elsewhere, or set `relatedList: false` on that package's FK to hide it. Nothing in HotCRM changes meaning today: no module writes `place`, and no object declares `relatedLists`. Most HotCRM objects already declare `fieldGroups`, so a field or group placement there applies as soon as a module writes one; a list placement waits until the parent declares its `relatedLists` (follow-up #35902). ADR-0087 semantic entry `object-extension-place-and-cross-package-lists`; ADR-0146 D10 and ADR-0085 notes. diff --git a/content/docs/data-modeling/object-extensions.mdx b/content/docs/data-modeling/object-extensions.mdx index e1adda52726..f4959d49b12 100644 --- a/content/docs/data-modeling/object-extensions.mdx +++ b/content/docs/data-modeling/object-extensions.mdx @@ -119,10 +119,12 @@ objectExtensions: [{ after or before one of the target's groups. Its `fields` may name only fields you add. - **`{ list, after | before, label?, columns? }`** puts a child list of your own package (a child object of your package with a lookup to the target, or `object.field`) right after - or before one of the target's tabs, with that tab's own title and columns. + or before one of the target's tabs, with that tab's own title and columns (each column a + field of the child, checked by `os validate` as a `relatedLists` entry's columns are). -Write `after` or `before`, not both; neither means the end. An anchor the target does not -have puts the item at the end of its group, of the groups, or of the tabs (before the +Write `after` or `before`, not both; neither means the end. An anchor may be an item +another placement brings, in whatever order the two are written or installed. 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). Several packages at one anchor follow ascending `priority`, then package name. When the target's owner already names your list or lists your field, the owner's position wins. @@ -140,9 +142,9 @@ stack. A child list your package brings is shown even when the target's `relatedLists` does not name it: placed, where you put it; unplaced, at the end of the tabs. -**You place only what you bring.** A field of the target or of another package, a group -key the target already declares, or a list that is not a child object of your package is -refused at authoring time, and skipped by the merge with a warning naming whose item it +**You place only what you bring.** A field of the target or of another package (also one +you redeclare to relabel it), a group key the target already declares, or a list (or a +group placing one) that is not a child object of your package is refused at authoring time, and skipped by the merge with a warning naming whose item it is. Uninstalling or disabling your package takes its items off and leaves the target's own order as it was. diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 54bb35a10a9..f695bda288c 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -614,7 +614,7 @@ const result = ApiMethod.parse(data); | **description** | `string` | optional | Override description for the extended object | | **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. Write `after` or `before`, or neither for the end. An anchor that does not exist 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`, a group key the extended object or another package already declares, or a list that is not a child object of its package is refused (here, or at `defineStack` where the package's objects are known) and skipped by the merge with a warning naming whose item it is. 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'] }]`. | +| **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'] }]`. | | **priority** | `integer` | optional (default: `200`) | Merge priority (higher = applied later) | ### Nested Shape: `ObjectExtension.fields[string]` diff --git a/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md b/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md index c825dc5a2e5..85ae5477a87 100644 --- a/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md +++ b/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md @@ -112,7 +112,9 @@ Keys that merely hide/re-arrange correct information (`hideRelatedTab`, `showRef > `relatedLists`: placed, it sits where its package puts it; unplaced, it shows at the end of the > tabs (the maintainer: 「装了就自动排在末尾」, ruling 7073014077, flipping ruling 7072511859). The > parent's tab list still decides everything the parent's own package and package-less metadata -> bring. Placement arranges what the parent declares (「父对象声明了才生效」): a group or field placement +> bring. The ruling's consequence, for the approver: the parent cannot hide another package's list. +> It can move it by naming it in its own `relatedLists`; only `relatedList: false` on that package's +> FK hides it, and that FK is the other package's to set. Placement arranges what the parent declares (「父对象声明了才生效」): a group or field placement > applies only where the parent declares `fieldGroups`, so §5's derivation is unchanged: an > extension's group lands among the declared groups (after or before one of them, or last) and a > field it places lands inside a group's member list, never above the parent's own fields on a diff --git a/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md b/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md index 444da310d59..0893b5d1307 100644 --- a/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md +++ b/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md @@ -635,8 +635,11 @@ name suffixed, the base untouched (N-23c). > `fields` into a group of the extended object after or before a member, a group of the extension's own after or before > one of the object's groups, and a child list of the extension's own package after or before one of the object's tabs. > A field of the base (or of another package's extension), a group key the base declares, and another package's list -> are refused at parse or at `defineStack` and skipped by the merge with a warning: the base's arrangement stays the -> base's, as its fields beyond the whitelist do. The placements are applied once, by the registry fold +> (placed as a tab or by a group's `relatedList`) are refused at parse or at `defineStack` and skipped by the merge with +> a warning: the base's arrangement stays the base's, as its fields beyond the whitelist do. A field is the extension's +> by where it comes from, not by its presence in the extension's `fields`: a base field the extension redeclares for its +> display (admitted above) is still the base's, and the extension cannot place it. The merge judges every door, the +> stored `object_extension` row and an unparsed manifest body included. The placements are applied once, by the registry fold > (`packages/objectql/src/registry-extension-placement.ts#applyExtensionPlacements`, after every contributor's fields are > merged), so the record page, the forms and Studio read one arrangement, and uninstalling or disabling the package > leaves the base's order as it was. They arrange only what the base declares (ruling 7073014077: a list placement diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 6be2d24111f..32c16c416d2 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -662,7 +662,8 @@ export type { // which runs no `defineStack`. [#27478] A field group's `relatedList` must // name body tables only (`related-list-group-not-body`). [#35897 · #35899] A // `relatedLists` object entry's columns must be child fields -// (`related-list-column-unknown`, error); a built-in tab entry that draws +// (`related-list-column-unknown`, error), and since #35901 an object +// extension's list placement's columns too; a built-in tab entry that draws // nothing warns (`related-list-attachments-off`, `related-list-stream-part`). export { validateRelatedListRefs, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index cd66abd6d23..664ef492ccf 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -4757,6 +4757,8 @@ const RELATED_LIST_COLUMN_UNKNOWN_EXPLANATION: RuleExplanation = { '`os validate`, `os build` and at the runtime publish gate. Judged against every child the entry ' + 'names whose fields this rule can see (the authored fields and the registry-injected columns); a ' + 'child outside the stack is not judged here.', + 'An object extension\'s list placement (`place: [{ list, columns }]`) carries its columns the same way, ' + + 'and they are judged the same way, against the child the placement names.', ], }; diff --git a/packages/lint/src/validate-related-list-refs.test.ts b/packages/lint/src/validate-related-list-refs.test.ts index c244491786b..83dbfbea58a 100644 --- a/packages/lint/src/validate-related-list-refs.test.ts +++ b/packages/lint/src/validate-related-list-refs.test.ts @@ -206,3 +206,33 @@ describe('validateRelatedListRefs — built-in tabs and an entry\'s columns', () expect(findings(stackOf(lead({ relatedLists: [{ list: 'rlo_elsewhere', columns: ['nope'] }] })))).toEqual([]); }); }); + +describe('[#35901] an object extension\'s list placement: its columns are judged as a relatedLists entry\'s are (L2 S4)', () => { + const findings = (stack: Record) => + validateRelatedListRefs(stack).map((f) => [f.severity, f.rule, f.path]); + const placing = (place: unknown[], at: 'top' | 'package' = 'top') => { + const ext = { extend: 'rlo_lead', place }; + return at === 'top' + ? stackOf(lead(), { objectExtensions: [ext] }) + : stackOf(lead(), { packages: [{ manifest: { objectExtensions: [ext] } }] }); + }; + + it('a child field, an injected column and a resolving path are the control', () => { + expect(findings(placing([{ list: 'rlo_task', columns: ['lead_id', 'created_at', 'lead_id.name'] }]))).toEqual([]); + }); + + it('refuses a column that is no field of the child, at the placement, at the top level and in a package body', () => { + expect(findings(placing([{ list: 'rlo_task', after: 'rlo_event', columns: ['lead_id', 'nope'] }]))).toEqual([ + ['error', RELATED_LIST_COLUMN_UNKNOWN, 'objectExtensions[0].place[0].columns[1]'], + ]); + expect(findings(placing([{ list: 'rlo_task.lead_id', columns: ['lead_id.nope'] }], 'package'))).toEqual([ + ['error', RELATED_LIST_COLUMN_UNKNOWN, 'packages[0].manifest.objectExtensions[0].place[0].columns[0]'], + ]); + const [finding] = validateRelatedListRefs(placing([{ list: 'rlo_task', columns: ['nope'] }])); + expect(finding.message).toContain("Object extension of 'rlo_lead' place[0].columns[0] 'nope' is not a field of 'rlo_task'"); + }); + + it('leaves a child outside the stack unjudged, as an entry\'s', () => { + expect(findings(placing([{ list: 'rlo_elsewhere', columns: ['nope'] }]))).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-related-list-refs.ts b/packages/lint/src/validate-related-list-refs.ts index 46abcf29992..dbeb3f576a1 100644 --- a/packages/lint/src/validate-related-list-refs.ts +++ b/packages/lint/src/validate-related-list-refs.ts @@ -89,6 +89,10 @@ * (`resolveFieldPath`, relationship hops from the child), so a column the * FK's `relatedListColumns` accepts is accepted here too; a path the graph * cannot answer is left unjudged, as there. + * - [#35901] An object extension's list placement (`place: [{ list, + * columns }]`, at the top level and in each package body) carries its + * columns as an entry does; they are judged the same way, against the + * child the placement names. */ import { @@ -203,6 +207,43 @@ export function validateRelatedListRefs(stack: AnyRec, options?: RelatedListRefO injectedByObject.set(obj.name, injectedColumnsFor(obj)); } + /** + * [#35899] A list entry's own `columns`, judged against the child whose rows + * the list shows (a `relatedLists` object entry, and since #35901 an object + * extension's list placement): each must be a field of the child, an + * injected column, or a relationship path from it that resolves. + */ + const judgeColumns = (child: string, columns: readonly unknown[], name: string, subject: string, where: string, path: string): void => { + const fields = fieldsByObject.get(child); + if (!fields) return; + const injected = injectedByObject.get(child) ?? new Set(); + columns.forEach((column, c) => { + if (typeof column !== 'string' || fields.has(column) || injected.has(column)) return; + let message = + `${subject}.columns[${c}] '${column}' is not a field of '${child}', ` + + `the child whose rows the list '${name}' shows, so the column would draw empty.`; + if (column.includes('.')) { + // A relationship path from the child, judged as `relatedListColumns` judges one. + graph ??= indexServedObjectGraph(stack); + const verdict = resolveFieldPath(graph, child, column); + if (!verdict || isUnjudgeable(verdict)) return; + const account = describeFieldPathVerdict(verdict, column, `${subject}.columns[${c}]`); + if (!account) return; // the path resolves + message = `${account.message} The path is walked from '${child}', the child whose rows the list '${name}' shows, so the column would draw empty.`; + } + findings.push({ + severity: 'error', + rule: RELATED_LIST_COLUMN_UNKNOWN, + where, + path: `${path}.columns[${c}]`, + message, + hint: + `Name a field of '${child}' (a related-list column is a field of the child object), ` + + 'or drop the entry\'s columns and let them derive.', + }); + }); + }; + // Parent name → its inbound relationships, in child then field order. const inbound = new Map(); for (const [child, fields] of fieldsByObject) { @@ -294,34 +335,7 @@ export function validateRelatedListRefs(stack: AnyRec, options?: RelatedListRefO // [#35899] The entry's own columns: fields of every child it names whose fields are known. const children = [...new Set(namedBy(name).map((r) => r.child))]; for (const child of children) { - const fields = fieldsByObject.get(child); - if (!fields) continue; - const injected = injectedByObject.get(child) ?? new Set(); - entry.columns.forEach((column, c) => { - if (typeof column !== 'string' || fields.has(column) || injected.has(column)) return; - let message = - `Object '${parentName}' relatedLists[${i}].columns[${c}] '${column}' is not a field of '${child}', ` + - `the child whose rows the list '${name}' shows, so the column would draw empty.`; - if (column.includes('.')) { - // A relationship path from the child, judged as `relatedListColumns` judges one. - graph ??= indexServedObjectGraph(stack); - const verdict = resolveFieldPath(graph, child, column); - if (!verdict || isUnjudgeable(verdict)) return; - const account = describeFieldPathVerdict(verdict, column, `Object '${parentName}' relatedLists[${i}].columns[${c}]`); - if (!account) return; // the path resolves - message = `${account.message} The path is walked from '${child}', the child whose rows the list '${name}' shows, so the column would draw empty.`; - } - findings.push({ - severity: 'error', - rule: RELATED_LIST_COLUMN_UNKNOWN, - where: `object "${parentName}" › relatedLists`, - path: `${path}.columns[${c}]`, - message, - hint: - `Name a field of '${child}' (a related-list column is a field of the child object), ` + - 'or drop the entry\'s columns and let them derive.', - }); - }); + judgeColumns(child, entry.columns, name, `Object '${parentName}' relatedLists[${i}]`, `object "${parentName}" › relatedLists`, path); } }); } @@ -345,5 +359,33 @@ export function validateRelatedListRefs(stack: AnyRec, options?: RelatedListRefO }); } } + + // [#35901] An object extension's list placement carries `columns` as a + // `relatedLists` entry does, and they are judged the same way, against the + // child the placement names (its package's own, so in view where the + // extension is authored). The top level and each package body. + const extensionBodies: Array<[string, unknown]> = [ + ['', stack.objectExtensions], + ...(Array.isArray(stack.packages) + ? stack.packages.map((entry, i): [string, unknown] => [ + `packages[${i}].manifest.`, + isRec(entry) && isRec(entry.manifest) ? entry.manifest.objectExtensions : undefined, + ]) + : []), + ]; + for (const [at, extensions] of extensionBodies) { + if (!Array.isArray(extensions)) continue; + extensions.forEach((ext, j) => { + if (!isRec(ext) || typeof ext.extend !== 'string' || !Array.isArray(ext.place)) return; + const target = ext.extend; + ext.place.forEach((entry, k) => { + if (!isRec(entry) || typeof entry.list !== 'string' || !Array.isArray(entry.columns)) return; + const list = entry.list; + const child = list.includes('.') ? list.slice(0, list.indexOf('.')) : list; + const path = `${at}objectExtensions[${j}].place[${k}]`; + judgeColumns(child, entry.columns, list, `Object extension of '${target}' place[${k}]`, `object extension of "${target}" › place`, path); + }); + }); + } return findings; } diff --git a/packages/objectql/src/registry-extension-placement.test.ts b/packages/objectql/src/registry-extension-placement.test.ts index 4bc79b1af36..9b63c240605 100644 --- a/packages/objectql/src/registry-extension-placement.test.ts +++ b/packages/objectql/src/registry-extension-placement.test.ts @@ -17,6 +17,7 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import { SchemaRegistry } from './registry.js'; import { ObjectQL } from './engine.js'; import { PLACEMENT_ARRANGES_DECLARED_ONLY, applyExtensionPlacements } from './registry-extension-placement.js'; +import { ObjectExtensionSchema } from '@objectstack/spec/data'; const OWNER_PKG = 'com.vendor.crm'; const EXT_PKG = 'com.acme.contracts'; @@ -283,6 +284,40 @@ describe('#35901 — an extension places only its own items', () => { expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain(`package "${OWNER_PKG}"'s, not a child object this package defines`); }); + it('a group placing a list whose object another package owns is not added, named; the owner\'s tab stays', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + extend(reg, [{ group: { key: 'deals', label: 'Deals', relatedList: 'crm_opportunity' }, after: 'basic' }]); + const body = served(reg); + expect(body.fieldGroups).toEqual(vendorAccount().fieldGroups); + expect(body.relatedLists).toEqual(['crm_contact', 'crm_opportunity']); + expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain( + `adds field group 'deals' (place[0]) placing list 'crm_opportunity', whose object 'crm_opportunity' is package "${OWNER_PKG}"'s`, + ); + }); + + it('a group placing its own package\'s list, or a list not registered (yet), is added (control)', () => { + const reg = withVendor(); + reg.registerObject(child('acme_contract', 'Contract') as any, EXT_PKG, undefined, 'own'); + extend(reg, [ + { group: { key: 'contracts', label: 'Contracts', relatedList: 'acme_contract' }, after: 'basic' }, + { group: { key: 'later', label: 'Later', relatedList: 'acme_later' }, after: 'contracts' }, + ]); + expect(served(reg).fieldGroups.map((g: any) => g.key)).toEqual(['basic', 'contracts', 'later', 'more']); + }); + + it('a group listing a field the extension does not add takes only its own, named; the owner\'s field stays', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + extend(reg, [{ group: { key: 'tax', label: 'Tax', fields: ['tax_id', 'industry'] }, after: 'basic' }]); + const body = served(reg); + expect(groupFields(body, 'tax')).toEqual(['tax_id']); + expect(body.fields.industry.group).toBe('basic'); + expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain( + "adds field group 'tax' (place[0]) listing `industry`, which this extension does not add", + ); + }); + it('a child not registered (yet) is no verdict: the list is placed', () => { const reg = withVendor(); extend(reg, [{ list: 'acme_later', after: 'crm_contact' }]); @@ -302,6 +337,94 @@ describe('#35901 — an extension places only its own items', () => { }); }); +describe('#35901 — a field is owned by where it comes from, not by its presence in a body (L2 S2)', () => { + it('an owner field the extension redeclares for its display is not moved by its placement, named', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + extend(reg, [{ field: 'industry', group: 'basic', after: 'phone' }], { + fields: { tax_id: TAX_ID, industry: { name: 'industry', type: 'text', label: 'Sector', group: 'basic' } }, + }); + const body = served(reg); + expect(groupFields(body, 'basic')).toBeUndefined(); + expect(body.fieldGroups).toEqual(vendorAccount().fieldGroups); + expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain( + '`industry` (place[0]), which is not a field this extension adds', + ); + }); + + it('a field two extensions declare is the one folded first\'s: the later one cannot place it', () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const region = { name: 'region', type: 'text', label: 'Region' }; + const reg = withVendor(); + extend(reg, [], { pkg: 'com.acme.first', priority: 100, fields: { region } }); + extend(reg, [{ field: 'region', group: 'basic', after: 'name' }], { pkg: 'com.acme.second', priority: 200, fields: { region } }); + expect(groupFields(served(reg), 'basic')).toBeUndefined(); + expect(served(reg).fields.region.group).toBeUndefined(); + }); + + it('a placed group\'s fields keep only the extension\'s own, a redeclared owner field left out', () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + extend(reg, [{ group: { key: 'tax', label: 'Tax', fields: ['tax_id', 'industry'] }, after: 'basic' }], { + fields: { tax_id: TAX_ID, industry: { name: 'industry', type: 'text', label: 'Sector', group: 'basic' } }, + }); + expect(groupFields(served(reg), 'tax')).toEqual(['tax_id']); + }); +}); + +describe('#35901 — an anchor another placement brings is found whatever the order (L2 S3)', () => { + it('a list anchored on a list the same extension places after it', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + extend(reg, [{ list: 'acme_a', after: 'acme_b' }, { list: 'acme_b', after: 'crm_contact' }]); + expect(served(reg).relatedLists).toEqual(['crm_contact', 'acme_b', 'acme_a', 'crm_opportunity']); + expect(warn).not.toHaveBeenCalled(); + }); + + it('a lower-priority package anchored on a higher-priority package\'s group', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + extend(reg, [{ group: { key: 'audit', label: 'Audit' }, after: 'tax' }], { pkg: 'com.acme.audit', priority: 100, fields: {} }); + extend(reg, [{ group: { key: 'tax', label: 'Tax' }, after: 'basic' }], { pkg: 'com.acme.tax', priority: 200, fields: {} }); + expect(served(reg).fieldGroups.map((g: any) => g.key)).toEqual(['basic', 'tax', 'audit', 'more']); + expect(warn).not.toHaveBeenCalled(); + }); + + it('a field anchored on a field the same extension places later in the entry list', () => { + const reg = withVendor(); + extend( + reg, + [{ field: 'tax_region', group: 'basic', after: 'tax_id' }, { field: 'tax_id', group: 'basic', after: 'industry' }], + { fields: { tax_id: TAX_ID, tax_region: { name: 'tax_region', type: 'text', label: 'Tax region' } } }, + ); + expect(groupFields(served(reg), 'basic')).toEqual(['name', 'industry', 'tax_id', 'tax_region', 'phone']); + }); + + it('an anchor nobody brings still goes to the end and is named (control)', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + extend(reg, [{ list: 'acme_a', after: 'acme_nowhere' }]); + expect(served(reg).relatedLists).toEqual(['crm_contact', 'crm_opportunity', 'acme_a']); + expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain("places list 'acme_a' after 'acme_nowhere'"); + }); +}); + +describe('#35901 — the stored object_extension door (parse only) is held by the merge too (L2 S1)', () => { + it('a parsed extension whose group places the owner\'s list is not added, named', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reg = withVendor(); + const parsed = ObjectExtensionSchema.parse({ + extend: OBJ, + place: [{ group: { key: 'deals', label: 'Deals', relatedList: 'crm_opportunity' }, after: 'basic' }], + }); + reg.registerObjectExtension(parsed as never, EXT_PKG); + const body = served(reg); + expect(body.fieldGroups).toEqual(vendorAccount().fieldGroups); + expect(body.relatedLists).toEqual(['crm_contact', 'crm_opportunity']); + expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain("placing list 'crm_opportunity'"); + }); +}); + describe('#35901 — the manifest loop carries place onto the extension def', () => { it('a package\'s objectExtensions entry places its field through ObjectQL.registerApp', () => { const ql = new ObjectQL(); diff --git a/packages/objectql/src/registry-extension-placement.ts b/packages/objectql/src/registry-extension-placement.ts index 49f18309b02..fa092e429cd 100644 --- a/packages/objectql/src/registry-extension-placement.ts +++ b/packages/objectql/src/registry-extension-placement.ts @@ -23,14 +23,22 @@ * * Several items at one anchor keep reading order: after an anchor they follow * it lowest priority first; before an anchor they precede it lowest priority - * first. An anchor the object does not have puts the item at the end and is - * named. An item the object (or the base the fold starts from) already + * first. An anchor another placement brings is found whatever order the two + * are written or registered in (each pass places in rounds); an anchor nobody + * brings puts the item at the end and is named. An item the object (or the base the fold starts from) already * arranges keeps that position, silently: the owner's position wins, and a * body that already carries the placements re-folds to itself. * * Nothing here drops an item from the object: a placement that does not apply * leaves the item where the merge put it (the field among the fields, the * list in the automatic tab order) and is named once. + * + * An extension places only its own items, judged here as well as at parse and + * at `defineStack` (a manifest's body reaches the registry unparsed): a field + * it does not add is not moved, a group's `fields` keep only the fields it + * adds, and a list placement, or a group whose `relatedList` names a list, is + * skipped when the list's child object is registered to another package (or + * to none). Each is named once; an unregistered child is no verdict. */ import { readFieldGroupMembership, relatedListEntryName } from '@objectstack/spec/data'; @@ -56,7 +64,10 @@ export interface PlacementContributor { readonly priority: number; /** The extension's `place` entries, as registered (un-parsed tolerant read). */ readonly place: readonly unknown[]; - /** The field names this extension's own `fields` declares. */ + /** + * The fields this extension adds and owns: keys of its own `fields` that + * neither the owner nor an extension folded earlier declares. + */ readonly ownFields: ReadonlySet; } @@ -137,6 +148,50 @@ function splice(slots: Slot[], name: string, value: T, after: string | und return after === undefined && before === undefined; } +/** One splice a pass queues: where it goes, and what to do once it is placed. */ +interface PlacementJob { + readonly slots: Slot[]; + readonly name: string; + readonly value: T; + readonly after: string | undefined; + readonly before: string | undefined; + readonly endIndex: () => number; + /** Called once, with whether the anchor it names was found. */ + readonly placed: (anchored: boolean) => void; +} + +/** + * [#35901] Run a pass's splices so that an anchor another placement brings + * is found whatever order the two are written or registered in (`os validate` + * accepts such an anchor, so the merge must too). Rounds in placement order: + * each round places every job whose anchor is present (or that names none); + * a job whose anchor is absent waits for the next round. When a round places + * nothing, the jobs still waiting name an anchor nobody brings, and go to the + * end in placement order. + */ +function placeInRounds(jobs: readonly PlacementJob[]): void { + const holds = (job: PlacementJob): boolean => { + const anchor = job.after ?? job.before; + return anchor === undefined || job.slots.some((slot) => slot.name === anchor); + }; + let waiting = [...jobs]; + let progressed = true; + while (waiting.length > 0 && progressed) { + progressed = false; + const next: PlacementJob[] = []; + for (const job of waiting) { + if (!holds(job)) { + next.push(job); + continue; + } + job.placed(splice(job.slots, job.name, job.value, job.after, job.before, job.endIndex)); + progressed = true; + } + waiting = next; + } + for (const job of waiting) job.placed(splice(job.slots, job.name, job.value, job.after, job.before, job.endIndex)); +} + /** The extensions in placement order: ascending priority, then package id. */ function inPlacementOrder(extensions: readonly PlacementContributor[]): PlacementContributor[] { return extensions @@ -178,20 +233,27 @@ function tabsArrange(names: readonly string[], list: string): boolean { /** * [#35901] The `extend` contributors that carry placements, in the fold's - * hands: each one's `place` and the names of its own `fields`. + * hands: each one's `place` and the fields it OWNS. A field is owned by where + * it comes from, never by its presence in a body: the owner's fields + * (`ownerFields`) are the owner's, and a field two extensions declare is the + * one folded first's (contributors arrive in fold order). An extension that + * redeclares such a field (ADR-0146 D10 admits a display-only redeclaration) + * does not own it, so it cannot place it. */ -export function placementContributorsOf(contributors: readonly ObjectContributor[]): PlacementContributor[] { +export function placementContributorsOf( + contributors: readonly ObjectContributor[], + ownerFields: ReadonlySet | undefined, +): PlacementContributor[] { const out: PlacementContributor[] = []; + const claimed = new Set(ownerFields ?? []); for (const contributor of contributors) { if (contributor.ownership !== 'extend') continue; const body = contributor.definition as unknown as AnyRecord; + const declared = isRecord(body.fields) ? Object.keys(body.fields) : []; + const ownFields = new Set(declared.filter((name) => !claimed.has(name))); + for (const name of declared) claimed.add(name); if (!Array.isArray(body.place) || body.place.length === 0) continue; - out.push({ - packageId: contributor.packageId, - priority: contributor.priority, - place: body.place, - ownFields: new Set(isRecord(body.fields) ? Object.keys(body.fields) : []), - }); + out.push({ packageId: contributor.packageId, priority: contributor.priority, place: body.place, ownFields }); } return out; } @@ -241,12 +303,30 @@ export function applyExtensionPlacements( .map((group) => ({ name: isRecord(group) ? stringOrUndefined(group.key) ?? '' : '', value: group })); const groupAddedBy = new Map(); let groupsChanged = false; + const groupJobs: PlacementJob[] = []; for (const extension of placing) { extension.place.forEach((entry, index) => { if (!isRecord(entry) || !isRecord(entry.group)) return; const key = stringOrUndefined(entry.group.key); if (key === undefined) return; const { after, before } = anchorOf(entry); + // A group that places a body table moves that list into the field area + // (and, on a declared tab list that does not name it, off the tabs), so + // it is judged as a list placement is: skipped on a positive verdict + // that the child is not this package's. An unregistered child is no + // verdict: its package may register it later in the boot. + const groupList = relatedListEntryName(entry.group.relatedList); + if (groupList !== undefined) { + const owner = context.childPackageOf(childOf(groupList)); + if (owner !== undefined && (owner ?? undefined) !== extension.packageId) { + note(extension, index, `group:${key}`, + `adds field group '${key}' (place[${index}]) placing list '${groupList}', whose object ` + + `'${childOf(groupList)}' is ${owner === null ? 'registered with no package' : `package "${owner}"'s`}, ` + + 'not a child object this package defines, so the group is not added: the lists of the extended ' + + 'object and of other packages are arranged by their owners.'); + return; + } + } if (!groupsDeclared) { note(extension, index, `group:${key}`, `places field group '${key}' (place[${index}]), which is not applied: "${objectName}" declares no ` + @@ -271,16 +351,36 @@ export function applyExtensionPlacements( // A base that already carries the key (a body that carries these // placements, or a tenant base) keeps its own position. if (groupSlots.some((slot) => slot.name === key)) return; - const anchored = splice(groupSlots, key, { ...entry.group }, after, before, () => groupSlots.length); - groupAddedBy.set(key, extension.packageId); - groupsChanged = true; - if (!anchored) { - note(extension, index, `group:${key}`, - `places field group '${key}' ${anchorText(after, before)} (place[${index}]), but "${objectName}" has ` + - 'no such group, so it is placed after the last group.'); + // The parse refuses a group listing a field the extension does not add; + // a manifest's body reaches the registry unparsed, so the merge drops + // such a name from the group too, and its owner keeps arranging it. + const placed: AnyRecord = { ...entry.group }; + if (Array.isArray(entry.group.fields)) { + const listed = entry.group.fields; + const own = listed.filter((name): name is string => typeof name === 'string' && extension.ownFields.has(name)); + const foreign = listed.filter((name): name is string => typeof name === 'string' && !extension.ownFields.has(name)); + if (own.length !== listed.length) placed.fields = own; + if (foreign.length > 0) { + note(extension, index, `group:${key}:fields`, + `adds field group '${key}' (place[${index}]) listing ${foreign.map((name) => `\`${name}\``).join(', ')}, ` + + 'which this extension does not add, so the group does not take them: a field of the extended object, ' + + 'or of another package\'s extension, is arranged by its owner.'); + } } + groupAddedBy.set(key, extension.packageId); + groupJobs.push({ + slots: groupSlots, name: key, value: placed, after, before, endIndex: () => groupSlots.length, + placed: (anchored) => { + groupsChanged = true; + if (anchored) return; + note(extension, index, `group:${key}`, + `places field group '${key}' ${anchorText(after, before)} (place[${index}]), but "${objectName}" has ` + + 'no such group, so it is placed after the last group.'); + }, + }); }); } + placeInRounds(groupJobs); // ── 2. fields ─────────────────────────────────────────────────────────── // Members of each group the pass touches, read once from the running @@ -289,6 +389,7 @@ export function applyExtensionPlacements( const groupsNow = (): AnyRecord[] => groupSlots.map((slot) => slot.value).filter(isRecord); const listedSomewhere = (field: string): boolean => groupsNow().some((group) => Array.isArray(group.fields) && group.fields.includes(field)); + const fieldJobs: PlacementJob[] = []; for (const extension of placing) { extension.place.forEach((entry, index) => { if (!isRecord(entry) || typeof entry.field !== 'string') return; @@ -299,7 +400,8 @@ export function applyExtensionPlacements( if (!extension.ownFields.has(field)) { note(extension, index, `field:${field}`, `places field \`${field}\` (place[${index}]), which is not a field this extension adds, so it is not ` + - 'moved: a field of the extended object, or of another package\'s extension, is arranged by its owner.'); + 'moved: a field of the extended object, or of another package\'s extension, is arranged by its owner, ' + + 'also when this extension redeclares it.'); return; } if (!isRecord(fields[field])) return; @@ -334,18 +436,23 @@ export function applyExtensionPlacements( } const at = slots.findIndex((slot) => slot.name === field); if (at !== -1) slots.splice(at, 1); - const anchored = splice(slots, field, field, after, before, () => slots!.length); + const memberList = slots; + fieldJobs.push({ + slots: memberList, name: field, value: field, after, before, endIndex: () => memberList.length, + placed: (anchored) => { + if (anchored) return; + note(extension, index, `field:${field}`, + `places field \`${field}\` ${anchorText(after, before)} in group '${key}' (place[${index}]), but that ` + + 'group has no such member, so the field is placed last in the group.'); + }, + }); if (fields[field] && (fields[field] as AnyRecord).group !== key) { fields = { ...fields, [field]: { ...(fields[field] as AnyRecord), group: key } }; fieldsChanged = true; } - if (!anchored) { - note(extension, index, `field:${field}`, - `places field \`${field}\` ${anchorText(after, before)} in group '${key}' (place[${index}]), but that ` + - 'group has no such member, so the field is placed last in the group.'); - } }); } + placeInRounds(fieldJobs); if (memberSlots.size > 0) { for (let index = 0; index < groupSlots.length; index += 1) { const slot = groupSlots[index]; @@ -365,6 +472,7 @@ export function applyExtensionPlacements( return end; }; let tabsChanged = false; + const listJobs: PlacementJob[] = []; for (const extension of placing) { extension.place.forEach((entry, index) => { if (!isRecord(entry) || typeof entry.list !== 'string') return; @@ -396,18 +504,22 @@ export function applyExtensionPlacements( const value = label !== undefined || columns !== undefined ? { list, ...(label !== undefined ? { label } : {}), ...(columns !== undefined ? { columns: [...columns] } : {}) } : list; - const anchored = splice(tabSlots, list, value, after, before, tabsEnd); - tabsChanged = true; - // Before a trailing built-in tab the object leaves unlisted is the end - // of the tabs anyway (the approvals and the stream follow every listed - // tab), so that miss is the position asked for and is not named. - if (!anchored && !(before !== undefined && TRAILING_BUILTIN_TABS.has(before))) { - note(extension, index, `list:${list}`, - `places list '${list}' ${anchorText(after, before)} (place[${index}]), but "${objectName}" has no such ` + - 'tab in its `relatedLists`, so the list is placed at the end of the tabs.'); - } + listJobs.push({ + slots: tabSlots, name: list, value, after, before, endIndex: tabsEnd, + placed: (anchored) => { + tabsChanged = true; + // Before a trailing built-in tab the object leaves unlisted is the + // end of the tabs anyway (the approvals and the stream follow every + // listed tab), so that miss is the position asked for and is not named. + if (anchored || (before !== undefined && TRAILING_BUILTIN_TABS.has(before))) return; + note(extension, index, `list:${list}`, + `places list '${list}' ${anchorText(after, before)} (place[${index}]), but "${objectName}" has no such ` + + 'tab in its `relatedLists`, so the list is placed at the end of the tabs.'); + }, + }); }); } + placeInRounds(listJobs); if (!groupsChanged && !tabsChanged && !fieldsChanged) return { object, notes }; const out = { ...record } as AnyRecord; diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index 784828facaf..6e2e2bbc1ec 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -945,7 +945,7 @@ export class ObjectRegistrationFacet { // [#35901] Where each extension's own fields, groups and child lists go: // applied once, here, after every contributor's fields are merged, so the // anchors an extension names are the object's as served. - const placing = placementContributorsOf(contributors); + const placing = placementContributorsOf(contributors, ownFields); if (placing.length > 0) { const placed = applyExtensionPlacements(merged, placing, { objectName: String(merged.name ?? baseDefinition.name ?? ''), diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index c5448583069..6ec2feedaab 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -6492,8 +6492,10 @@ function objectExtensionPlaceDescription(): string { '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. Write `after` or `before`, or neither for the end. An anchor that ' + - 'does not exist puts the item at the end of its group, of the groups, or of the tabs (before the approvals ' + + '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 ' + @@ -6505,9 +6507,13 @@ function objectExtensionPlaceDescription(): string { '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`, a group key the extended object or another package already ' + - 'declares, or a list that is not a child object of its package is refused (here, or at `defineStack` where ' + - 'the package\'s objects are known) and skipped by the merge with a warning naming whose item it is. Applied ' + + '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: ' + diff --git a/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts b/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts index 173a8374f30..58c44527a0f 100644 --- a/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts +++ b/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts @@ -25,9 +25,10 @@ export const entry: SemanticMigration = { + 'their objects (「三个内置项,是不是可以直接用对应的对象名」). Until now a declared relatedLists only ' + 'ordered: listed lists came first and every unlisted one still followed, and the attachments, ' + 'approvals and stream tabs always closed the strip in a fixed order. Now, on a declared non-empty ' - + 'relatedLists, a side list no entry names shows no tab, a child list another package adds included: ' - + 'it is hidden until the parent names it, which a build accepts only when that package is in the ' - + 'parent\'s stack (no longer hidden since object-extension-place-and-cross-package-lists); the attachments tab shows only when ' + + 'relatedLists, a side list no entry names shows no tab. A child list another package adds was hidden ' + + 'too until the parent named it, which a build accepts only when that package is in the parent\'s ' + + 'stack; since object-extension-place-and-cross-package-lists it shows at the end of the tabs instead. ' + + 'The attachments tab shows only when ' + "'sys_attachment' is listed (and the object enables files, as before); the approvals tab, when " + 'unlisted, follows the listed tabs and still shows whenever the record has requests; the stream ' + 'tab, when unlisted, still closes the strip. Body tables a field group places stay at their group; ' diff --git a/packages/spec/src/stack-extension-place.test.ts b/packages/spec/src/stack-extension-place.test.ts index 2bcdebe838d..6e10cd3ddce 100644 --- a/packages/spec/src/stack-extension-place.test.ts +++ b/packages/spec/src/stack-extension-place.test.ts @@ -47,7 +47,9 @@ const contract = { }; const memo = { name: 'xplx_memo', label: 'Memo', fields: { title: { type: 'text' as const, label: 'Title' } } }; -const extensionPackage = (place: unknown[], objects: unknown[] = [contract, memo]) => ({ +const TAX_ID_FIELDS = { tax_id: { type: 'text' as const, label: 'Tax ID' } }; + +const extensionPackage = (place: unknown[], objects: unknown[] = [contract, memo], fields: Record = TAX_ID_FIELDS) => ({ manifest: { id: 'com.example.xpl-ext', namespace: 'xplx', @@ -57,14 +59,14 @@ const extensionPackage = (place: unknown[], objects: unknown[] = [contract, memo objects, objectExtensions: [{ extend: 'xpl_account', - fields: { tax_id: { type: 'text' as const, label: 'Tax ID' } }, + fields, place, }], }, }); -const stackWith = (place: unknown[], objects?: unknown[]) => - ({ manifest, objects: [account, opportunity], packages: [extensionPackage(place, objects)] }) as any; +const stackWith = (place: unknown[], objects?: unknown[], fields?: Record) => + ({ manifest, objects: [account, opportunity], packages: [extensionPackage(place, objects, fields)] }) as any; const refusalOf = (fn: () => unknown): Refusal | undefined => { try { @@ -123,6 +125,25 @@ describe('defineStack — an extension adds a group of its own', () => { }); }); +describe('defineStack — an extension places only a field it adds, not one it redeclares', () => { + // ADR-0146 D10 admits redeclaring an owner field for its display; that does not make it the extension's. + const redeclared = { ...TAX_ID_FIELDS, industry: { type: 'text' as const, label: 'Sector' } }; + + it('accepts placing its own field while it redeclares an owner field (control)', () => { + expect(() => defineStack(stackWith([{ field: 'tax_id', group: 'basic', after: 'industry' }], undefined, redeclared))).not.toThrow(); + }); + + it.each([ + ['at the entry', { field: 'industry', group: 'basic', after: 'name' }, "place[0] places field 'industry'"], + ['in a placed group\'s fields', { group: { key: 'tax', label: 'Tax', fields: ['tax_id', 'industry'] }, after: 'basic' }, "place[0].group.fields[1] places field 'industry'"], + ])('refuses placing the redeclared owner field %s', (_label, entry, subject) => { + const refusal = refusalOf(() => defineStack(stackWith([entry], undefined, redeclared))); + expect(refusal?.code).toBe('STACK_CROSS_REFERENCE_INVALID'); + expect(refusal?.issues).toHaveLength(1); + expect(refusal?.issues?.[0]).toContain(`${subject}, which 'xpl_account' declares itself`); + }); +}); + describe('defineStack — a missing anchor is no refusal', () => { it('accepts anchors the extended object does not have (the merge puts the item at the end)', () => { expect(() => defineStack(stackWith([ diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index c85a082aca3..2fd398b6df3 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -4643,6 +4643,10 @@ function collectRelatedListNameErrors( * - a placed group's `key` must not be one of the extended object's own * group keys, where this stack defines that object: the group would be * the owner's, which an extension does not arrange. + * - a placed field (and a placed group's `fields`) must not be a field the + * extended object declares, where this stack defines that object: an + * extension may redeclare an owner field for its display properties + * (ADR-0146 D10), which does not make the field the extension's to move. * * Anchors are not judged here: a missing anchor puts the item at the end and * is a `@objectstack/lint` warning, never a refusal, so removing a field from @@ -4729,12 +4733,26 @@ function collectExtensionPlacementErrors(config: ObjectStackDefinition): string[ ); } }; + const targetFields = asRecord(definedAnywhere.get(target)?.fields) ?? {}; + const judgeOwnerField = (name: unknown, where: string): void => { + if (typeof name !== 'string' || !Object.prototype.hasOwnProperty.call(targetFields, name)) return; + errors.push( + `${at}objectExtensions[${j}] (extending '${target}') ${where} places field '${name}', which ` + + `'${target}' declares itself: an extension places only a field it adds, and redeclaring an owner ` + + 'field (for its display properties) does not make it the extension\'s. The owner arranges it; ' + + 'remove the placement.', + ); + }; (record.place as unknown[]).forEach((entry: unknown, k: number) => { const placement = asRecord(entry); if (!placement) return; if (typeof placement.list === 'string') judgeList(placement.list, `place[${k}].list`); + judgeOwnerField(placement.field, `place[${k}]`); const group = asRecord(placement.group); if (!group) return; + if (Array.isArray(group.fields)) { + group.fields.forEach((name: unknown, f: number) => judgeOwnerField(name, `place[${k}].group.fields[${f}]`)); + } if (typeof group.relatedList === 'string') judgeList(group.relatedList, `place[${k}].group.relatedList`); if (typeof group.key === 'string' && targetGroups.has(group.key)) { errors.push( From 42d56e66cbcb04222ddfae95496b5f17d0542db2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:41:47 +0000 Subject: [PATCH 9/9] docs(references): regenerate the protocol index after merging main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUxeTKkCvZ2iariHQf --- content/docs/references/index.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 61375a5ebcd..60f5438d80a 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 — 1707 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1708 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/. */} @@ -32,9 +32,9 @@ counts are sums of the rows they head. Regenerate with | [Security Protocol](/docs/references/security) | 6 | 37 | Permission sets, row-level security, sharing rules, tenancy posture. | | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | -| [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | +| [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** | **1707** | 14 protocol modules | +| **Total** | **219** | **1708** | 14 protocol modules | --- @@ -335,7 +335,7 @@ Studio designer metadata — the authoring surfaces for the protocols above. ## System Protocol -**Source:** `packages/spec/src/system/` · **Import:** `@objectstack/spec/system` · **40 pages, 297 schemas** +**Source:** `packages/spec/src/system/` · **Import:** `@objectstack/spec/system` · **40 pages, 298 schemas** The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. @@ -375,7 +375,7 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a | [`settings-client.zod.ts`](/docs/references/system/settings-client) | `SettingsChangeEvent` | | [`settings-manifest.zod.ts`](/docs/references/system/settings-manifest) | `ResolvedSettingValue`, `SettingsActionResult`, `SettingsManifest`, `SettingsNamespacePayload`, `Specifier`, `SpecifierHandler`, `SpecifierOption`, `SpecifierScope`, `SpecifierType`, `SpecifierValueDomain` | | [`sms-config.zod.ts`](/docs/references/system/sms-config) | `StackSmsConfig` | -| [`stack-server.zod.ts`](/docs/references/system/stack-server) | `ServerRateLimitConfig`, `StackServerConfig`, `StackServerSecurity` | +| [`stack-server.zod.ts`](/docs/references/system/stack-server) | `ServerRateLimitConfig`, `StackServerConfig`, `StackServerSecurity`, `TrustedProxyNetworks` | | [`supplier-security.zod.ts`](/docs/references/system/supplier-security) | `SupplierAssessmentStatus`, `SupplierRiskLevel`, `SupplierSecurityAssessment`, `SupplierSecurityPolicy`, `SupplierSecurityRequirement` | | [`tenant.zod.ts`](/docs/references/system/tenant) | `DatabaseLevelIsolationStrategy`, `DatabaseProvider`, `QuotaEnforcementResult`, `RowLevelIsolationStrategy`, `SchemaLevelIsolationStrategy`, `Tenant`, `TenantConnectionConfig`, `TenantIsolationConfig`, `TenantIsolationLevel`, `TenantQuota`, `TenantSecurityPolicy`, `TenantUsage` | | [`tracing.zod.ts`](/docs/references/system/tracing) | `OpenTelemetryCompatibility`, `OtelExporterType`, `SamplingDecision`, `SamplingStrategyType`, `Span`, `SpanAttributeValue`, `SpanAttributes`, `SpanEvent`, `SpanKind`, `SpanLink`, `SpanStatus`, `TraceContext`, `TraceContextPropagation`, `TraceFlags`, `TracePropagationFormat`, `TraceSamplingConfig`, `TraceState`, `TracingConfig` |