diff --git a/.changeset/20731-metadata-protocol-packaged-view-base.md b/.changeset/20731-metadata-protocol-packaged-view-base.md new file mode 100644 index 00000000000..d6bbc0faa31 --- /dev/null +++ b/.changeset/20731-metadata-protocol-packaged-view-base.md @@ -0,0 +1,13 @@ +--- +'@objectstack/metadata-protocol': minor +--- + +fix(metadata-protocol): `getPackagedViewBase(name)` answers the view a code package ships, before any overlay (#20731) + +`ObjectStackProtocolImplementation` gains `getPackagedViewBase(name)`, the view twin of `getPackagedDashboardBase`. It returns the packaged (code-layer) declaration of a view, which is the `packagedBase` that `translateView` compares a served view against, so that a tenant's published overlay is not overwritten by the packaged translation catalog. + +`name` is the view's registry identity, the qualified `.` that each view of a `defineView` container is registered under and that the overlay row and both reads carry. The bare view key that the catalog uses under its object is not an identity (another object may ship a view with the same key), and it answers `undefined`. + +It reads the artifact registry's code-package entry only, through the same lookup as `getPackagedDashboardBase`. An overlay that was hydrated under the plain registry key can therefore never be returned as the base it is compared against. It returns `undefined` for a view that no code package ships, for an unknown or empty name, and for a registry that cannot answer. A caller treats `undefined` as "no base known", and the catalog applies as before. + +The method is additive. No existing read changes answer, and `getPackagedDashboardBase` answers exactly as before. Nothing is removed or renamed. diff --git a/.changeset/20731-spec-view-catalog-override.md b/.changeset/20731-spec-view-catalog-override.md new file mode 100644 index 00000000000..d86b1bc35d4 --- /dev/null +++ b/.changeset/20731-spec-view-catalog-override.md @@ -0,0 +1,19 @@ +--- +'@objectstack/spec': minor +--- + +fix(spec): `translateView` lets an explicit override beat the packaged catalog when it is handed the packaged view (#20731) + +`translateView` (`@objectstack/spec/system`) now follows the rule ADR-0029 D9.2a records for objects, and that `translateDashboard` already follows: an explicit override beats a packaged default. When the caller supplies `packagedBase` (the view as its code package ships it, before any tenant overlay), a catalog string replaces a served string only while that string still equals its packaged counterpart. It is the same comparison, not a second one. + +The comparison is made per string: the view `label` and `description`, each bulk-action def's `label`, `confirmText` and `confirmLabel`, and each of its params' `label`, `help` and `placeholder`. A def or param is matched by the `name` the bundle addresses it by, and one that the packaged view does not carry counts as authored, so its strings keep their values. + +Why: an org overlay on a packaged view (ADR-0126 Regime O) changed the label of the showcase's `showcase_task.in_progress` and published. The metadata protocol's item and list reads served the edit, but a `zh-CN` reader was served `进行中`, the catalog's translation of the label the package shipped. The catalog (`objects.._views.`) translated the packaged view and was applied over the tenant's edit. + +What changes for a caller: + +- `translateView`'s third parameter is typed `TranslateDocumentOptions` (was `ResolveOptions`). That type is `ResolveOptions` plus the optional `packagedBase`, and `translateMetadataDocument` already passed it through. Every existing call compiles unchanged. +- Without `packagedBase` (`undefined` or `null`), the output is byte-identical to before: the catalog applies. No serving layer in this release passes a view base yet, so no served view changes answer with this package alone. +- An edit back to exactly the shipped string is a no-op: the catalog still translates it. A label written as an inline locale map is not an override either; only a string is compared. + +Nothing is removed or renamed, and there is nothing to migrate. diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index a4668598319..77cb8eeb221 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -7192,12 +7192,62 @@ export class ObjectStackProtocolImplementation implements * unknown name, and a registry double without the lookup. */ getPackagedDashboardBase(name: string): unknown { + return this.packagedArtifactBase('dashboard', name); + } + + /** + * [#20731] The PACKAGED (code-layer) declaration of a VIEW — the view + * item a code package ships, before any tenant `sys_metadata` overlay. + * The view twin of {@link getPackagedDashboardBase}, answered the same + * way, and the fact `translateView` (`@objectstack/spec/system`) compares + * against as its `packagedBase`: the i18n catalog + * (`objects.._views.`) is the packaged translation of + * exactly this body, so it may only replace a string the served view + * still carries unchanged from it (ADR-0029 D9.2a — an explicit override + * beats a packaged default; ADR-0126 Regime O — a packaged view is + * overlay-editable, and a published overlay is what every read serves). + * + * Measured before this existed: an org overlay on the showcase's + * `showcase_task.in_progress` changed its label, published, and was + * returned by {@link getMetaItem} and {@link getMetaItems}, yet a `zh-CN` + * reader was served the catalog's translation of the shipped label, + * because the translation of the served view had no base to compare with. + * + * `name` is the served view's REGISTRY identity — the qualified + * `.` the boot registers each view of a `defineView` + * container under (`expandViewContainer`), which is also the name the + * overlay row and both reads carry. ⛔ Not the bare `` the catalog + * is keyed by under its object: that key is unique only within one object, + * so it can never select the base (it answers `undefined` here unless some + * code package registers a view under that literal name). + * + * Shadow-immune for the same reason as the dashboard's: an overlay hydrated + * under the plain registry key is never returned as the base it is meant + * to be compared against. A view has no extension fold, so the artifact + * item IS the packaged declaration. + * + * Returns `undefined` for a runtime/tenant-authored view (no code package + * ships it), an unknown or empty name, and a registry double without the + * lookup — "no packaged baseline", read by the translator as the catalog + * applying unchanged. + */ + getPackagedViewBase(name: string): unknown { + return this.packagedArtifactBase('view', name); + } + + /** + * The one body behind {@link getPackagedDashboardBase} and + * {@link getPackagedViewBase}: {@link lookupArtifactItem}, and nothing + * wider, so only an item whose `_packageId` marks a genuine code package + * answers, and an overlay hydrated under the plain registry key never does. + */ + private packagedArtifactBase(type: 'dashboard' | 'view', name: string): unknown { if (typeof name !== 'string' || name === '') return undefined; try { - return this.lookupArtifactItem('dashboard', name); + return this.lookupArtifactItem(type, name); } catch { // A read over the in-memory registry; a failure here must never - // turn a served dashboard into a 5xx. + // turn a served document into a 5xx. return undefined; } } diff --git a/packages/objectql/src/protocol-packaged-view-base.test.ts b/packages/objectql/src/protocol-packaged-view-base.test.ts new file mode 100644 index 00000000000..8b37b58bcd4 --- /dev/null +++ b/packages/objectql/src/protocol-packaged-view-base.test.ts @@ -0,0 +1,257 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #20731 — `ObjectStackProtocolImplementation.getPackagedViewBase`, against a + * REAL `SchemaRegistry`, and the read it exists to feed. The view twin of + * `protocol-packaged-dashboard-base.test.ts`. + * + * ## What was measured + * + * An org overlay on the showcase's packaged view `showcase_task.in_progress` + * (ADR-0126 Regime O — a packaged view is overlay-editable) changed its label + * and was published. An `en` reader was served the edit; a `zh-CN` reader, + * admin or member, on the `/meta` item and list reads, was served `进行中` — + * the catalog's translation of the label the package shipped. Reproduced here + * one layer down, on the tree before this change: the protocol's item and list + * reads both return the overlay's label, and `translateView` answered `进行中` + * over it in `zh-CN` even when handed the packaged view, because it took no + * base at all. + * + * The rule that fixes it is ADR-0029 D9.2a's — an explicit override beats a + * packaged default, decided by comparing against the PACKAGED declaration — + * and that comparison is only as good as the body this accessor returns. Hence + * a real registry, registered the way the boot registers a `defineView` + * container: the container under the bare object key, and each view it + * expands to (`expandViewContainer`) under its qualified `.` + * name, which is the identity the base is looked up by. + */ + +import { describe, it, expect } from 'vitest'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { translateView, type TranslationBundle } from '@objectstack/spec/system'; +import { expandViewContainer } from '@objectstack/spec/ui'; +import { SchemaRegistry } from './registry.js'; +import { assertEngineFindOnePredicate } from './engine-findone-predicate.js'; + +const PKG = 'com.example.showcase'; +const OBJ = 'showcase_task'; +const VIEW = 'showcase_task.in_progress'; +const ORG = 'org_acme'; + +const SHIPPED_LABEL = 'In Progress'; +const EDITED_LABEL = 'In Progress (edited)'; + +const listView = (object: string, label: string) => ({ + label, + type: 'grid' as const, + data: { provider: 'object' as const, object }, + columns: [{ field: 'title' }], +}); + +/** The `defineView` container as the code package ships it. */ +const taskContainer = () => ({ + listViews: { + in_progress: listView(OBJ, SHIPPED_LABEL), + urgent: listView(OBJ, 'Urgent'), + }, +}); + +/** + * The catalog: `zh-CN` translates the shipped labels, keyed by the BARE view + * key under its object; `en` repeats the shipped label, the way a package that + * extracts its source locale ships it. + */ +const BUNDLE: TranslationBundle = { + en: { objects: { [OBJ]: { _views: { in_progress: { label: SHIPPED_LABEL }, urgent: { label: 'Urgent' } } } } } as any, + 'zh-CN': { objects: { [OBJ]: { _views: { in_progress: { label: '进行中' }, urgent: { label: '紧急' } } } } } as any, +}; + +const matchesWhere = (row: Record, where: Record) => + Object.entries(where ?? {}).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + if (v === null) return row[k] === null || row[k] === undefined; + return row[k] === v; + }); + +/** + * A real registry and the real protocol over a READ-ONLY in-memory + * `sys_metadata`: the overlay row is seeded exactly as a published org overlay + * stores it, so no write verb is doubled here at all. + */ +function makeSession() { + const registry = new SchemaRegistry({ multiTenant: false }); + registry.logLevel = 'silent'; + const rows: Record[] = []; + const engine: any = { + registry, + async findOne(table: string, o: { where: Record }) { + // The real engine's #4419 predicate: a `findOne` naming no record is refused. + assertEngineFindOnePredicate(table, o); + if (table !== 'sys_metadata') return null; + return rows.find((r) => matchesWhere(r, o.where)) ?? null; + }, + async find(table: string, o: { where: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + const matched = rows.filter((r) => matchesWhere(r, o.where)); + // The caller's bound, applied after the filter, by presence. + return typeof o?.limit === 'number' ? matched.slice(0, o.limit) : matched; + }, + }; + const protocol: any = new ObjectStackProtocolImplementation(engine, undefined, 'env_test'); + return { protocol, registry, rows }; +} + +/** Register a container the way the boot does: the bare object key, then every expanded view. */ +function registerContainer(registry: SchemaRegistry, object: string, container: Record, pkg: string) { + registry.registerItem('view', { name: object, ...container }, 'name', pkg); + for (const item of expandViewContainer(object, container)) { + registry.registerItem('view', item, 'name', pkg); + } +} + +/** The packaged view item, as the boot registered it — the overlay's starting point. */ +const packagedItem = () => { + const item = expandViewContainer(OBJ, taskContainer()).find((v) => v.name === VIEW); + if (!item) throw new Error(`fixture missing ${VIEW}`); + return item; +}; + +/** The same view as the org's published overlay stores it — its label edited. */ +const overlayBody = () => ({ ...packagedItem(), label: EDITED_LABEL }); + +/** The published org overlay row, in the identity the write stores. */ +function seedOrgOverlay(rows: Record[]) { + rows.push({ + id: 'r_1', + type: 'view', + name: VIEW, + package_id: null, + organization_id: ORG, + state: 'active', + metadata: JSON.stringify(overlayBody()), + }); +} + +describe('#20731 getPackagedViewBase — the packaged view, never an overlay', () => { + it('answers the view item the code package shipped, by its qualified name', () => { + const s = makeSession(); + registerContainer(s.registry, OBJ, taskContainer(), PKG); + const base = s.protocol.getPackagedViewBase(VIEW); + expect(base?.name).toBe(VIEW); + expect(base?.object).toBe(OBJ); + expect(base?.label).toBe(SHIPPED_LABEL); + expect(base?._packageId).toBe(PKG); + }); + + it('is immune to an overlay hydrated under the plain registry key', () => { + // A published overlay is hydrated into the registry's PLAIN key. The + // accessor must still answer the packaged body — a base that returned + // the overlay would compare the edit equal to itself and hand the + // catalog straight back. + const s = makeSession(); + registerContainer(s.registry, OBJ, taskContainer(), PKG); + s.registry.registerItem('view', overlayBody(), 'name'); + + // The trap is live: the plain registry read answers the overlay… + expect((s.registry.getItem('view', VIEW) as any)?.label).toBe(EDITED_LABEL); + // …and the packaged base does not move. + expect(s.protocol.getPackagedViewBase(VIEW)?.label).toBe(SHIPPED_LABEL); + }); + + it('the KEY — matched by the qualified ., never by the bare catalog key another object shares', () => { + // The catalog addresses a view by its bare key UNDER its object, so the + // bare key alone is not an identity: `showcase_project` ships an + // `in_progress` view too. The base must be this object's view. + const s = makeSession(); + registerContainer(s.registry, OBJ, taskContainer(), PKG); + registerContainer(s.registry, 'showcase_project', { listViews: { in_progress: listView('showcase_project', 'Active Projects') } }, PKG); + + expect(s.protocol.getPackagedViewBase(VIEW)?.label).toBe(SHIPPED_LABEL); + expect(s.protocol.getPackagedViewBase('showcase_project.in_progress')?.label).toBe('Active Projects'); + // The bare key selects nothing — no view is registered under it. + expect(s.protocol.getPackagedViewBase('in_progress')).toBeUndefined(); + }); + + it('is undefined for a view no code package ships, an unknown name, and an empty name', () => { + // "No packaged baseline" is a real answer: the translator reads it as + // "infer nothing" and keeps the catalog, as before this change. + const s = makeSession(); + s.registry.registerItem('view', { ...packagedItem(), name: 'showcase_task.tenant_view' }, 'name'); + expect(s.protocol.getPackagedViewBase('showcase_task.tenant_view')).toBeUndefined(); + expect(s.protocol.getPackagedViewBase('showcase_task.no_such_view')).toBeUndefined(); + expect(s.protocol.getPackagedViewBase('')).toBeUndefined(); + }); + + it('is undefined when the host registry cannot answer', () => { + const partial: any = new ObjectStackProtocolImplementation({ registry: {} } as any, undefined, 'env_test'); + expect(partial.getPackagedViewBase(VIEW)).toBeUndefined(); + const none: any = new ObjectStackProtocolImplementation({} as any, undefined, 'env_test'); + expect(none.getPackagedViewBase(VIEW)).toBeUndefined(); + }); +}); + +describe('#20731 the published org overlay, through the protocol reads and the translation', () => { + it('the item and list reads serve the overlay — one identity for the write and both reads', async () => { + const s = makeSession(); + registerContainer(s.registry, OBJ, taskContainer(), PKG); + seedOrgOverlay(s.rows); + const served = await s.protocol.getMetaItem({ type: 'view', name: VIEW, organizationId: ORG }); + expect(served.item.label).toBe(EDITED_LABEL); + // The code artifact's envelope rides on the overlay body; it names the + // registering package, not a second identity the overlay missed. + expect(served.item._packageId).toBe(PKG); + + const list = await s.protocol.getMetaItems({ type: 'view', organizationId: ORG }); + const listed = (list.items as any[]).find((v) => v?.name === VIEW); + expect(listed?.label).toBe(EDITED_LABEL); + }); + + it('the translation serves the edit once it is handed the packaged base — zh-CN and en, item and list', async () => { + const s = makeSession(); + registerContainer(s.registry, OBJ, taskContainer(), PKG); + seedOrgOverlay(s.rows); + const item = (await s.protocol.getMetaItem({ type: 'view', name: VIEW, organizationId: ORG })).item; + const listed = ((await s.protocol.getMetaItems({ type: 'view', organizationId: ORG })).items as any[]) + .find((v) => v?.name === VIEW); + + for (const served of [item, listed]) { + const packagedBase = s.protocol.getPackagedViewBase(served.name); + for (const locale of ['zh-CN', 'en']) { + expect(translateView(served, BUNDLE, { locale, packagedBase }).label, locale).toBe(EDITED_LABEL); + } + } + }); + + it('an unedited view stays translated, handed its own base', async () => { + const s = makeSession(); + registerContainer(s.registry, OBJ, taskContainer(), PKG); + seedOrgOverlay(s.rows); + const urgent = (await s.protocol.getMetaItem({ type: 'view', name: 'showcase_task.urgent', organizationId: ORG })).item; + const packagedBase = s.protocol.getPackagedViewBase('showcase_task.urgent'); + expect(packagedBase?.label).toBe('Urgent'); + expect(translateView(urgent, BUNDLE, { locale: 'zh-CN', packagedBase }).label).toBe('紧急'); + }); + + it('CONTROL — without the base, the catalog replaces the edit (the measured defect)', async () => { + const s = makeSession(); + registerContainer(s.registry, OBJ, taskContainer(), PKG); + seedOrgOverlay(s.rows); + const served = (await s.protocol.getMetaItem({ type: 'view', name: VIEW, organizationId: ORG })).item; + expect(translateView(served, BUNDLE, { locale: 'zh-CN' }).label).toBe('进行中'); + expect(translateView(served, BUNDLE, { locale: 'en' }).label).toBe(SHIPPED_LABEL); + }); + + it('after reset (no overlay row) the shipped label is served and translated again', async () => { + const s = makeSession(); + registerContainer(s.registry, OBJ, taskContainer(), PKG); + seedOrgOverlay(s.rows); + const edited = (await s.protocol.getMetaItem({ type: 'view', name: VIEW, organizationId: ORG })).item; + const packagedBase = s.protocol.getPackagedViewBase(VIEW); + expect(translateView(edited, BUNDLE, { locale: 'zh-CN', packagedBase }).label).toBe(EDITED_LABEL); + + s.rows.length = 0; + const served = (await s.protocol.getMetaItem({ type: 'view', name: VIEW, organizationId: ORG })).item; + expect(served.label).toBe(SHIPPED_LABEL); + expect(translateView(served, BUNDLE, { locale: 'zh-CN', packagedBase }).label).toBe('进行中'); + }); +}); diff --git a/packages/spec/src/system/i18n-resolver.test.ts b/packages/spec/src/system/i18n-resolver.test.ts index 3092c3034b0..3d9702e8c16 100644 --- a/packages/spec/src/system/i18n-resolver.test.ts +++ b/packages/spec/src/system/i18n-resolver.test.ts @@ -3998,6 +3998,232 @@ describe('translateView — bulkActionDefs (#14253)', () => { }); }); +import { translateView } from './i18n-resolver'; + +describe('translateView — the catalog loses to an explicit override (#20731, ADR-0029 D9.2a)', () => { + // The view container as the package ships it. The served documents below are + // what `expandViewContainer` emits from it — the same composer the boot + // registers each packaged view with — so the base and the served view share + // one shape by construction. + const CONTAINER = { + listViews: { + in_progress: { + label: 'In Progress', + description: 'Tasks being worked on', + type: 'grid' as const, + data: { provider: 'object' as const, object: 'showcase_task' }, + columns: [{ field: 'title' }], + bulkActionDefs: [ + { + name: 'mark_done', + label: 'Mark done', + operation: 'update' as const, + patch: { status: 'done' }, + confirmText: 'Mark the selected tasks done?', + confirmLabel: 'Mark them', + params: [{ name: 'note', type: 'text' as const, label: 'Note', help: 'Shown on the timeline', placeholder: 'Optional' }], + }, + { name: 'skip', label: 'Skip', operation: 'update' as const, patch: { status: 'skipped' } }, + ], + }, + urgent: { + label: 'Urgent', + type: 'grid' as const, + data: { provider: 'object' as const, object: 'showcase_task' }, + columns: [{ field: 'title' }], + }, + }, + }; + + const clone = (v: T): T => JSON.parse(JSON.stringify(v)); + const packagedView = (name: string): any => { + const item = expandViewContainer('showcase_task', CONTAINER).find((v) => v.name === name); + if (!item) throw new Error(`fixture missing ${name}`); + return item; + }; + const PACKAGED = packagedView('showcase_task.in_progress'); + + // `en` repeats the shipped strings (a package that extracts its source + // locale), `zh-CN` translates them. The measured reading was in `zh-CN`; the + // `en` half proves the rule in the source locale too, where a repeated + // shipped string is exactly as able to overwrite an edit. + const BUNDLE: TranslationBundle = { + en: { + objects: { + showcase_task: { + _views: { + in_progress: { + label: 'In Progress', + description: 'Tasks being worked on', + bulkActions: { + mark_done: { + label: 'Mark done', + confirmText: 'Mark the selected tasks done?', + confirmLabel: 'Mark them', + params: { note: { label: 'Note', help: 'Shown on the timeline', placeholder: 'Optional' } }, + }, + skip: { label: 'Skip' }, + }, + }, + urgent: { label: 'Urgent' }, + }, + }, + }, + } as any, + 'zh-CN': { + objects: { + showcase_task: { + _views: { + in_progress: { + label: '进行中', + description: '正在处理的任务', + bulkActions: { + mark_done: { + label: '标记完成', + confirmText: '确定将所选任务标记为完成吗?', + confirmLabel: '确认标记', + // `added` is a param the package does not ship — addressed + // only to prove a tenant-added param keeps its own label. + params: { note: { label: '备注', help: '会显示在动态中', placeholder: '选填' }, added: { label: 'MUST-NOT-APPLY' } }, + }, + skip: { label: '跳过' }, + // A def the package does not ship, for the same reason. + added_def: { label: 'MUST-NOT-APPLY' }, + }, + }, + urgent: { label: '紧急' }, + }, + }, + }, + } as any, + }; + + const def = (view: any, name: string) => view.config.bulkActionDefs.find((d: any) => d.name === name); + const param = (view: any, defName: string, name: string) => def(view, defName).params.find((p: any) => p.name === name); + + it('composes the identity this test is pinned to — the served name is qualified, the catalog key is bare', () => { + expect(PACKAGED.name).toBe('showcase_task.in_progress'); + expect(PACKAGED.object).toBe('showcase_task'); + expect(PACKAGED.label).toBe('In Progress'); + // The catalog is addressed by the BARE key under the object; the base is + // the same registry item the served view is, handed in whole. + expect((BUNDLE['zh-CN'] as any).objects.showcase_task._views.in_progress.label).toBe('进行中'); + }); + + it('an unedited view still gets the catalog — every string', () => { + const out: any = translateView(clone(PACKAGED), BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); + expect(out.label).toBe('进行中'); + expect(out.description).toBe('正在处理的任务'); + expect(def(out, 'mark_done')).toMatchObject({ label: '标记完成', confirmText: '确定将所选任务标记为完成吗?', confirmLabel: '确认标记' }); + expect(param(out, 'mark_done', 'note')).toMatchObject({ label: '备注', help: '会显示在动态中', placeholder: '选填' }); + expect(def(out, 'skip').label).toBe('跳过'); + }); + + it("an org overlay's edited label is served — in zh-CN and in the source locale", () => { + const doc = clone(PACKAGED); + doc.label = 'In Progress (edited)'; + for (const locale of ['zh-CN', 'en']) { + const out: any = translateView(doc, BUNDLE, { locale, packagedBase: PACKAGED }); + expect(out.label, locale).toBe('In Progress (edited)'); + } + }); + + it('judges each string SEPARATELY — an edited label leaves the rest of the view translated', () => { + const doc = clone(PACKAGED); + doc.label = 'In Progress (edited)'; + const out: any = translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); + expect(out.description).toBe('正在处理的任务'); + expect(def(out, 'mark_done').label).toBe('标记完成'); + expect(param(out, 'mark_done', 'note').help).toBe('会显示在动态中'); + expect(def(out, 'skip').label).toBe('跳过'); + }); + + it('every translatable string follows the same rule — description, def label / confirm prompt / confirm button, param label / help / placeholder', () => { + const doc = clone(PACKAGED); + doc.description = 'Our open work'; + const markDone = def(doc, 'mark_done'); + markDone.label = 'Close out'; + markDone.confirmText = 'Close the selected tasks?'; + markDone.confirmLabel = 'Close them'; + const note = markDone.params[0]; + note.label = 'Closing note'; + note.help = 'Kept forever'; + note.placeholder = 'Say why'; + const out: any = translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); + expect(out.label).toBe('进行中'); + expect(out.description).toBe('Our open work'); + expect(def(out, 'mark_done')).toMatchObject({ label: 'Close out', confirmText: 'Close the selected tasks?', confirmLabel: 'Close them' }); + expect(param(out, 'mark_done', 'note')).toMatchObject({ label: 'Closing note', help: 'Kept forever', placeholder: 'Say why' }); + // The sibling def nobody edited is still translated. + expect(def(out, 'skip').label).toBe('跳过'); + }); + + it('a def or param the package does not ship was authored after the fact and keeps its strings', () => { + const doc = clone(PACKAGED); + doc.config.bulkActionDefs.push({ name: 'added_def', label: 'Added by the org', operation: 'update', patch: {} }); + def(doc, 'mark_done').params.push({ name: 'added', type: 'text', label: 'Added param' }); + const out: any = translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); + expect(def(out, 'added_def').label).toBe('Added by the org'); + expect(param(out, 'mark_done', 'added').label).toBe('Added param'); + expect(param(out, 'mark_done', 'note').label).toBe('备注'); + }); + + it('NO packaged base supplied → the pre-#20731 behaviour, catalog applies (the measured defect, as a control)', () => { + const doc = clone(PACKAGED); + doc.label = 'In Progress (edited)'; + expect(translateView(doc, BUNDLE, { locale: 'zh-CN' }).label).toBe('进行中'); + expect(translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: undefined }).label).toBe('进行中'); + expect(translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: null }).label).toBe('进行中'); + expect(translateView(doc, BUNDLE, { locale: 'en' }).label).toBe('In Progress'); + }); + + it('a reset (the served view equals the packaged one again) restores the translated shipped label', () => { + const edited = clone(PACKAGED); + edited.label = 'In Progress (edited)'; + expect(translateView(edited, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }).label).toBe('In Progress (edited)'); + const reset = clone(PACKAGED); + expect(translateView(reset, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }).label).toBe('进行中'); + expect(translateView(reset, BUNDLE, { locale: 'en', packagedBase: PACKAGED }).label).toBe('In Progress'); + }); + + it('the ruled edge — an edit back to exactly the shipped string is a no-op, and a non-string label is never an override', () => { + const same = clone(PACKAGED); + same.label = 'In Progress'; + expect(translateView(same, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }).label).toBe('进行中'); + // An inline locale map is the author's own multilingual route, not a + // diverged string — the comparison answers only for a string. + const map: any = clone(PACKAGED); + map.label = { en: 'Doing', 'zh-CN': '处理中' }; + expect(translateView(map, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }).label).toBe('进行中'); + }); + + it('an unedited sibling view stays translated when handed its OWN base', () => { + const urgent = packagedView('showcase_task.urgent'); + expect(translateView(clone(urgent), BUNDLE, { locale: 'zh-CN', packagedBase: urgent }).label).toBe('紧急'); + }); + + it('does not mutate either input document', () => { + const doc = clone(PACKAGED); + doc.label = 'In Progress (edited)'; + def(doc, 'mark_done').label = 'Close out'; + const before = clone(doc); + const packagedBefore = clone(PACKAGED); + translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); + expect(doc).toEqual(before); + expect(PACKAGED).toEqual(packagedBefore); + }); + + it('reaches the generic dispatcher — translateMetadataDocument carries the base for a view', () => { + // The serving layer never calls `translateView` directly; a base that + // stopped at the dispatcher would leave the defect exactly where it was. + const doc = clone(PACKAGED); + doc.label = 'In Progress (edited)'; + const out = translateMetadataDocument('view', doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); + expect(out.label).toBe('In Progress (edited)'); + expect(def(out, 'mark_done').label).toBe('标记完成'); + }); +}); + describe('ObjectTranslationDataSchema — _views..bulkActions (#14253)', () => { it('accepts the measured key face', () => { const data = ObjectTranslationDataSchema.parse({ diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index 7be4c844922..1e7995c1148 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -812,13 +812,21 @@ function lookupBulkActionText( * Reference identity is load-bearing rather than tidy: `translateView` uses it * to decide whether to rebuild `config` at all, so a view with no bulk * translations comes back with its config object untouched. + * + * `packagedConfig` is the `config` of the view's packaged base (`undefined` + * when no base was supplied, `{}` when the base carries none): each def and + * each param is found in it by the `name` the bundle addresses it by + * ({@link packagedPart}), and a string that diverged from its packaged + * counterpart is authored and keeps its value (#20731, see + * {@link translateView}). */ function translateBulkActionDefs( defs: unknown, bundle: TranslationBundle | undefined, objectName: string, viewKey: string, - opts?: ResolveOptions, + opts: ResolveOptions | undefined, + packagedConfig: Record | undefined, ): unknown { if (!Array.isArray(defs) || !bundle) return defs; let changed = false; @@ -828,12 +836,21 @@ function translateBulkActionDefs( return raw; } const defName = def.name; - const text = (pick: (node: NonNullable>) => unknown) => - lookupBulkActionText(bundle, objectName, viewKey, defName, pick, opts); - - const label = text((n) => n.label); - const confirmText = text((n) => n.confirmText); - const confirmLabel = text((n) => n.confirmLabel); + const packagedDef = packagedPart(packagedConfig, 'bulkActionDefs', (candidate) => candidate.name === defName); + // The catalog's string for `attr`, unless the authored value diverged from + // `packaged`'s — then `undefined`, which leaves the authored value in place. + const text = ( + packaged: Record | undefined, + attr: string, + authored: unknown, + pick: (node: NonNullable>) => unknown, + ) => valueOverridesPackagedBase(packaged, attr, authored) + ? undefined + : lookupBulkActionText(bundle, objectName, viewKey, defName, pick, opts); + + const label = text(packagedDef, 'label', def.label, (n) => n.label); + const confirmText = text(packagedDef, 'confirmText', def.confirmText, (n) => n.confirmText); + const confirmLabel = text(packagedDef, 'confirmLabel', def.confirmLabel, (n) => n.confirmLabel); let params = def.params; if (Array.isArray(def.params)) { @@ -843,9 +860,10 @@ function translateBulkActionDefs( return param; } const paramName = param.name; - const pLabel = text((n) => n.params?.[paramName]?.label); - const pHelp = text((n) => n.params?.[paramName]?.help); - const pPlaceholder = text((n) => n.params?.[paramName]?.placeholder); + const packagedParam = packagedPart(packagedDef, 'params', (candidate) => candidate.name === paramName); + const pLabel = text(packagedParam, 'label', param.label, (n) => n.params?.[paramName]?.label); + const pHelp = text(packagedParam, 'help', param.help, (n) => n.params?.[paramName]?.help); + const pPlaceholder = text(packagedParam, 'placeholder', param.placeholder, (n) => n.params?.[paramName]?.placeholder); if (pLabel === undefined && pHelp === undefined && pPlaceholder === undefined) return param; paramsChanged = true; return { @@ -902,24 +920,61 @@ function translateBulkActionDefs( * `expandViewContainer` put the whole `ListViewSchema` under `config`. The * object is rebuilt only when a def actually gained a translation, so a view * with none comes back with the very same `config` reference. + * + * ## [#20731] The catalog LOSES to an explicit override — ADR-0029 D9.2a + * + * The catalog (`objects.._views.`) is the packaged + * translation of the PACKAGED view. Consulting it first overwrote every + * string authored on top of that view — measured: an org overlay on the + * showcase's packaged `showcase_task.in_progress` (ADR-0126 Regime O, "yours + * to edit directly") changed its label to `In Progress (edited-20680)`, the + * metadata protocol's item and list reads both served the edit, an `en` + * reader got it, and a `zh-CN` reader — admin or member, item or list — got + * `进行中`, the catalog's translation of the label the package shipped. + * + * So every string here follows the rule {@link translateDashboard} and + * {@link translateObject} follow, by the same comparison + * ({@link valueOverridesPackagedBase}; ⛔ never a second one): the catalog + * applies only while the served value still equals the one in + * {@link TranslateDocumentOptions.packagedBase}, which the serving layer + * supplies — the packaged view before any tenant overlay, + * `getPackagedViewBase` on the metadata protocol, looked up by the served + * view's registry identity (the qualified `.` name, never the + * bare key the catalog uses, which another object's view may share). The view + * `label` and `description` are judged against the base's; each bulk-action + * def's `label` / `confirmText` / `confirmLabel` and each of its params' + * `label` / `help` / `placeholder` against the def and param the base carries + * under the same `name` — the key the bundle addresses them by — and a def or + * param the base does not carry was authored after the fact and counts as + * diverged. No base supplied is the pre-#20731 behaviour, unchanged: the + * catalog applies. */ export function translateView( view: T, bundle: TranslationBundle | undefined, - opts?: ResolveOptions, + opts?: TranslateDocumentOptions, ): T { - const label = resolveViewLabel(bundle, view, opts); - const description = resolveViewDescription(bundle, view, opts); + const base = asRecord(opts?.packagedBase); + const label = valueOverridesPackagedBase(base, 'label', view.label) + ? (view.label as string) + : resolveViewLabel(bundle, view, opts); + const description = valueOverridesPackagedBase(base, 'description', view.description) + ? view.description + : resolveViewDescription(bundle, view, opts); let config = view.config; const objectName = viewObjectName(view); if (config && typeof config === 'object' && bundle && objectName) { + // The base's own `config` — `{}` when the base is known but carries none, + // so every def on the served view then counts as authored. + const packagedConfig = base === undefined ? undefined : asRecord(base.config) ?? {}; const defs = translateBulkActionDefs( config.bulkActionDefs, bundle, objectName, viewTranslationKey(view, objectName), opts, + packagedConfig, ); if (defs !== config.bulkActionDefs) config = { ...config, bulkActionDefs: defs }; } @@ -1240,9 +1295,10 @@ function isOptionValue(value: unknown): value is string | number | boolean { } /** - * [#20680] The packaged counterpart of one addressable part of a dashboard — - * a widget, a global filter, a filter option — found in `parent[key]` (an - * array) by the key the bundle addresses it by. + * [#20680] The packaged counterpart of one addressable part of a translated + * document — a dashboard's widget, global filter or filter option; a view's + * bulk-action def or its param (#20731) — found in `parent[key]` (an array) by + * the key the bundle addresses it by. * * Three answers, and the difference between the first two is the point: * @@ -1254,10 +1310,13 @@ function isOptionValue(value: unknown): value is string | number | boolean { * it counts as diverged, as a scalar the packaged object never declared * does under #8284; * - the packaged part itself otherwise. + * + * One finder for both translators ({@link translateDashboard}, + * {@link translateView}), as there is one comparison behind them. */ -function packagedDashboardPart( +function packagedPart( parent: Record | undefined, - key: 'widgets' | 'globalFilters' | 'options', + key: 'widgets' | 'globalFilters' | 'options' | 'bulkActionDefs' | 'params', matches: (candidate: Record) => boolean, ): Record | undefined { if (parent === undefined) return undefined; @@ -1278,7 +1337,7 @@ function packagedDashboardPart( * moved. * * `packagedFilter` is the same filter in the dashboard's packaged base - * ({@link packagedDashboardPart}); a label that diverged from it is authored + * ({@link packagedPart}); a label that diverged from it is authored * and keeps its value (#20680, see {@link translateDashboard}). */ function translateGlobalFilter( @@ -1307,7 +1366,7 @@ function translateGlobalFilter( // is the one spelling every value has; `null`/`undefined`/objects have // no such spelling and are left alone. if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') return option; - const packagedOption = packagedDashboardPart( + const packagedOption = packagedPart( packagedFilter, 'options', (candidate) => isOptionValue(candidate.value) && String(candidate.value) === String(value), @@ -1427,7 +1486,7 @@ export function translateDashboard( const rebuilt = doc.globalFilters.map((filter) => { if (!filter || typeof filter !== 'object') return filter; const key = globalFilterKey(filter); - const packagedFilter = packagedDashboardPart( + const packagedFilter = packagedPart( base, 'globalFilters', (candidate) => key !== undefined && globalFilterKey(candidate) === key, @@ -1443,7 +1502,7 @@ export function translateDashboard( ? doc.widgets.map((w) => { if (!w || typeof w !== 'object' || typeof w.id !== 'string') return w; const next: WidgetLike = { ...w }; - const packagedWidget = packagedDashboardPart(base, 'widgets', (candidate) => candidate.id === w.id); + const packagedWidget = packagedPart(base, 'widgets', (candidate) => candidate.id === w.id); const title = valueOverridesPackagedBase(packagedWidget, 'title', w.title) ? undefined : lookupWidgetAttr(bundle, name, w.id, 'title', opts); @@ -2650,9 +2709,11 @@ export function scalarOverridesPackagedBase( * keyed by any attribute name — the exported predicate's key union names the * object scalars its two callers ask about, and the dashboard translator * ({@link translateDashboard}) asks the same question of `title`, which that - * union does not carry. One implementation, so the three conservative edges - * documented on the exported predicate hold for every caller alike; ⛔ never - * a second copy of the comparison. + * union does not carry; the view translator ({@link translateView}, #20731) + * asks it of a bulk-action def's `confirmText` and its params' `help`. One + * implementation, so the three conservative edges documented on the exported + * predicate hold for every caller alike; ⛔ never a second copy of the + * comparison. */ function valueOverridesPackagedBase(base: unknown, key: string, value: unknown): boolean { if (!base || typeof base !== 'object') return false; diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index a43f4becd1b..4bb56cdbcba 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -2086,6 +2086,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/objectql/src/protocol-packaged-view-base.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/objectql/src/protocol-publish-package-drafts.test.ts", "verb": "update",