diff --git a/.changeset/29673-translated-echo-save-door.md b/.changeset/29673-translated-echo-save-door.md new file mode 100644 index 00000000000..363566465cb --- /dev/null +++ b/.changeset/29673-translated-echo-save-door.md @@ -0,0 +1,24 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/objectql': patch +'@objectstack/spec': patch +--- + +fix(metadata-protocol)!: an object saved back from a translated `/meta` read stores its source labels, and an object the registry would refuse is refused at save and at publish, never reported published (#29673) + +Clause-②: no (narrowing) — the object save door (`saveMetaItem`, draft and live) refuses `422 INVALID_METADATA` an object declaring its own `queue` field on a user-owned object (ADR-0142 D3), which it stored before and the registry then refused to register; the publish promote refuses such a draft the same way. A label equal to what the `/meta` read serves for its source in some locale is stored as the source text. Nothing is widened. +Metadata-protocol: none +Skills-docs: none — `skills/objectstack-data/SKILL.md` (Ownership queues) already teaches that an object declaring its own `queue` field is refused, which stays true and is now said at save; no file under `skills/**` teaches saving a translated read back. + + + +**BREAKING** accept-set narrowing at the object save door (`@objectstack/metadata-protocol`), served by `PUT /api/v1/meta/object/:name` (draft and live) and `POST /api/v1/packages/:id/publish-drafts`. + +- **Before.** A `/meta` read in a non-English locale serves each injected system column with a translated label (`queue` → `队列`, `owner_id` → `负责人`). Studio saves the whole body it read, so the save stored those columns back as the author's own fields. For `queue` the registry then refused the object at publish, the refusal went to a log line, and `publish-drafts` answered `outcome: 'published'` while the object's data door answered 404. For `owner_id` and the other columns, every other locale was served the Chinese label. +- **Now.** + - The save door puts a slot back to its source text when the incoming value differs from the source and equals what the read's translator makes of that source in some locale, translating with the read's own options (a packaged object's overlay slot that diverged from the packaged text is served untranslated, so it is no translation's source). The source is the stored row the save overwrites, then the platform's own definition of an injected column. The strip that follows then removes the platform's columns as it always did. Slots: an object's `label`, `pluralLabel` and `description`; a field's `label`, `description`, `inlineHelpText` and `inlineTitle`; an option's `label`. + - The save door asks the registry whether it would register the object, judging the body alone, and refuses what it would not, in both modes. The publish promote asks again, before anything is promoted, so a draft stored before this rule is refused and not reported published. The only refusal this makes new at the door is an author's own `queue`; a field `type` the registry refuses was already refused at save by the object schema. The record-currency `summary` door is left to the registration, since it judges the body against the other objects as they stand and a sibling in the same batch can change that answer either way. + - `os migrate meta --stored` reports a stored object row carrying a translated label as `translated-label-echo` and, with `--apply`, re-saves it through the save door. +- **Unchanged.** A label that is not a translation of its source is the author's edit and is kept. A field the source does not declare is not compared. An English body is stored as before. +- **The edge.** An author who types exactly the translation of a label's source in some locale gets the source back; a reader in that locale is served the translation anyway. +- **New export.** `BUILTIN_SYSTEM_FIELD_LABEL_LOCALES` (`@objectstack/spec/system`): the locales the built-in system-field label table answers in, with no bundle. `SchemaRegistry.objectRegistrationRefusal` (`@objectstack/objectql`) answers the refusal `registerObject` would throw judging the body alone (every door but the record-currency `summary` one), without registering anything. diff --git a/packages/metadata-protocol/src/protocol-translated-echo.test.ts b/packages/metadata-protocol/src/protocol-translated-echo.test.ts new file mode 100644 index 00000000000..ae3798f401c --- /dev/null +++ b/packages/metadata-protocol/src/protocol-translated-echo.test.ts @@ -0,0 +1,134 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#29673] `restoreTranslatedEchoes` — the save door's inverse of the `/meta` + * read's translation, as a pure function. The echo every case hands it is + * built with the spec translator the read exits call, so a case can only pass + * when the inverse matches what a read really serves. + * + * The door end to end (the real registry, the real protocol, the publish and + * the stored-row repair) is pinned in `@objectstack/objectql`'s + * `protocol-meta-effective-schema.test.ts`. + */ + +import { describe, it, expect } from 'vitest'; +import { translateObject, type TranslationBundle } from '@objectstack/spec/system'; +import { QUEUE_FIELD_DEF, OWNER_FIELD_DEF } from '@objectstack/spec/data'; +import { restoreTranslatedEchoes, translatedEchoLocales } from './protocol-translated-echo.js'; + +const bundle: TranslationBundle = { + 'zh-CN': { + objects: { + crm_invoice: { + label: '发票', + fields: { + amount: { label: '金额' }, + status: { label: '状态', options: { open: '打开', closed: '关闭' } }, + }, + }, + }, + }, +} as unknown as TranslationBundle; + +/** The source a stored row carries. */ +const stored = () => ({ + name: 'crm_invoice', + label: 'Invoice', + sharingModel: 'private', + fields: { + amount: { type: 'currency', label: 'Amount' }, + status: { type: 'select', label: 'Status', options: [{ value: 'open', label: 'Open' }, { value: 'closed', label: 'Closed' }] }, + }, +}); + +/** What a read serves in `locale`: the stored row plus the injected columns, translated. */ +const read = (locale: string, b: TranslationBundle | undefined = bundle): any => { + const doc: any = stored(); + doc.fields = { ...doc.fields, queue: { ...QUEUE_FIELD_DEF }, owner_id: { ...OWNER_FIELD_DEF } }; + return translateObject(doc, b, { locale }); +}; + +describe('[#29673] restoreTranslatedEchoes', () => { + it('a zh-CN echo is put back to the source on every slot the read translated', () => { + const echo = read('zh-CN'); + // The precondition: the read really translated each slot. + expect([echo.label, echo.fields.amount.label, echo.fields.status.options[0].label, echo.fields.queue.label, echo.fields.owner_id.label]) + .toEqual(['发票', '金额', '打开', '队列', '负责人']); + const { item, restored } = restoreTranslatedEchoes(echo, { source: stored(), bundle }); + expect(item.label).toBe('Invoice'); + expect(item.fields.amount.label).toBe('Amount'); + expect(item.fields.status.label).toBe('Status'); + expect(item.fields.status.options.map((o: any) => o.label)).toEqual(['Open', 'Closed']); + // The injected columns are the platform's own again, byte for byte: the strip that follows removes them. + expect(item.fields.queue).toEqual(QUEUE_FIELD_DEF); + expect(item.fields.owner_id).toEqual(OWNER_FIELD_DEF); + expect(restored.map((r) => r.path).sort()).toEqual([ + 'fields.amount.label', 'fields.owner_id.label', 'fields.queue.label', + 'fields.status.label', 'fields.status.options[closed].label', 'fields.status.options[open].label', 'label', + ]); + }); + + it('a built-in locale with no bundle at all is recognised (the read translates injected columns without one)', () => { + expect(translatedEchoLocales(undefined)).toEqual(expect.arrayContaining(['zh-CN', 'ja-JP', 'es-ES'])); + const echo = read('ja-JP', undefined); + expect(echo.fields.queue.label).toBe('キュー'); + const { item } = restoreTranslatedEchoes(echo, { source: stored(), bundle: undefined }); + expect(item.fields.queue).toEqual(QUEUE_FIELD_DEF); + }); + + it('the author\'s own text is kept: an edit that is not a translation, a new field, an own owner_id label', () => { + const echo = read('zh-CN'); + echo.fields.amount.label = 'Total'; + echo.fields.memo = { type: 'text', label: '备注' }; + echo.fields.owner_id = { ...OWNER_FIELD_DEF, label: 'Account Owner' }; + const source: any = stored(); + source.fields.owner_id = { ...OWNER_FIELD_DEF, label: 'Account Owner' }; + const { item } = restoreTranslatedEchoes(echo, { source, bundle }); + expect(item.fields.amount.label).toBe('Total'); + expect(item.fields.memo.label).toBe('备注'); + expect(item.fields.owner_id.label).toBe('Account Owner'); + }); + + it('a row that already stored the echo is repaired against the platform\'s definition', () => { + const echo = read('zh-CN'); + // The stored row IS the echo (a zh-CN session saved it before this door existed). + const { item } = restoreTranslatedEchoes(echo, { source: echo, bundle }); + expect(item.fields.queue).toEqual(QUEUE_FIELD_DEF); + expect(item.fields.owner_id).toEqual(OWNER_FIELD_DEF); + }); + + it('the array `fields` shape is restored in place, and an untranslated body comes back as the same reference', () => { + const echo = read('zh-CN'); + const asArray = { ...echo, fields: Object.entries(echo.fields).map(([name, f]: [string, any]) => ({ name, ...f })) }; + const { item } = restoreTranslatedEchoes(asArray, { source: stored(), bundle }); + expect(item.fields.map((f: any) => f.name)).toEqual(asArray.fields.map((f: any) => f.name)); + expect(item.fields.find((f: any) => f.name === 'amount').label).toBe('Amount'); + + const untouched = read('en'); + const same = restoreTranslatedEchoes(untouched, { source: stored(), bundle }); + expect(same.item).toBe(untouched); + expect(same.restored).toEqual([]); + }); + + it('a packaged object\'s overlay slot that diverged from the packaged text is no translation\'s source: the catalog string an author types is kept', () => { + // The packaged base ships `amount: Amount`; the catalog translates that + // packaged text. The tenant's overlay renamed it `Total`, which the read + // serves untranslated in every locale (ADR-0029 D9.2a). + const packagedBase = stored(); + const overlay: any = stored(); + overlay.fields.amount = { ...overlay.fields.amount, label: 'Total' }; + // The precondition: the read, with the packaged base, serves `Total` in zh-CN. + expect((translateObject(overlay, bundle, { locale: 'zh-CN', packagedBase }) as any).fields.amount.label).toBe('Total'); + + const typed: any = stored(); + typed.fields.amount = { ...typed.fields.amount, label: '金额' }; + const kept = restoreTranslatedEchoes(typed, { source: overlay, bundle, packagedBase }); + expect(kept.item.fields.amount.label).toBe('金额'); + expect(kept.restored).toEqual([]); + + // Control: the same typed string over a slot that still equals the + // packaged text IS the read's translation, and is put back. + const echoed = restoreTranslatedEchoes(typed, { source: packagedBase, bundle, packagedBase }); + expect(echoed.item.fields.amount.label).toBe('Amount'); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-translated-echo.ts b/packages/metadata-protocol/src/protocol-translated-echo.ts new file mode 100644 index 00000000000..49b98ea0eb4 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-translated-echo.ts @@ -0,0 +1,332 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The write door's inverse of the `/meta` read's TRANSLATION: an object body + * that comes back carrying a label the read translated is stored with the + * source text, never with the translation. + * + * ## Why the write door owes this + * + * A `/meta` read of an object is translated for the caller's locale on its way + * out (the REST read exits run `translateMetadataDocument` from + * `@objectstack/spec/system`): a field label the bundle carries an entry for, + * and every injected system column's label through the built-in table, is + * served in the caller's language. Studio edits by GET → edit → PUT of the + * WHOLE body, and the write path persists the body verbatim (ADR-0005 appendix + * (c)), so a zh-CN session stored the translation as the document: + * + * - an injected column is no longer byte-identical to the platform's + * definition, so `stripInjectedSystemColumns` keeps it as the AUTHOR's own + * field. For `queue` that is a refusal: the registry refuses an author's + * `queue` on a user-owned object, so the object never registered and its + * data door answered 404 after a publish that said it succeeded. For + * `owner_id` and the others it is a silent change of what every other + * locale reads: the stored label is the author's now, so the translator + * yields to it and an `en` reader is served `负责人`. + * - an author's field the catalog translates stores the translation as its + * own label, which the catalog then can no longer translate for anyone. + * + * Its siblings on the same door, for the same reason: the read decorations + * (`stripReadDecorations`), the derived provenance keys + * (`stripDerivedProvenance`) and the injected columns themselves + * (`stripServedObjectColumns`) — what the READ adds comes off again on the way + * in. This one runs first, so the strip that follows sees the platform's own + * definition again and removes it. + * + * ## The rule — comparison against the source the read translated + * + * A slot is restored when, and only when, the incoming value differs from the + * SOURCE value and equals what the translator makes of that source in some + * locale. The source is the field's definition before the read translated it: + * + * - the stored row this save overwrites (the draft, or the active row a first + * draft overlays — the baseline the credential carry-forward reads); then + * - for an injected column, the platform's own definition, exactly as the + * read's `applyInjectedSystemColumns` adds it. Asked second, and also when + * the stored row declares the column: a row a zh-CN session already stored + * carries the echo itself, so compared with itself nothing differs, and + * compared with the platform's `queue` its label is `队列` for `Queue`. That + * is what lets the next save of such a row — and the stored-row migration, + * which re-saves through this door — repair it. + * + * The locales tried are every one the read could have answered in: the + * bundle's, and the built-in system-field table's + * (`BUILTIN_SYSTEM_FIELD_LABEL_LOCALES`), which the read applies with no + * bundle at all. A request locale matches one of those or translates nothing. + * + * It is the same comparison-based provenance the translator itself applies + * (`scalarOverridesPackagedBase`, ADR-0029 D9.2a), run backwards, and its edge + * is the same: an author who deliberately types exactly the translation of + * the source in some locale gets the source back — which the reader in that + * locale is served anyway, since the catalog translates it. Nothing else is + * touched: a label that is not a translation of its source is the author's + * edit and is kept, and a field the source does not declare has nothing to + * be compared with. + * + * The source is translated with the read's own options, the packaged base + * included: a slot the read serves untranslated (an overlay that diverged + * from the packaged text) is no translation's source. + * + * Pure: no store, no service. The caller hands in the source row, the + * bundle and the packaged base. + */ + +import type { RuntimeAuthoringIssue } from '@objectstack/spec/api'; +import { injectedSystemColumnDefs } from '@objectstack/spec/data'; +import { + BUILTIN_SYSTEM_FIELD_LABEL_LOCALES, + translateObject, + type ObjectLike, + type TranslationBundle, +} from '@objectstack/spec/system'; + +/** + * The `conversionId` the stored-row migration (`migrateStoredMetadata`) files + * a restored slot under. Not an ADR-0087 `MetadataConversion`: no stored + * spelling is retired here, the row simply carries a value the save door now + * keeps out — the same standing the `registerFlow` id has on a flow row's + * TODOs. + */ +export const TRANSLATED_ECHO_NOTICE_ID = 'translated-label-echo'; + +/** One slot the door put back to its source text. */ +export interface RestoredTranslatedSlot { + /** Where, e.g. `fields.queue.label` or `fields.status.options[open].label`. */ + path: string; + /** The translation the body carried. */ + from: string; + /** The source text stored instead (`undefined` when the source has no such slot). */ + to: string | undefined; +} + +/** + * One `info` advisory per author slot a save put back to its source text, for + * the save answer's `advisories` — beside the credential carry-forward's + * `withheld-key-dropped` notices on the same door. The `path` is the object + * write's name-keyed one (`objects.NAME.fields.F.label`). The platform's + * injected columns are not reported: the stored document never carries them. + */ +export function translatedEchoNotices(name: string, restored: readonly RestoredTranslatedSlot[]): RuntimeAuthoringIssue[] { + return restored.map((slot) => ({ + rule: TRANSLATED_ECHO_NOTICE_ID, + severity: 'info' as const, + where: `object "${name}"`, + path: `objects.${name}.${slot.path}`, + message: slot.to === undefined + ? `this save left '${slot.path}' unset rather than storing '${slot.from}': that is what a /meta read serves for it in another language, translated from the source, which sets no text there.` + : `this save stored '${slot.to}' at '${slot.path}', not '${slot.from}': '${slot.from}' is what a /meta read serves for '${slot.to}' in another language, so it is the read's translation, not the document.`, + hint: 'Readers in that language are served the translation from the catalog. To change the text itself, edit it in the source language, or change the catalog entry.', + })); +} + +/** The field slots the object translator writes. */ +const FIELD_TEXT_SLOTS = ['label', 'description', 'inlineHelpText', 'inlineTitle'] as const; +/** The object scalars the object translator writes. */ +const OBJECT_TEXT_SLOTS = ['label', 'pluralLabel', 'description'] as const; + +type Rec = Record; + +/** + * A slot read off a source that does not declare the field (or option) at + * all: a sentinel no incoming string can equal, so that source explains + * nothing about it. + */ +const NOT_DECLARED: unique symbol = Symbol('not-declared'); + +function isRec(value: unknown): value is Rec { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** A document's `fields` as `name -> definition`, from either the record or the array shape. */ +function fieldMap(doc: unknown): Map { + const out = new Map(); + if (!isRec(doc)) return out; + const fields = doc.fields; + if (Array.isArray(fields)) { + for (const f of fields) if (isRec(f) && typeof f.name === 'string') out.set(f.name, f); + } else if (isRec(fields)) { + for (const [name, f] of Object.entries(fields)) if (isRec(f)) out.set(name, f); + } + return out; +} + +function optionKey(option: unknown): string | undefined { + if (!isRec(option)) return undefined; + const v = option.value; + return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ? String(v) : undefined; +} + +function optionLabel(options: unknown, key: string): unknown { + return Array.isArray(options) ? (options.find((o) => optionKey(o) === key) as Rec | undefined)?.label : undefined; +} + +/** + * The locales a read could have translated into: the bundle's own, then the + * built-in system-field table's. Order is irrelevant to the verdict. + */ +export function translatedEchoLocales(bundle: TranslationBundle | undefined): string[] { + return [...new Set([...Object.keys(bundle ?? {}), ...BUILTIN_SYSTEM_FIELD_LABEL_LOCALES])]; +} + +/** + * One source document and what every locale's read made of it: `fields` holds + * only the names the incoming body declares. + */ +interface TranslatedSource { + doc: Rec; + fields: Map; + reads: Array<{ doc: Rec; fields: Map }>; +} + +function translatedSource( + doc: Rec, + locales: readonly string[], + bundle: TranslationBundle | undefined, + packagedBase: unknown, +): TranslatedSource { + return { + doc, + fields: fieldMap(doc), + reads: locales.map((locale) => { + // The read's own options: with the packaged base, a slot that + // diverged from the packaged text is served untranslated in every + // locale (ADR-0029 D9.2a), so it is no translation's source here + // either. + const read = translateObject(doc as unknown as ObjectLike, bundle, { + locale, + ...(packagedBase !== undefined && packagedBase !== null ? { packagedBase } : {}), + }) as unknown as Rec; + return { doc: read, fields: fieldMap(read) }; + }), + }; +} + +/** + * Put every translated slot of `item` back to its source text. Returns the + * SAME reference when nothing was restored. See the module header. + * + * Two sources, asked in order, the first that explains the value wins: the + * stored row's own declaration, then — for an injected column — the + * platform's definition. The second is what heals a row a zh-CN session + * already stored: its `queue` declaration IS the translation, so compared + * with itself nothing differs, while compared with the platform's `queue` the + * label is `队列` for `Queue`. + */ +export function restoreTranslatedEchoes( + item: T, + args: { + source: unknown; + bundle: TranslationBundle | undefined; + /** + * The packaged base the `/meta` read translates against (the code + * layer of a packaged object), passed through as `translateObject`'s + * `packagedBase`. Without it, a stored overlay slot that diverged from + * the packaged text (`Title` renamed `Subject`) would read as + * translated to the catalog's entry for the packaged text (`标题`), and + * an author typing exactly that would be put back to `Subject`. Absent + * for an object no package ships. + */ + packagedBase?: unknown; + }, +): { item: T; restored: RestoredTranslatedSlot[] } { + const restored: RestoredTranslatedSlot[] = []; + if (!isRec(item) || typeof item.name !== 'string') return { item, restored }; + const incoming = fieldMap(item); + const locales = translatedEchoLocales(args.bundle); + + const storedFields = fieldMap(args.source); + const storedDoc: Rec = { name: item.name, fields: {} }; + for (const name of incoming.keys()) { + const def = storedFields.get(name); + if (def) (storedDoc.fields as Rec)[name] = { ...def }; + } + if (isRec(args.source)) { + for (const slot of OBJECT_TEXT_SLOTS) { + if (typeof args.source[slot] === 'string') storedDoc[slot] = args.source[slot]; + } + } + const injectedDoc: Rec = { name: item.name, fields: {} }; + for (const [name, def] of Object.entries(injectedSystemColumnDefs(item))) { + if (incoming.has(name)) (injectedDoc.fields as Rec)[name] = { ...def }; + } + const sources = [storedDoc, injectedDoc] + .filter((doc) => Object.keys(doc.fields as Rec).length > 0 || Object.keys(doc).length > 2) + .map((doc) => translatedSource(doc, locales, args.bundle, args.packagedBase)); + if (sources.length === 0) return { item, restored }; + + /** + * The source text `value` is a translation of, through `pick` (which reads + * one slot off a source document or a read of it, {@link NOT_DECLARED} + * where that source does not declare it); `null` when no source explains + * it. A source the value equals explains nothing and the next is asked: + * that is the stored echo meeting the platform's definition. + */ + const sourceOf = (value: unknown, pick: (doc: Rec, fields: Map) => unknown): { to: unknown } | null => { + if (typeof value !== 'string') return null; + for (const source of sources) { + const original = pick(source.doc, source.fields); + if (original === NOT_DECLARED || original === value) continue; + if (source.reads.some((read) => { + const translated = pick(read.doc, read.fields); + return translated !== original && translated === value; + })) return { to: original }; + } + return null; + }; + + let nextItem: Rec = item; + for (const slot of OBJECT_TEXT_SLOTS) { + const hit = sourceOf(item[slot], (doc) => (typeof doc[slot] === 'string' ? doc[slot] : NOT_DECLARED)); + if (!hit || typeof hit.to !== 'string') continue; + restored.push({ path: slot, from: item[slot] as string, to: hit.to }); + nextItem = nextItem === item ? { ...item } : nextItem; + nextItem[slot] = hit.to; + } + + const nextFields = new Map(); + for (const [name, field] of incoming) { + if (!sources.some((source) => source.fields.has(name))) continue; + let next: Rec = field; + for (const slot of FIELD_TEXT_SLOTS) { + const hit = sourceOf(field[slot], (_doc, fields) => { + const f = fields.get(name); + return f ? f[slot] : NOT_DECLARED; + }); + if (!hit) continue; + restored.push({ path: `fields.${name}.${slot}`, from: field[slot] as string, to: hit.to as string | undefined }); + next = next === field ? { ...field } : next; + if (hit.to === undefined) delete next[slot]; + else next[slot] = hit.to; + } + if (Array.isArray(field.options)) { + let options: unknown[] | undefined; + field.options.forEach((option, index) => { + const key = optionKey(option); + if (key === undefined || !isRec(option)) return; + const hit = sourceOf(option.label, (_doc, fields) => { + const f = fields.get(name); + return f ? optionLabel(f.options, key) ?? NOT_DECLARED : NOT_DECLARED; + }); + if (!hit || typeof hit.to !== 'string') return; + restored.push({ path: `fields.${name}.options[${key}].label`, from: option.label as string, to: hit.to }); + options ??= [...(field.options as unknown[])]; + options[index] = { ...option, label: hit.to }; + }); + if (options) { + next = next === field ? { ...field } : next; + next.options = options; + } + } + if (next !== field) nextFields.set(name, next); + } + + if (nextFields.size > 0) { + nextItem = nextItem === item ? { ...item } : nextItem; + const fields = item.fields; + nextItem.fields = Array.isArray(fields) + ? fields.map((f) => (isRec(f) && typeof f.name === 'string' && nextFields.get(f.name)) || f) + : Object.fromEntries(Object.entries(fields as Rec).map(([name, f]) => [name, nextFields.get(name) ?? f])); + } + return { item: nextItem as T, restored }; +} + diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 9c7faba87bb..fe0c220b086 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -142,7 +142,13 @@ import { type I18nLabel, isAggregatedViewContainer, expandViewContainer } from ' // (curated entry, unchanged). import { type FormFieldInput } from '@objectstack/spec/ui'; export type { FormFieldInput }; -import { CORE_SERVICE_PROVIDER, serviceUnavailableMessage } from '@objectstack/spec/system'; +import { CORE_SERVICE_PROVIDER, serviceUnavailableMessage, type TranslationBundle } from '@objectstack/spec/system'; +import { + restoreTranslatedEchoes, + translatedEchoNotices, + TRANSLATED_ECHO_NOTICE_ID, + type RestoredTranslatedSlot, +} from './protocol-translated-echo.js'; import { DEFAULT_METADATA_TYPE_REGISTRY, getMetadataTypeSchema, getMetadataTypeActions, getMetadataCreateSeed, PROTOCOL_VERSION } from '@objectstack/spec/kernel'; import { resolveLockState, @@ -3763,6 +3769,125 @@ export class ObjectStackProtocolImplementation implements return (stripServedObjectColumns).call(host, type, item); } + /** + * [#29673] The refusal `registerObject` would throw for this object body, + * registered as the write-through registers it + * ({@link applyObjectRegistryMutation}: `_provenance: 'org'`, the layer's + * package and kind) — asked of the registry's own doors + * (`SchemaRegistry.objectRegistrationRefusal`), so a door that makes the + * body live refuses it before the row is written instead of meeting the + * throw after. `null` when the registry would take it, when the layer is a + * D9.9 `mismatch` (that refusal is the caller's own, asked first), and on + * a registry that cannot answer the question (a partial double). + */ + private objectRegistrationRefusal( + body: unknown, + layer: ReturnType, + ): Error | null { + if (layer.kind === 'mismatch') return null; + const registry = this.engine?.registry as { objectRegistrationRefusal?: (...args: unknown[]) => Error | null } | undefined; + if (typeof registry?.objectRegistrationRefusal !== 'function') return null; + if (!body || typeof body !== 'object' || Array.isArray(body)) return null; + return registry.objectRegistrationRefusal( + { ...(body as Record), _provenance: 'org' }, + layer.packageId, + layer.kind, + ); + } + + /** + * [#29673] The write-path inverse of the `/meta` read's translation, for an + * `object` body: every label the read served translated is put back to its + * source text before the body is stored ({@link restoreTranslatedEchoes}, + * whose module header is the contract). Its pure half, + * {@link restoreInjectedColumnEchoes}, already ran before the served-column + * strip; this half reads the stored row, so it runs after every refusal. + * + * The source is the row this save overwrites, read as the credential + * carry-forward reads it ({@link storedBodyForCarryForward}: the row at the + * save's own state, else the active row a first draft overlays), and with + * no stored row the packaged base (`getPackagedObjectBase`) in place of + * the carry-forward's code-layer read. Every read of the source is + * translated against that packaged base, as the REST read's is, so a slot + * the read serves untranslated is no translation's source. The locales are + * the bundle's and the built-in system-field table's — every locale a read + * could have answered in. Each restored slot is answered on the save's + * `advisories` ({@link translatedEchoNotices}). + * + * Every save is asked, the stored-row migration included + * (`source: 'migrate-stored'`): it re-saves a row through this door, which + * is how a row a zh-CN session already stored is repaired. Any other + * type's body is returned as it came. No `try`/`catch`: a failed stored-row + * read fails the save rather than storing a body this door could not judge; + * the packaged base is a registry lookup, so a degraded MetadataService + * fails nothing here. + */ + private async restoreTranslatedObjectEchoes( + request: SaveMetaItemRequest, + repo: SysMetadataRepository, + ref: Parameters[0], + mode: 'draft' | 'publish', + ): Promise<{ item: SaveMetaItemRequest['item']; restored: RestoredTranslatedSlot[] }> { + if (canonicalMetaType(request.type) !== 'object') return { item: request.item, restored: [] }; + if (!request.item || typeof request.item !== 'object' || Array.isArray(request.item)) { + return { item: request.item, restored: [] }; + } + // The packaged base the read translates against (`getPackagedObjectBase`, + // what the REST read hands `translateObject` as `packagedBase`), and, + // with no stored row, the source itself: the body a read of an object + // with no overlay served. A registry lookup, never a MetadataService + // read — so a degraded service fails no save here (a brand-new object + // has no source beyond the platform columns the pure half handled). + const packagedBase = this.getPackagedObjectBase(request.name); + const source = await storedBodyForCarryForward.call( + { readCodeLayerForCarryForward: async () => packagedBase }, + { + type: 'object', + repo, + ref, + state: mode === 'draft' ? 'draft' : 'active', + packageId: request.packageId ?? null, + }, + ); + return restoreTranslatedEchoes(request.item, { + source, + bundle: this.registeredTranslationBundle(), + packagedBase: packagedBase ?? undefined, + }); + } + + /** + * [#29673] The pure half of {@link restoreTranslatedObjectEchoes}, run + * before the served-column strip: each injected column's slots compared + * with the platform's own definition only (no stored row, so no read). + * A column that came back translated is the platform's definition again, + * and the strip removes it. + */ + private restoreInjectedColumnEchoes(request: SaveMetaItemRequest): SaveMetaItemRequest['item'] { + if (canonicalMetaType(request.type) !== 'object') return request.item; + if (!request.item || typeof request.item !== 'object' || Array.isArray(request.item)) return request.item; + return restoreTranslatedEchoes(request.item, { source: undefined, bundle: this.registeredTranslationBundle() }).item; + } + + /** + * [#29673] The registered i18n service's catalog as a `TranslationBundle` + * (`locale -> data`), or `undefined` when no service or no locale is + * registered — the bundle the `/meta` read exits translate with + * (`translationBundleOf` in `@objectstack/rest`, built the same way). + */ + private registeredTranslationBundle(): TranslationBundle | undefined { + const service: any = this.getServicesRegistry?.().get('i18n'); + if (!service || typeof service.getLocales !== 'function' || typeof service.getTranslations !== 'function') { + return undefined; + } + const bundle: Record = {}; + for (const locale of service.getLocales() as string[]) { + const data = service.getTranslations(locale); + if (data && typeof data === 'object') bundle[locale] = data; + } + return Object.keys(bundle).length > 0 ? (bundle as TranslationBundle) : undefined; + } + /** * [#8154] The write-path counterpart the read exits' credential redaction * owes, in the same sense {@link stripServedObjectColumns} is owed to @@ -13365,6 +13490,16 @@ export class ObjectStackProtocolImplementation implements // schema gate, the authoring gate and the persisted body all still see // one document. See {@link stripServedSystemColumns} for why this is a // separate strip from the decoration list and not another entry in it. + // + // [#29673] …and, one beat BEFORE that strip, the read's TRANSLATION + // of an injected column taken back off: a label the `/meta` read served + // in the caller's language through the built-in table is put back to + // the platform's own text, so the column is the platform's definition + // again and comes off with the rest. Pure — no read, so it runs before + // the refusals. The author's own slots are compared with the stored + // row later, beside the credential carry-forward that reads the same + // row. See {@link restoreInjectedColumnEchoes}. + request.item = this.restoreInjectedColumnEchoes(request); request.item = this.stripServedObjectColumns(request.type, request.item); // Per-item lifecycle (ADR-0005 §"Drafts"). Default is `'publish'` // (legacy semantics — save goes straight live) to keep callers @@ -13668,6 +13803,9 @@ export class ObjectStackProtocolImplementation implements // answered `200` for a draft no publish can serve. An ambiguous // address is left to the repository's `409`, as before. The address // is the one read above, before the named-base rule's inherited arm. + // [#29673] The object layer the D9.9 block below classified, for the + // registry's refusal asked after the spec gate. + let objectRegistrationLayer: ReturnType | undefined; if (singularType === 'object') { const writtenPackage = draftAddress && draftAddress.kind !== 'ambiguous' ? draftAddress.into @@ -13692,6 +13830,9 @@ export class ObjectStackProtocolImplementation implements { mode, storedPackages, namedNoPackage, strandedDrafts }, ); } + // [#29673] …and the layer the registry's own refusal of the BODY + // is asked under, after the spec gate below. + objectRegistrationLayer = layer; } // [#24547 · ADR-0129 D2] THE NAMESPACE-PREFIX RULE, on the door that @@ -14237,6 +14378,21 @@ export class ObjectStackProtocolImplementation implements (err as any).issues = issues; throw err; } + // [#29673] The registry's own refusal of the BODY, at the + // producer for the D9.9 refusal's reason: a body + // `registerObject` refuses was stored, answered `200`, and + // logged a `console.warn` at the write-through — and a draft of + // it published as "published" and never reached the data plane. + // Asked in both modes (#23712: a draft no publish can serve is a + // refusal now, not later), and AFTER the spec gate, so a body + // both refuse keeps the gate's structured `issues[]` (#5364). + // The body is the one this save stores: the read's injected + // columns already came off it above. See + // {@link objectRegistrationRefusal}. + if (objectRegistrationLayer) { + const registration = this.objectRegistrationRefusal(request.item, objectRegistrationLayer); + if (registration) throw registration; + } if (singularType === 'view') { // [#20051] A saved view is the parsed body: the parsed // value of every key the request carried, undeclared keys @@ -14765,6 +14921,13 @@ export class ObjectStackProtocolImplementation implements // no door accepts and nothing reads): those are never re-grafted, so // this save drops them from the row at rest, and the answer names each // one on `advisories` (`droppedWithheldKeyNotices`) — loud, never silent. + // [#29673] The author's own slots the `/meta` read translated (a field's + // label through the catalog, the object's own label), put back to the + // stored row's source text. After every refusal, so a refused save + // costs no read; before the carry-forward and the put, so what is + // stored is the source. See {@link restoreTranslatedObjectEchoes}. + const echoes = await this.restoreTranslatedObjectEchoes(request, repo, ref, mode); + request.item = echoes.item; const carried = await this.carryForwardRedactedCredentials({ type: singularTypeForRepo, repo, @@ -14778,6 +14941,8 @@ export class ObjectStackProtocolImplementation implements const saveNotices = [ ...runtimeAdvisories, ...droppedWithheldKeyNotices({ type: singularTypeForRepo, name: request.name, dropped: carried.dropped }), + // [#29673] Each author slot this save put back to its source text. + ...translatedEchoNotices(request.name, echoes.restored), ]; // [#20790] …and then OUT of the body: a type with a write-only // credential channel (`flow`, registered by the automation plugin) @@ -15394,7 +15559,28 @@ export class ObjectStackProtocolImplementation implements : this.convertStoredItemDetailed( singular, body, undefined, await this.storedRowKnownDatasources(singular, body), ); - const changed = flowResult ? item !== body : notices.length > 0; + // [#29673] …and, for an `object` row, the save door's translated-echo + // restoration ({@link restoreTranslatedObjectEchoes}), asked of the + // row against itself and the platform's injected columns: a row a + // zh-CN Studio session stored before that door existed carries an + // injected column's TRANSLATED label as an author's field (a `queue` + // the registry refuses, so the object never registers and a restart + // does not recover it). Each slot is a notice, and the re-save below + // goes through the door that puts it back and strips the column. + const echoNotices: StoredMigrationNotice[] = singular === 'object' && !flowResult + ? restoreTranslatedEchoes(item, { source: item, bundle: this.registeredTranslationBundle() }) + .restored.map((slot) => ({ + conversionId: TRANSLATED_ECHO_NOTICE_ID, + surface: 'object.field.label', + from: slot.from, + to: slot.to ?? '', + path: slot.path, + message: 'the stored text is the /meta read\'s translation of its source, stored as the ' + + 'document by an edit that echoed a translated read; the re-save stores the source ' + + 'text, and an injected column that is the platform\'s own again comes off the row', + })) + : []; + const changed = flowResult ? item !== body : notices.length > 0 || echoNotices.length > 0; // [#17321] A site the chain left as stored — no lossless rewrite // exists for it (ADR-0087 D3: a structured TODO, never silence) — // rides on the row whatever its outcome, and is what keeps a row @@ -15430,14 +15616,17 @@ export class ObjectStackProtocolImplementation implements }); continue; } - const flattened: StoredMigrationNotice[] = notices.map((n) => ({ - conversionId: n.conversionId, - surface: n.surface, - from: n.from, - to: n.to, - path: n.path, - message: n.message, - })); + const flattened: StoredMigrationNotice[] = [ + ...notices.map((n) => ({ + conversionId: n.conversionId, + surface: n.surface, + from: n.from, + to: n.to, + path: n.path, + message: n.message, + })), + ...echoNotices, + ]; if (!apply) { record({ ...base, notices: flattened, todos: flattenedTodos, outcome: 'pending' }); @@ -16129,7 +16318,19 @@ export class ObjectStackProtocolImplementation implements }, ); } + // [#29673] …and the registry's refusal of the body this promotion + // makes live, on the same row and for the D9.9 refusal's reason: + // the write-through runs after the row is active, where a refusal + // is only a `console.warn`, so a publish answered `published` for + // an object that never registered (a zh-CN Studio's echoed `queue` + // column, measured). Asked here, before `repo.promoteDraft` + // writes, the per-item publish answers the registry's own envelope + // and a batch publish aborts on it into `failed[]` as on the + // refusals below (ADR-0067 D2). See {@link objectRegistrationRefusal}. + const registration = this.objectRegistrationRefusal(draftForGate.body, layer); + if (registration) throw registration; } + // [#24547 · ADR-0129 D2] …and the namespace-prefix rule, the third // door's turn: the per-item publish (`POST /meta/object/:name/publish`) // made an object `active` under a namespaced package although its name diff --git a/packages/objectql/src/ownership-queue.test.ts b/packages/objectql/src/ownership-queue.test.ts index 169f08a76f3..81bd2dd04b0 100644 --- a/packages/objectql/src/ownership-queue.test.ts +++ b/packages/objectql/src/ownership-queue.test.ts @@ -157,6 +157,25 @@ describe('[ADR-0142 D3] the injected `queue` column', () => { expect(engine.registry.getObject('job')).toBeUndefined(); }); + it('[#29673] `objectRegistrationRefusal` answers the throw `registerObject` makes, and registers nothing', () => { + const engine = new ObjectQL(); + const declared = { name: 'job', fields: { queue: { type: 'text', label: 'Print queue' } } } as any; + const asked = engine.registry.objectRegistrationRefusal(declared, 'pkg'); + expect(asked).toMatchObject({ code: 'INVALID_METADATA', status: 422, name: 'ObjectQueueColumnRefusedError', objectName: 'job' }); + expect(engine.registry.getObject('job')).toBeUndefined(); + let thrown: any; + try { engine.registry.registerObject(declared, 'pkg'); } catch (err) { thrown = err; } + expect(thrown?.name).toBe(asked?.name); + expect(thrown?.message).toBe(asked?.message); + // The field-type door, the other body door, answers the same way. + expect(engine.registry.objectRegistrationRefusal({ name: 'job', fields: { x: { label: 'X' } } } as any, 'pkg')) + .toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + // The platform's own definition coming back, and an ordinary body: no refusal, and still nothing registered. + expect(engine.registry.objectRegistrationRefusal({ name: 'job', fields: { queue: { ...QUEUE_FIELD_DEF } } } as any, 'pkg')).toBeNull(); + expect(engine.registry.objectRegistrationRefusal({ name: 'job', fields: { title: { type: 'text' } } } as any, 'pkg')).toBeNull(); + expect(engine.registry.getObject('job')).toBeUndefined(); + }); + it('the platform\'s own definition coming back passes, and so does `queue` on a tier that carries none', () => { expect(objectQueueColumnRefusal({ name: 'ticket', fields: { queue: { ...QUEUE_FIELD_DEF } } })).toBeNull(); expect(objectQueueColumnRefusal({ name: 'catalog', ownership: 'org', fields: { queue: { type: 'text' } } })).toBeNull(); diff --git a/packages/objectql/src/protocol-meta-effective-schema.test.ts b/packages/objectql/src/protocol-meta-effective-schema.test.ts index 6105448a0a4..7260e940c14 100644 --- a/packages/objectql/src/protocol-meta-effective-schema.test.ts +++ b/packages/objectql/src/protocol-meta-effective-schema.test.ts @@ -47,6 +47,8 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; import { SchemaRegistry } from './registry.js'; import { assertEngineFindOnePredicate } from './engine-findone-predicate.js'; +import { translateMetadataDocument } from '@objectstack/spec/system'; +import { OWNER_FIELD_DEF, QUEUE_FIELD_DEF } from '@objectstack/spec/data'; interface Row { id: string; @@ -354,3 +356,182 @@ describe.each([true, false])('[#6562] /meta object read — effective schema (mu expect(registryBacked._diagnostics).toEqual({ valid: true }); }); }); + +/** + * [#29673] The write door's inverse of the read's TRANSLATION, over the real + * registry and the real protocol: the same two producers this file exists + * for, one step further along Studio's round trip. + * + * Measured on `origin/main` (fc558923) through the HTTP doors of a booted + * showcase: a zh-CN Studio session's autosave PUT carried `fields.queue.label` + * `队列` and `fields.owner_id.label` `负责人` (the read translates the injected + * columns through the built-in table); the write path stored both as the + * author's own fields; `registerObject` refused the author's `queue` into the + * write-through's `console.warn`; `publish-drafts` answered `published`; and + * `GET /data/:object` answered 404 `OBJECT_NOT_FOUND`. An `en` read of the + * same object was served `负责人`. + * + * The echo is built with the spec translator the REST read exits call + * (`translateMetadataDocument`), over the effective document the protocol + * read serves — exactly what reaches Studio, minus the HTTP envelope. + */ +describe('[#29673] a zh-CN read echoed back is stored as its source, and publish tells the truth', () => { + const zhRead = async (host: ReturnType, name: string): Promise => + translateMetadataDocument('object', (await host.protocol.getMetaItem({ type: 'object', name })).item as any, undefined, { locale: 'zh-CN' }); + const storedBody = (host: ReturnType, name: string, state = 'active') => + JSON.parse(Array.from(host.rows.values()).find((r) => r.name === name && r.state === state)!.metadata); + + it('the echo stores no injected column, the new field registers, and an en read is English again', async () => { + const host = makeHost(false); + await host.protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: { ...authored(), sharingModel: 'private' }, mode: 'publish' } as any); + + const echo = await zhRead(host, 'crm_invoice'); + // The precondition: the read really translated the injected columns. + expect(echo.fields.queue.label).toBe('队列'); + expect(echo.fields.owner_id.label).toBe('负责人'); + // The author's edit rides the echo: one new field, as Studio's autosave sends it. + echo.fields.memo = { type: 'text', label: '备注' }; + + await host.protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: echo, mode: 'publish' } as any); + + const stored = storedBody(host, 'crm_invoice'); + expect(Object.keys(stored.fields).sort()).toEqual(['amount', 'memo']); + // The author's own text is never touched — `备注` was typed, not translated. + expect(stored.fields.memo.label).toBe('备注'); + // Registered: the write-through took the new body (on main it refused the + // author's `queue` and kept serving the body without `memo`). + expect(Object.keys((host.registry.getObject('crm_invoice') as any).fields)).toContain('memo'); + const en: any = (await host.protocol.getMetaItem({ type: 'object', name: 'crm_invoice' })).item; + expect(en.fields.owner_id.label).toBe('Owner'); + expect(en.fields.queue.label).toBe('Queue'); + }); + + it('an author\'s own `queue` is refused at the save door with the registry\'s envelope, in both modes', async () => { + const host = makeHost(false); + for (const mode of ['draft', 'publish'] as const) { + const body = { ...authored(), sharingModel: 'private', name: `crm_case_${mode}`, fields: { ...authored().fields, queue: { type: 'text', label: 'Support Queue' } } }; + const err: any = await host.protocol.saveMetaItem({ type: 'object', name: body.name, item: body, mode } as any) + .then(() => null, (e) => e); + expect(err, mode).toMatchObject({ name: 'ObjectQueueColumnRefusedError', code: 'INVALID_METADATA', status: 422 }); + expect(Array.from(host.rows.values()).some((r) => r.name === body.name), mode).toBe(false); + } + }); + + it('a stored draft the registry refuses is refused at publish: nothing promoted, nothing registered', async () => { + const host = makeHost(false); + // A draft stored before the save door asked (the shape a zh-CN session + // left behind, here with an author's own `queue` so no restoration applies). + await host.engine.insert('sys_metadata', { + type: 'object', name: 'crm_case', organization_id: null, package_id: null, state: 'draft', + metadata: JSON.stringify({ ...authored(), sharingModel: 'private', name: 'crm_case', fields: { ...authored().fields, queue: { type: 'text', label: 'Support Queue' } } }), + }); + const err: any = await host.protocol.publishMetaItem({ type: 'object', name: 'crm_case' } as any).then(() => null, (e) => e); + // The registry's own refusal, by name — not some other gate's 422. + expect(err).toMatchObject({ name: 'ObjectQueueColumnRefusedError', code: 'INVALID_METADATA', status: 422 }); + expect(Array.from(host.rows.values()).some((r) => r.name === 'crm_case' && r.state === 'active')).toBe(false); + expect(host.registry.getObject('crm_case')).toBeUndefined(); + }); + + /** The same host's engine behind a protocol that has an i18n service (and, optionally, a metadata service). */ + const withServices = (host: ReturnType, bundle: Record, metadata?: unknown) => + new ObjectStackProtocolImplementation(host.engine, () => new Map([ + ['i18n', { getLocales: () => Object.keys(bundle), getTranslations: (locale: string) => bundle[locale] }], + ...(metadata ? [['metadata', metadata] as [string, any]] : []), + ])); + + it('an author slot the catalog translated is stored as its source, and the save answer says so on `advisories`', async () => { + const host = makeHost(false); + const bundle = { 'zh-CN': { objects: { crm_invoice: { fields: { amount: { label: '金额' } } } } } }; + const protocol = withServices(host, bundle); + await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: { ...authored(), sharingModel: 'private' }, mode: 'publish' } as any); + + const echo: any = translateMetadataDocument('object', (await protocol.getMetaItem({ type: 'object', name: 'crm_invoice' })).item as any, bundle as any, { locale: 'zh-CN' }); + expect(echo.fields.amount.label).toBe('金额'); + const saved: any = await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: echo, mode: 'publish' } as any); + + expect(storedBody(host, 'crm_invoice').fields.amount.label).toBe('Amount'); + expect(saved.advisories?.map((a: any) => [a.rule, a.severity, a.path])).toEqual([ + ['translated-label-echo', 'info', 'objects.crm_invoice.fields.amount.label'], + ]); + }); + + it('the door translates the stored source against the packaged base the read uses: a diverged slot set to the catalog string is kept', async () => { + // Seeded through `getPackagedObjectBase`, the accessor the REST read hands + // `translateObject` as `packagedBase` (an object's packaged base is only + // reachable through a writable package's code layer; the accessor is the + // seam both the read and this door ask). + const base = { name: 'crm_ticket', label: 'Ticket', fields: { title: { type: 'text', label: 'Title' } } }; + const bundle = { 'zh-CN': { objects: { crm_ticket: { fields: { title: { label: '标题' } } } } } }; + const overlay = { name: 'crm_ticket', label: 'Ticket', sharingModel: 'private', fields: { title: { type: 'text', label: 'Subject' } } }; + // The precondition: the read, with the packaged base, serves the diverged `Subject` untranslated. + expect((translateMetadataDocument('object', overlay as any, bundle as any, { locale: 'zh-CN', packagedBase: base }) as any).fields.title.label).toBe('Subject'); + const typed = { ...overlay, fields: { title: { type: 'text', label: '标题' } } }; + + const run = async (withBase: boolean) => { + const host = makeHost(false); + await host.engine.insert('sys_metadata', { + type: 'object', name: 'crm_ticket', organization_id: null, package_id: null, state: 'active', metadata: JSON.stringify(overlay), + }); + const protocol: any = withServices(host, bundle); + if (withBase) protocol.getPackagedObjectBase = (name: string) => (name === 'crm_ticket' ? base : undefined); + const saved: any = await protocol.saveMetaItem({ type: 'object', name: 'crm_ticket', item: typed, mode: 'publish' } as any); + return { label: storedBody(host, 'crm_ticket').fields.title.label, advisories: saved.advisories ?? [] }; + }; + // With the packaged base: `标题` is no translation of `Subject`, so it is the author's edit. + expect(await run(true)).toEqual({ label: '标题', advisories: [] }); + // Control, no packaged base: the catalog translates `Subject` by name, so the door restores it. + expect((await run(false)).label).toBe('Subject'); + }); + + it('a body the spec gate and the registry both refuse keeps the spec gate\'s structured `issues[]`', async () => { + const host = makeHost(false); + const body = { ...authored(), sharingModel: 'private', name: 'crm_bad', fields: { ...authored().fields, odd: { type: 'no_such_type', label: 'Odd' } } }; + const err: any = await host.protocol.saveMetaItem({ type: 'object', name: 'crm_bad', item: body, mode: 'draft' } as any).then(() => null, (e) => e); + expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(err.name).not.toBe('ObjectFieldTypeRefusedError'); + expect(Array.isArray(err.issues) && err.issues.length > 0).toBe(true); + expect(err.message).toContain('failed spec validation'); + }); + + it('a brand-new object saves while the metadata service reports itself degraded: the restoration reads no service', async () => { + const host = makeHost(false); + const degraded = { + get: async () => undefined, + getDiagnosed: async () => ({ data: undefined, degraded: true, errors: ['metadata store unreachable'] }), + }; + const protocol = withServices(host, {}, degraded); + const saved: any = await protocol.saveMetaItem({ type: 'object', name: 'crm_fresh', item: { ...authored(), name: 'crm_fresh', sharingModel: 'private' }, mode: 'draft' } as any); + expect(saved.success).toBe(true); + expect(storedBody(host, 'crm_fresh', 'draft').fields.amount.label).toBe('Amount'); + }); + + it('the stored-row migration repairs a row a zh-CN session already stored', async () => { + const host = makeHost(false); + const echoed = { + ...authored(), + name: 'crm_lead', + fields: { + ...authored().fields, + queue: { ...(QUEUE_FIELD_DEF as Record), label: '队列' }, + owner_id: { ...(OWNER_FIELD_DEF as Record), label: '负责人' }, + }, + }; + await host.engine.insert('sys_metadata', { + type: 'object', name: 'crm_lead', organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(echoed), + }); + + const preview: any = await host.protocol.migrateStoredMetadata({ types: ['object'] }); + const row = preview.rows.find((r: any) => r.name === 'crm_lead'); + expect(row?.outcome).toBe('pending'); + expect(row.notices.map((n: any) => [n.conversionId, n.path, n.from, n.to])).toEqual([ + ['translated-label-echo', 'fields.queue.label', '队列', 'Queue'], + ['translated-label-echo', 'fields.owner_id.label', '负责人', 'Owner'], + ]); + + const applied: any = await host.protocol.migrateStoredMetadata({ types: ['object'], apply: true }); + expect(applied.rows.find((r: any) => r.name === 'crm_lead')?.outcome).toBe('rewritten'); + expect(Object.keys(storedBody(host, 'crm_lead').fields)).toEqual(['amount']); + expect(host.registry.getObject('crm_lead')).toBeDefined(); + }); +}); diff --git a/packages/objectql/src/record-currency-guards.test.ts b/packages/objectql/src/record-currency-guards.test.ts index 926ef929c30..eeecbdc13d0 100644 --- a/packages/objectql/src/record-currency-guards.test.ts +++ b/packages/objectql/src/record-currency-guards.test.ts @@ -309,6 +309,18 @@ describe('a summary roll-up over a record-mode amount is refused at registration } }); + it('[#29673] the pre-flight `objectRegistrationRefusal` leaves this door to the registration: it reads other objects, not the body alone', async () => { + const { engine } = await bootEngine(); + engine.registry.registerObject(LINE as any); + // A sibling drafted in the same batch may take the child's amount out of + // record-currency mode before this parent registers, so the pre-flight a + // save or promote asks does not refuse it; the registration still does. + expect(engine.registry.objectRegistrationRefusal(parentWith('sum') as any)).toBeNull(); + const err = await refusalOf(() => engine.registry.registerObject(parentWith('sum') as any)); + expect(err?.name).toBe('RecordCurrencySummaryRefusedError'); + expect(engine.registry.getObject('fx_parent')).toBeUndefined(); + }); + it('the child registering after the parent is refused, naming the same roll-up', async () => { const { engine } = await bootEngine(); engine.registry.registerObject(parentWith('sum') as any); diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index bb63d6098f8..94e8721da3f 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -4241,41 +4241,50 @@ export class SchemaRegistry { // ========================================== /** - * Register an object with ownership semantics. - * - * @param schema - The object definition - * @param packageId - The owning package ID, or — for an `overlay` — the - * `sys_metadata` row's own binding (provenance ON the layer, never an - * ownership claim; ADR-0029 D9.9). Optional (#12623) — matches the - * sibling {@link registerItem}: a bare `registerObject(schema)` call - * passes `packageId: undefined` through to `applyProtection`, which - * leaves the item clean (no `_packageId`, no `_provenance`) rather than - * defaulting. Do not give this parameter a default value — that would - * silently stamp package provenance onto every bare-call fixture. - * @param namespace - The package namespace (for FQN computation) - * @param ownership - 'own' (single owner) | 'overlay' (tenant layer that - * REPLACES the base at resolution; ADR-0029 D9) | 'extend' (additive merge) - * @param priority - Merge priority (lower applied first, higher wins on conflict) - * - * @throws {ObjectOwnershipConflictError} ADR-0112 envelope (`code` + - * `status: 422`) if trying to 'own' an object that already has a PACKAGED - * owner from another package - * @throws {ObjectFieldTypeRefusedError} [#16319] ADR-0112 envelope (`code` + - * `status: 422`) if any declared field's `type` is absent or is not a - * `FieldType` member — the WHOLE declaration is refused, on every - * contributor kind. ⛔ The field is never dropped on its own. + * [#29673] Would {@link registerObject} refuse this body, as `ownership` + * from `packageId`? The refusal it would throw, or `null` — asked of its own + * doors ({@link judgeRegistrationDoors}), so the answer cannot drift from + * the throw. Registers nothing, materializes nothing. + * + * For the metadata doors that make a stored body LIVE (the per-item and the + * package publish, the publishing save): the registration runs after the row + * is already active, where a refusal can only be logged, so they ask this + * first and refuse the publish with the registry's own envelope — the same + * shape as the ADR-0029 D9.9 representability refusal they already ask. + * + * Covers the doors that judge the body ALONE. The record-currency + * `summary` door is left out: it judges the body against the registry as it + * stands (the pair is judged at whichever registration completes it), so + * asked of a draft before its batch registers it answers both ways wrong — + * it refuses a draft whose sibling in the same batch takes the child amount + * out of record-currency mode, and it passes one whose sibling completes the + * pair. It stays the registration's own question. The single-owner rule is + * the protocol's (`classifyObjectContribution`), and a code package's action + * parse never judges a tenant-authored body. */ - registerObject( + objectRegistrationRefusal( schema: ServiceObject, packageId?: string, - namespace?: string, ownership: ObjectOwnership = 'own', - priority: number = ownership === 'own' - ? DEFAULT_OWNER_PRIORITY - : ownership === 'overlay' - ? DEFAULT_OVERLAY_PRIORITY - : DEFAULT_EXTENDER_PRIORITY - ): string { + ): Error | null { + const door = this.judgeRegistrationDoors(schema, packageId, ownership, { bodyOnly: true }); + return 'refusal' in door ? door.refusal : null; + } + + /** + * [#29673] The registration doors of {@link registerObject}, moved here + * whole so {@link objectRegistrationRefusal} asks exactly what the + * registration throws: the refusal, or the body to register (an `extend` + * body re-keyed to the object it extends). `bodyOnly` skips the one door + * that reads the registry's other objects (see + * {@link objectRegistrationRefusal}). + */ + private judgeRegistrationDoors( + schema: ServiceObject, + packageId: string | undefined, + ownership: ObjectOwnership, + opts: { bodyOnly?: boolean } = {}, + ): { refusal: Error } | { schema: ServiceObject } { // [#16319] ⭐ THE FIELD-`type` DOOR — first statement in the method, and // its position is the whole point. // @@ -4295,7 +4304,7 @@ export class SchemaRegistry { // ⛔ The whole object is refused; the offending field is never dropped on // its own. See {@link ObjectFieldTypeRefusedError}. const fieldTypeRefusal = objectFieldTypeRefusal(schema); - if (fieldTypeRefusal) throw fieldTypeRefusal; + if (fieldTypeRefusal) return { refusal: fieldTypeRefusal }; // [ADR-0142 D3] Beside it, for its reason: an eligible object's own // `queue` field is refused before the injection could be skipped for it — @@ -4305,7 +4314,7 @@ export class SchemaRegistry { // whichever order the layers register in. if (ownership !== 'extend') { const queueRefusal = objectQueueColumnRefusal(schema); - if (queueRefusal) throw queueRefusal; + if (queueRefusal) return { refusal: queueRefusal }; } // [ADR-0095 D1 note; ruling E′ item 4] An `extend` contribution never sets @@ -4320,7 +4329,7 @@ export class SchemaRegistry { // metadata save and publish doors also ask of an `object_extension` item. if (ownership === 'extend') { const extendRefusal = extendContributionRefusal(schema, packageId); - if (extendRefusal) throw extendRefusal; + if (extendRefusal) return { refusal: extendRefusal }; // [#28858] …filed under the key the object it extends is registered // under — see {@link extensionTargetKey}. Every entry that registers an // extension reaches this line: the manifest `objectExtensions` loop and @@ -4328,6 +4337,9 @@ export class SchemaRegistry { const target = this.extensionTargetKey(String(schema.name ?? ''), packageId); if (target !== schema.name) schema = { ...schema, name: target }; } + // [#29673] The pre-flight question stops here: the door below reads the + // registry's other objects, not the body alone. + if (opts.bodyOnly) return { schema }; // [ADR-0144 D6] A `summary` roll-up that reads a `record`-mode amount — // `sum` / `avg` / `min` / `max` of a child field whose rows each carry // their own currency — is refused here, the door every metadata path @@ -4338,7 +4350,56 @@ export class SchemaRegistry { (name) => this.getObject(name), () => this.getAllObjects(), ); - if (recordCurrencySummary) throw recordCurrencySummary; + if (recordCurrencySummary) return { refusal: recordCurrencySummary }; + return { schema }; + } + + /** + * Register an object with ownership semantics. + * + * @param schema - The object definition + * @param packageId - The owning package ID, or — for an `overlay` — the + * `sys_metadata` row's own binding (provenance ON the layer, never an + * ownership claim; ADR-0029 D9.9). Optional (#12623) — matches the + * sibling {@link registerItem}: a bare `registerObject(schema)` call + * passes `packageId: undefined` through to `applyProtection`, which + * leaves the item clean (no `_packageId`, no `_provenance`) rather than + * defaulting. Do not give this parameter a default value — that would + * silently stamp package provenance onto every bare-call fixture. + * @param namespace - The package namespace (for FQN computation) + * @param ownership - 'own' (single owner) | 'overlay' (tenant layer that + * REPLACES the base at resolution; ADR-0029 D9) | 'extend' (additive merge) + * @param priority - Merge priority (lower applied first, higher wins on conflict) + * + * @throws {ObjectOwnershipConflictError} ADR-0112 envelope (`code` + + * `status: 422`) if trying to 'own' an object that already has a PACKAGED + * owner from another package + * @throws {ObjectFieldTypeRefusedError} [#16319] ADR-0112 envelope (`code` + + * `status: 422`) if any declared field's `type` is absent or is not a + * `FieldType` member — the WHOLE declaration is refused, on every + * contributor kind. ⛔ The field is never dropped on its own. + */ + registerObject( + schema: ServiceObject, + packageId?: string, + namespace?: string, + ownership: ObjectOwnership = 'own', + priority: number = ownership === 'own' + ? DEFAULT_OWNER_PRIORITY + : ownership === 'overlay' + ? DEFAULT_OVERLAY_PRIORITY + : DEFAULT_EXTENDER_PRIORITY + ): string { + // [#29673] The registration DOORS — every refusal this method answers + // before any materialization and before the contributor list is opened — + // live in {@link judgeRegistrationDoors}, so the metadata doors that make + // a body live can ask the same question BEFORE they promote it + // ({@link objectRegistrationRefusal}) instead of meeting the throw after + // the row is already active. Still the first statement here, and the + // position is still the whole point (the comments inside say why). + const door = this.judgeRegistrationDoors(schema, packageId, ownership); + if ('refusal' in door) throw door.refusal; + schema = door.schema; // [#25744] A code package's object keeps its own actions as their // `ActionSchema` parse — `requiresFeature` / `requiresMembershipReach` diff --git a/packages/qa/dogfood/test/studio-zh-cn-echo-publish.dogfood.test.ts b/packages/qa/dogfood/test/studio-zh-cn-echo-publish.dogfood.test.ts new file mode 100644 index 00000000000..7a19c52dc13 --- /dev/null +++ b/packages/qa/dogfood/test/studio-zh-cn-echo-publish.dogfood.test.ts @@ -0,0 +1,159 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#29673] Studio in zh-CN: a new object whose body echoes the translated +// `/meta` read publishes, registers, and serves data — over the real showcase +// composition and through the REST doors the card measured. +// +// ## What was broken +// +// A `/meta` read in zh-CN serves every injected system column with its label +// translated through the built-in table (`queue` → `队列`, `owner_id` → +// `负责人`). Studio edits by GET → edit → PUT of the whole body, so the draft +// PUT carried those columns back with the translated labels. The write door +// stored them verbatim; no longer byte-identical to the platform's own +// definition, they were kept as the AUTHOR's fields. The registry refuses an +// author's `queue` on a user-owned object, the publish's registry write-through +// swallowed that refusal into a log line, and `publish-drafts` answered +// `outcome: 'published'` for an object whose data door then answered 404. +// +// ## What these cases pin +// +// - the echo: a zh-CN draft PUT carrying the translated `queue` and `owner_id` +// stores neither (the save door restores the source label, and the strip +// that follows removes the platform's own columns), publishes, and serves +// data; an `en` read of it is served `Owner` / `Queue`, not the Chinese. +// - the control: the same body echoed from an `en` read. +// - the publish answer: an object the registry would refuse (an author's own +// `queue`) is refused at the save door — `422 INVALID_METADATA`, nothing +// stored — so no publish can report it published. The publish door's own +// refusal of such a draft stored before this rule is pinned in-process +// (`packages/objectql/src/protocol-meta-effective-schema.test.ts`). + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { bootShowcase } from './showcase-boot.js'; + +const PKG = 'app.zhecho29673'; +const NS = 'zhecho'; + +describe('dogfood: a zh-CN Studio echo of the translated read publishes and serves data (#29673)', () => { + let stack: VerifyStack; + let token: string; + + const call = async (method: string, path: string, body?: unknown, locale?: string) => { + const res = await stack.api(path, { + method, + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + ...(locale ? { 'Accept-Language': locale } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + const json: any = await res.json().catch(() => ({})); + return { status: res.status, json }; + }; + + /** The object document a `/meta` read answers, wherever the envelope nests it. */ + const docOf = (json: any) => json?.data?.item ?? json?.item ?? json?.data ?? json; + + beforeAll(async () => { + stack = await bootShowcase(); + token = await stack.signIn(); + const created = await call('POST', '/packages', { + manifest: { id: PKG, name: 'zh-CN echo probe', version: '0.1.0', type: 'app', namespace: NS }, + }); + expect(created.status, JSON.stringify(created.json)).toBe(201); + }, 180_000); + + afterAll(async () => { + await stack?.stop(); + }); + + /** The injected columns as a read in `locale` serves them, off a showcase object. */ + const servedColumns = async (locale: string) => { + const read = await call('GET', '/meta/object/showcase_task', undefined, locale); + expect(read.status, JSON.stringify(read.json)).toBe(200); + const fields = docOf(read.json)?.fields ?? {}; + expect(fields.queue, 'showcase_task is served the injected `queue`').toBeTruthy(); + return { queue: fields.queue, owner_id: fields.owner_id }; + }; + + /** Save as a draft in `locale`, publish, and answer the publish receipt. */ + const saveAndPublish = async (name: string, fields: Record, locale: string) => { + const saved = await call( + 'PUT', + `/meta/object/${name}?mode=draft&package=${PKG}`, + { name, label: name, sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' }, ...fields } }, + locale, + ); + expect(saved.status, JSON.stringify(saved.json)).toBe(200); + const published = await call('POST', `/packages/${PKG}/publish-drafts`, {}); + expect(published.status, JSON.stringify(published.json)).toBe(200); + return published.json?.data as { outcome?: string; failedCount?: number }; + }; + + const expectServesData = async (name: string) => { + const created = await call('POST', `/data/${name}`, { title: `row of ${name}` }); + expect(created.status, JSON.stringify(created.json)).toBe(201); + const listed = await call('GET', `/data/${name}`); + expect(listed.status, JSON.stringify(listed.json)).toBe(200); + expect(JSON.stringify(listed.json)).toContain(`row of ${name}`); + }; + + it('the read the card starts from: zh-CN serves the injected columns translated, en does not', async () => { + const zh = await servedColumns('zh-CN'); + const en = await servedColumns('en'); + expect(zh.queue.label).toBe('队列'); + expect(zh.owner_id.label).toBe('负责人'); + expect(en.queue.label).toBe('Queue'); + }); + + it('the card: a zh-CN echo of the translated columns publishes, stores neither column, and serves data', async () => { + const zh = await servedColumns('zh-CN'); + const name = `${NS}_q_zh`; + expect(await saveAndPublish(name, { queue: zh.queue, owner_id: zh.owner_id }, 'zh-CN')).toMatchObject({ + outcome: 'published', + failedCount: 0, + }); + await expectServesData(name); + + const layers = await call('GET', `/meta/object/${name}?layers=true`); + expect(layers.status, JSON.stringify(layers.json)).toBe(200); + const stored = JSON.stringify(docOf(layers.json)?.overlay ?? layers.json); + expect(stored).toContain('"title"'); + expect(stored).not.toContain('队列'); + expect(stored).not.toContain('负责人'); + + const en = docOf((await call('GET', `/meta/object/${name}`, undefined, 'en')).json); + expect(en?.fields?.owner_id?.label).toBe('Owner'); + expect(en?.fields?.queue?.label).toBe('Queue'); + }); + + it('control: the same body echoed from an en read publishes and serves data', async () => { + const en = await servedColumns('en'); + const name = `${NS}_q_en`; + expect(await saveAndPublish(name, { queue: en.queue, owner_id: en.owner_id }, 'en')).toMatchObject({ + outcome: 'published', + failedCount: 0, + }); + await expectServesData(name); + }); + + it('an object the registry would refuse (an author `queue`) is refused at the save door, so no publish reports it published', async () => { + const name = `${NS}_q_own`; + const saved = await call('PUT', `/meta/object/${name}?mode=draft&package=${PKG}`, { + name, + label: name, + sharingModel: 'private', + fields: { title: { type: 'text', label: 'Title' }, queue: { type: 'text', label: 'Support Queue' } }, + }); + expect(saved.status, JSON.stringify(saved.json)).toBe(422); + expect(JSON.stringify(saved.json)).toContain('INVALID_METADATA'); + expect(JSON.stringify(saved.json)).toContain('declares a field named `queue`'); + + const drafts = await call('GET', `/meta/_drafts?packageId=${PKG}`); + expect(drafts.status, JSON.stringify(drafts.json)).toBe(200); + expect(JSON.stringify(drafts.json)).not.toContain(name); + }); +}); diff --git a/packages/spec/api-surface/system.json b/packages/spec/api-surface/system.json index 1ac5c7b2198..2e272788a0d 100644 --- a/packages/spec/api-surface/system.json +++ b/packages/spec/api-surface/system.json @@ -55,6 +55,7 @@ "AwarenessUserState (type)", "AwarenessUserStateSchema (const)", "BUILTIN_OPERATION_MESSAGES (const)", + "BUILTIN_SYSTEM_FIELD_LABEL_LOCALES (const)", "BUILTIN_VALIDATION_MESSAGES (const)", "BackupConfig (type)", "BackupConfigParsed (type)", diff --git a/packages/spec/export-origins/system.json b/packages/spec/export-origins/system.json index 84dea07f904..8c1b91a57e1 100644 --- a/packages/spec/export-origins/system.json +++ b/packages/spec/export-origins/system.json @@ -55,6 +55,7 @@ "AwarenessUserState": "src/system/collaboration.zod.ts#AwarenessUserState (type)", "AwarenessUserStateSchema": "src/system/collaboration.zod.ts#AwarenessUserStateSchema (const)", "BUILTIN_OPERATION_MESSAGES": "src/system/operation-message.ts#BUILTIN_OPERATION_MESSAGES (const)", + "BUILTIN_SYSTEM_FIELD_LABEL_LOCALES": "src/system/i18n-resolver.ts#BUILTIN_SYSTEM_FIELD_LABEL_LOCALES (const)", "BUILTIN_VALIDATION_MESSAGES": "src/system/validation-message.ts#BUILTIN_VALIDATION_MESSAGES (const)", "BackupConfig": "src/system/disaster-recovery.zod.ts#BackupConfig (type)", "BackupConfigParsed": "src/system/disaster-recovery.zod.ts#BackupConfigParsed (type)", diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index f9e79845e66..8f7b266fd22 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -4030,6 +4030,22 @@ const SYSTEM_FIELD_LABELS: Record> = { queue: { en: 'Queue', 'zh-CN': '队列', 'ja-JP': 'キュー', 'es-ES': 'Cola' }, }; +/** + * Every locale the built-in system-field labels above carry a row for, `en` + * included — derived from the table, never listed by hand. + * + * These are locales a `/meta` read translates an injected column's label into + * with NO bundle registered for them at all: the request's `Accept-Language` + * is matched against this table directly (`builtinSystemFieldLabel`). So a + * write door that must recognise a served label coming back as a translation + * — and keep it out of the stored document, where it would read as the + * author's own field — has to try these locales as well as the bundle's own + * (`@objectstack/metadata-protocol`'s save door does). + */ +export const BUILTIN_SYSTEM_FIELD_LABEL_LOCALES: readonly string[] = Object.freeze([ + ...new Set(Object.values(SYSTEM_FIELD_LABELS).flatMap((entry) => Object.keys(entry))), +]); + /** * Fallback label for a platform-injected system field, honouring the same * locale-matching rules as bundle lookup (exact → case-insensitive → base