diff --git a/.changeset/35384-reader-labels-translate-object.md b/.changeset/35384-reader-labels-translate-object.md new file mode 100644 index 00000000000..59891f7fb85 --- /dev/null +++ b/.changeset/35384-reader-labels-translate-object.md @@ -0,0 +1,20 @@ +--- +'@objectstack/objectql': patch +'@objectstack/plugin-approvals': patch +'@objectstack/plugin-audit': patch +--- + +fix(objectql,approvals,audit): an authored rule message, an approval's object label and an activity summary's labels read as `/meta` serves them in a declared `i18n.sourceLocale` + +Clause-②: no +Metadata-protocol: none + +In a deployment whose `i18n.sourceLocale` differs from its `i18n.defaultLocale` (an app authored in English that defaults its users to Chinese, say), three readers still looked metadata text up through `II18nService.t()`, which falls back to the `defaultLocale` row when the reader's locale holds no entry. An `en` reader was shown the Chinese text where `GET /meta` and every other refusal label showed the English one as authored: + +- objectql: the author-written message of a validation rule (`objects.._validations..message`) in a `400 VALIDATION_FAILED` refusal; +- plugin-approvals: the object label on the approvals inbox, the request page, the generic data door's request rows and the approval refusals that name an object; +- plugin-audit: the object, field and select-option labels inside an activity summary composed in the reader's language. + +Each now resolves through `translateObject` (`@objectstack/spec/system`) over every locale the i18n service holds, with the resolve options the metadata route builds: the reader's locale, the declared fallback chain and the authored language (the declared `sourceLocale`, else `defaultLocale`). A reader in the authored language reads the text as written; every other reader reads the same row as before. `t()` keeps carrying the catalog sentences. + +An i18n service that cannot hand its translations over (no `getLocales()` / `getTranslations()`) no longer has these labels and rule messages translated through `t()`: the authored text stands. Every service the platform ships implements both. diff --git a/packages/objectql/src/engine-label-source-locale.test.ts b/packages/objectql/src/engine-label-source-locale.test.ts index 9575590260e..daac7f76cbb 100644 --- a/packages/objectql/src/engine-label-source-locale.test.ts +++ b/packages/objectql/src/engine-label-source-locale.test.ts @@ -60,9 +60,31 @@ const deal = { }], }; +/** + * [#35384] An object whose rule carries an AUTHORED message: the sentence is + * metadata (`objects.._validations..message`), served by `/meta`'s + * `translateObjectValidations`. + */ +const task = { + name: 'lsl_task', + label: 'Task', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + due: { name: 'due', type: 'text' as const, label: 'Due' }, + }, + validations: [{ + type: 'script', + name: 'task_needs_due', + message: 'A task needs a due date.', + condition: "record.due == null || record.due == ''", + fields: ['due'], + }], +}; + /** The deployment ships `zh-CN` rows only. */ const ZH_CN = { objects: { + lsl_task: { label: '任务', _validations: { task_needs_due: { message: '任务必须设置截止日期。' } } }, lsl_account: { label: '客户', fields: { name: { label: '名称' } } }, lsl_deal: { label: '商机', @@ -147,7 +169,7 @@ async function makeEngine(i18n: ReturnType) { const engine = new ObjectQL(); engine.registerDriver(makeStubDriver(), true); await engine.init(); - for (const o of [account, deal]) engine.registry.registerObject(o as any); + for (const o of [account, deal, task]) engine.registry.registerObject(o as any); engine.setI18nService(i18n); return engine; } @@ -213,3 +235,34 @@ describe('a refusal in the declared sourceLocale names labels as authored', () = for (const word of ['客户', '商机', '所属客户']) expect(object.message).toContain(word); }); }); + +/** + * [#35384] The authored rule message resolves by the same rule: through + * `translateObject` over the metadata route's `ResolveOptions`, so an `en` + * write in a deployment authored in English reads the sentence as written — + * what `/meta` serves the same rule's `message` as for an `en` request + * (`packages/rest/src/meta-i18n-declared-fallback-chain.test.ts` §6 pins that + * half) — never the `zh-CN` row `t()` falls back to. + */ +describe('an authored rule message in the declared sourceLocale reads as authored', () => { + const refusal = async (declared: Parameters[0], locale: string) => + refused((await makeEngine(servedI18n(declared))).insert('lsl_task', { due: '' }, { context: { locale } as any })); + + it('an en write reads the authored English sentence', async () => { + const err = await refusal(SOURCE_EN, 'en'); + expect(err.code).toBe('VALIDATION_FAILED'); + expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: 'A task needs a due date.' }); + }); + + it('CONTROL: a zh-CN write still reads the zh-CN row', async () => { + const err = await refusal(SOURCE_EN, 'zh-CN'); + expect(err.code).toBe('VALIDATION_FAILED'); + expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: '任务必须设置截止日期。' }); + }); + + it('CONTROL: with no sourceLocale declared, an en write walks to the zh-CN row as before', async () => { + const err = await refusal({ defaultLocale: 'zh-CN' }, 'en'); + expect(err.code).toBe('VALIDATION_FAILED'); + expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: '任务必须设置截止日期。' }); + }); +}); diff --git a/packages/objectql/src/engine-validation-locale-negotiation.test.ts b/packages/objectql/src/engine-validation-locale-negotiation.test.ts index 1d3c3e9b534..8827bd10f56 100644 --- a/packages/objectql/src/engine-validation-locale-negotiation.test.ts +++ b/packages/objectql/src/engine-validation-locale-negotiation.test.ts @@ -95,6 +95,10 @@ function servedI18n(bundle: Record, fallbackLocale = 'en') { return typeof fallback === 'string' ? fallback : key; }, getLocales: () => Object.keys(bundle), + // [#35384] The authored rule message is metadata: it is read off the + // bundle by `translateObject`, as `/meta` reads it, never through `t()`. + getTranslations: (locale: string) => bundle[locale] ?? {}, + getFallbackLocale: () => fallbackLocale, }; } @@ -105,6 +109,9 @@ const DUTY_SCHEMA = { form: { type: 'select', label: 'Form' }, status: { type: 'select', label: 'Status' }, return_note: { type: 'text', label: 'Return note' }, + // [#35384] Refused by a BUILT-IN message (`max_length`), the sentence the + // `t()` bridge still carries: the probe of what locale the bridge asks. + code: { type: 'text', label: 'Code', maxLength: 3 }, }, validations: [{ type: 'script', @@ -168,6 +175,22 @@ async function refusalFor(header: string, i18n: ReturnType): return (await refusalEnvelopeFor(header, i18n)).message; } +/** + * [#35384] A write refused by a BUILT-IN message (`code` over its + * `maxLength`), which renders through the `t()` bridge — the one the locale + * negotiation below is asserted on, now that the authored rule message reads + * the bundle through `translateObject` instead. + */ +async function builtinRefusalFor(locale: string | undefined, i18n: Parameters[0]): Promise { + const ql = await makeEngine(i18n); + try { + await ql.update('duly_duty', { id: 'r1', code: 'too long' }, { context: { locale } } as any); + } catch (e) { + return e; + } + throw new Error('expected the write to be rejected'); +} + /** PATH B — the cross-path control: a document translator, same bundle, same header. */ function datasetStyleLabelsFor(header: string): string[] { const locale = preferredLocaleFromHeader(header); @@ -278,7 +301,7 @@ describe('#15757 the validation-message bridge negotiates the locale like every it('asks the service for the locale it actually has, not the tag the client sent', async () => { const i18n = servedI18n(BUNDLE); expect(preferredLocaleFromHeader('zh')).toBe('zh'); - await refusalFor('zh', i18n); + await builtinRefusalFor(preferredLocaleFromHeader('zh'), i18n); expect(i18n.asked).not.toContain('zh'); expect(i18n.asked).toContain('zh-CN'); }); @@ -291,6 +314,7 @@ describe('#15757 the validation-message bridge negotiates the locale like every it('leaves a locale with no match alone', async () => { const i18n = servedI18n(BUNDLE); expect(await refusalFor('de', i18n)).toBe(AUTHORED_EN); + await builtinRefusalFor('de', i18n); expect(i18n.asked).toContain('de'); }); @@ -303,12 +327,9 @@ describe('#15757 the validation-message bridge negotiates the locale like every */ it('passes the tag through when the service cannot report its locales', async () => { const asked: string[] = []; - const ql = await makeEngine({ + await builtinRefusalFor('zh', { t: (key: string, locale: string) => { asked.push(locale); return key; }, }); - try { - await ql.update('duly_duty', { id: 'r1', status: 'returned' }, { context: { locale: 'zh' } } as any); - } catch { /* expected */ } expect(asked).toContain('zh'); }); }); diff --git a/packages/objectql/src/engine-validation-tenant-rewrite.test.ts b/packages/objectql/src/engine-validation-tenant-rewrite.test.ts index dfeb7d5c919..8987dcacee7 100644 --- a/packages/objectql/src/engine-validation-tenant-rewrite.test.ts +++ b/packages/objectql/src/engine-validation-tenant-rewrite.test.ts @@ -130,6 +130,10 @@ function servedI18n(bundle: Record, fallbackLocale = 'en') { return typeof fallback === 'string' ? fallback : key; }, getLocales: () => Object.keys(bundle), + // [#35384] The refusal reads a rule message off the bundle by + // `translateObject`, as `/meta` does, never through `t()`. + getTranslations: (locale: string) => bundle[locale] ?? {}, + getFallbackLocale: () => fallbackLocale, }; } diff --git a/packages/objectql/src/validation/rule-validator.test.ts b/packages/objectql/src/validation/rule-validator.test.ts index 2292a9a3c48..c062505c197 100644 --- a/packages/objectql/src/validation/rule-validator.test.ts +++ b/packages/objectql/src/validation/rule-validator.test.ts @@ -2464,25 +2464,38 @@ describe('evaluateValidationRules — built-in messages are localized (#3957)', * * The evaluator emitted the authored sentence verbatim, so a deployment with a * complete `zh-CN` bundle read platform-generated refusals in Chinese and - * author-written refusals in English **inside one error envelope**. The - * built-in field catalog has resolved through `messages.translate` since #3957; - * what was missing was a key shape for an author's own rule, not a channel. + * author-written refusals in English **inside one error envelope**. What was + * missing was a key shape for an author's own rule, not a channel. * - * These tests drive the SAME `ValidationMessageContext.translate` hook the - * built-in catalog uses (the engine's `i18nService`, `II18nService.t` - * semantics: the key is echoed back on a miss). If a second i18n path were ever - * added to objectql, this fixture would keep passing through the old one — so - * the address is asserted explicitly, not just the output. + * [#35384] The sentence is metadata (`objects.._validations..message`, + * the key `/meta`'s `translateObjectValidations` reads), so these tests drive + * `ValidationMessageContext.labelTranslation` — the bundle and the metadata + * route's `ResolveOptions` the refusal's labels read (#34030) — and never the + * `translate` (`t()`) hook, which carries the built-in messages only. A `t()` + * that would answer a rule message is wired beside it in the first test, so a + * reader that went back to `t()` reads the decoy. */ describe('evaluateValidationRules — authored rule messages resolve from the bundle (#14253)', () => { - /** An `II18nService.t`-shaped lookup over a flat key→string map. */ - const service = (entries: Record) => { - const seen: string[] = []; + /** A `locale|a.b.c` map as the nested per-locale bundle `getTranslations()` hands over. */ + const bundleOf = (entries: Record): Record> => { + const bundle: Record> = {}; + for (const [address, value] of Object.entries(entries)) { + const [locale, key] = address.split('|'); + const parts = key.split('.'); + let cur = (bundle[locale] ??= {}); + for (const part of parts.slice(0, -1)) cur = cur[part] ??= {}; + cur[parts[parts.length - 1]] = value; + } + return bundle; + }; + /** `labelTranslation` over `entries`, read in `locale`; counts its calls. */ + const service = (entries: Record, locale = 'zh-CN') => { + const calls = { count: 0 }; return { - seen, - t: (key: string, locale: string) => { - seen.push(`${locale}|${key}`); - return entries[`${locale}|${key}`] ?? key; + calls, + labelTranslation: () => { + calls.count += 1; + return { bundle: bundleOf(entries) as any, options: { locale } }; }, }; }; @@ -2512,41 +2525,54 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu }], }); - it('asks for objects.._validations..message, and returns what it gets', () => { + it('reads objects.._validations..message through labelTranslation, never t()', () => { const i18n = service({ 'zh-CN|objects.duly_duty._validations.standing_no_frequency.message': '常规任务必须设置频率。', + // Another object's rule of the same name: not this refusal's address. + 'zh-CN|objects.other_duty._validations.standing_no_frequency.message': 'WRONG — another object', }); const [err] = failing(scriptSchema('A standing duty must declare a frequency.'), {}, 'insert', { - messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t }, + messages: { + locale: 'zh-CN', + objectName: 'duly_duty', + labelTranslation: i18n.labelTranslation, + translate: (key: string) => (key.includes('._validations.') ? 'WRONG — read through t()' : key), + }, }); expect(err.message).toBe('常规任务必须设置频率。'); - expect(i18n.seen).toContain('zh-CN|objects.duly_duty._validations.standing_no_frequency.message'); // The wire vocabulary is unchanged — ADR-0114's `code` does not split // because a sentence is now translatable. expect(err.code).toBe('rule_violation'); expect(err.field).toBe('frequency'); }); - it('keeps the authored sentence when the bundle has no entry (the key echoes back)', () => { + it('keeps the authored sentence when the bundle has no entry', () => { const i18n = service({}); const [err] = failing(scriptSchema('A standing duty must declare a frequency.'), {}, 'insert', { - messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t }, + messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation }, }); expect(err.message).toBe('A standing duty must declare a frequency.'); }); + it('keeps the authored sentence when the service cannot hand its translations over', () => { + const [err] = failing(scriptSchema('authored'), {}, 'insert', { + messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: () => undefined }, + }); + expect(err.message).toBe('authored'); + }); + it('does not consult the bundle without an object name or a locale', () => { const i18n = service({ 'zh-CN|objects.duly_duty._validations.standing_no_frequency.message': '常规任务必须设置频率。', }); expect(failing(scriptSchema('authored'), {}, 'insert', { - messages: { locale: 'zh-CN', translate: i18n.t }, + messages: { locale: 'zh-CN', labelTranslation: i18n.labelTranslation }, })[0].message).toBe('authored'); expect(failing(scriptSchema('authored'), {}, 'insert', { - messages: { objectName: 'duly_duty', translate: i18n.t }, + messages: { objectName: 'duly_duty', labelTranslation: i18n.labelTranslation }, })[0].message).toBe('authored'); - expect(i18n.seen).toEqual([]); + expect(i18n.calls.count).toBe(0); }); it('survives a throwing i18n service — a 400 must not become a 500', () => { @@ -2554,7 +2580,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu messages: { locale: 'zh-CN', objectName: 'duly_duty', - translate: () => { throw new Error('i18n exploded'); }, + labelTranslation: () => { throw new Error('i18n exploded'); }, }, }); expect(err.message).toBe('authored'); @@ -2566,7 +2592,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu 'zh-CN|objects.duly_duty._validations.contact_email.message': '联系邮箱格式不正确。', 'zh-CN|objects.duly_duty._validations.payload_shape.message': '负载结构不符合约定。', }); - const messages = { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t }; + const messages = { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation }; const fsm = { fields: { status: { type: 'select', label: '状态' } }, @@ -2623,7 +2649,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu }], }; const [err] = failing(schema, { account_type: 'enterprise', approver: null }, 'insert', { - messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t }, + messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation }, }); expect(err.message).toBe('企业客户需要审批人。'); }); @@ -2643,7 +2669,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu }], }; const [err] = failing(schema, {}, 'insert', { - messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t }, + messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation }, }); expect(err.message).toMatch(/could not be evaluated/); expect(err.message).not.toBe('这条不该出现。'); @@ -2666,8 +2692,11 @@ describe('evaluateValidationRules — a tenant-rewritten rule message beats the const PACKAGED = 'A standing duty must declare a frequency.'; const REWRITE = 'Pick how often this duty repeats.'; const ZH = '常规任务必须设置频率。'; - const KEY = 'zh-CN|objects.duly_duty._validations.standing_no_frequency.message'; - const t = (key: string, locale: string) => ({ [KEY]: ZH } as Record)[`${locale}|${key}`] ?? key; + // [#35384] The catalog entry as the bundle `labelTranslation` hands over. + const labelTranslation = () => ({ + bundle: { 'zh-CN': { objects: { duly_duty: { _validations: { standing_no_frequency: { message: ZH } } } } } } as any, + options: { locale: 'zh-CN' }, + }); const failing = (schema: any, data: Record, opts: Record) => { try { @@ -2691,7 +2720,7 @@ describe('evaluateValidationRules — a tenant-rewritten rule message beats the }); const packagedRule = (name: string) => (name === 'standing_no_frequency' ? scriptRule(PACKAGED) : undefined); const messages = (extra: Record = {}) => - ({ locale: 'zh-CN', objectName: 'duly_duty', translate: t, ...extra }); + ({ locale: 'zh-CN', objectName: 'duly_duty', labelTranslation, ...extra }); it('returns the rewrite as written in a non-default locale', () => { const [err] = failing(schemaWith(REWRITE), {}, { messages: messages({ packagedRule }) }); diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index abbd8f1543f..58a2a26200c 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -243,7 +243,7 @@ import { isEmptyForRequired, recordAdvisoryHit } from '@objectstack/core'; // reports it unconditionally, even under `systemFields: false`), and the // engine's whole by-id addressing reads that key (`idAddressesThisRow`, // `addressKey: 'id'`). -import { SystemFieldName, objectValidationMessageKey, scalarOverridesPackagedBase } from '@objectstack/spec/system'; +import { SystemFieldName, scalarOverridesPackagedBase } from '@objectstack/spec/system'; import Ajv, { type ValidateFunction } from 'ajv'; // #5029 — `format` is NOT built into ajv 8; it ships in this separate package. // See the `const ajv` note below for why the runtime registers it. @@ -4066,11 +4066,17 @@ export function emitValidationAdvisories( * * ## What this is NOT * - * It is not a second i18n path into objectql. The lookup runs on the SAME - * `ValidationMessageContext.translate` hook — the engine's `i18nService`, - * bridged by `ObjectQLPlugin` — that `renderValidationMessage` already uses - * (a metadata LABEL reads `labelTranslation` instead, #34030). What was missing was a key shape for - * an author-written rule, not a channel to resolve one. + * It is not a second i18n path into objectql. [#35384] The message is + * METADATA (`objects.._validations..message`, the key `/meta`'s + * `translateObjectValidations` reads), so it resolves as `/meta` serves it: + * `translateObject` (`@objectstack/spec/system`) over + * `ValidationMessageContext.labelTranslation` — the bundle and the + * `ResolveOptions` the field, option and object labels of the same refusal + * read (#34030), ⛔ never a second copy of those options. So a request in the + * deployment's declared `sourceLocale` reads the sentence as authored, never + * the `defaultLocale` row `t()` falls back to; `translate` (`t()`) carries the + * built-in MESSAGES only. What #14253 added was a key shape for an + * author-written rule, not a channel to resolve one. * * The authored message is handed over verbatim on a miss and the translation is * handed over verbatim on a hit: no `{{…}}` interpolation, because an authored @@ -4090,26 +4096,27 @@ export function emitValidationAdvisories( * one here), so the served rule and the refusal of the same write keep * showing one sentence. A rule the packaged declaration does not carry, or no * lookup at all, has nothing to diverge from: the catalog applies. + * + * Nothing is translated — the authored sentence stands — without an object + * name or a locale, with a service that cannot hand its translations over + * (`labelTranslation` answers `undefined`), and when the translator throws + * ({@link translatedLabels}: a misbehaving i18n service must not turn a 400 + * into a 500). */ function authoredRuleMessage( rule: Pick, messages: ValidationMessageContext | undefined, ): string { - if (messages?.translate && messages.objectName && messages.locale - && typeof rule.name === 'string' && rule.name.length > 0) { + if (messages?.objectName && messages.locale && typeof rule.name === 'string' && rule.name.length > 0) { if (scalarOverridesPackagedBase(messages.packagedRule?.(rule.name), 'message', rule.message)) { return rule.message; } - const key = objectValidationMessageKey(messages.objectName, rule.name); - try { - const translated = messages.translate(key, messages.locale); - // II18nService echoes the key back on a miss. - if (typeof translated === 'string' && translated.length > 0 && translated !== key) { - return translated; - } - } catch { - // A misbehaving i18n service must not turn a 400 into a 500. - } + const doc = translatedLabels( + { name: messages.objectName, validations: [{ name: rule.name, message: rule.message }] }, + messages, + ); + const translated: unknown = doc.validations[0]?.message; + if (typeof translated === 'string' && translated.length > 0) return translated; } return rule.message; } diff --git a/packages/plugins/plugin-approvals/src/reader-locale-labels.test.ts b/packages/plugins/plugin-approvals/src/reader-locale-labels.test.ts index 3dac6086c58..214193b7fd2 100644 --- a/packages/plugins/plugin-approvals/src/reader-locale-labels.test.ts +++ b/packages/plugins/plugin-approvals/src/reader-locale-labels.test.ts @@ -184,3 +184,99 @@ describe('[#24863] the overlay on a served row', () => { expect(row).toMatchObject({ process_label: 'Account Approval', step_label: 'Manager Review', object_label: '客户' }); }); }); + +/** + * [#35384] The object's label is resolved the way the metadata route serves + * it — `translateObject` over every locale the service holds, with `/meta`'s + * `ResolveOptions` (the reader's locale, the declared fallback chain, and the + * authored language: the declared `sourceLocale`, else `defaultLocale`) — and + * never through `t()`. + * + * The scenario: an app authored in English (`sourceLocale: 'en'`) that + * defaults its users to Chinese (`defaultLocale: 'zh-CN'`) and ships a + * `zh-CN` pack only, so `t('objects.account.label', 'en')` falls to the + * `zh-CN` row. `/meta` answers an `en` request with the authored label + * (`packages/rest/src/meta-i18n-declared-fallback-chain.test.ts` §6 pins that + * half); this reader must say the same, which here means picking nothing so + * the declared label stands. CONTROLS: a `zh-CN` reader still reads the + * `zh-CN` row, and with no `sourceLocale` declared an `en` reader walks the + * declared fallback to it, as `/meta` does. + */ +describe('[#35384] the object label in the declared sourceLocale reads as authored', () => { + /** The real in-memory service, declared as `AppPlugin.loadTranslations` declares it. */ + const declaredMemory = () => { + const i18n = i18nWith({ 'zh-CN': ZH }); + i18n.setDefaultLocale('zh-CN'); + i18n.setFallbackLocale('zh-CN'); + i18n.setSourceLocale('en'); + return i18n; + }; + /** The served adapter's shape (`FileI18nAdapter`): requested locale, then the declared fallback, then the key. */ + const servedI18n = (declared: { defaultLocale: string; sourceLocale?: string }): ReaderLabelI18n => { + const packs: Record> = { 'zh-CN': packOf(ZH) }; + const fallback = declared.defaultLocale; + const read = (data: unknown, key: string): string | undefined => { + let cur: unknown = data; + for (const part of key.split('.')) { + if (!cur || typeof cur !== 'object') return undefined; + cur = (cur as Record)[part]; + } + return typeof cur === 'string' ? cur : undefined; + }; + return { + t: (key, locale) => read(packs[locale], key) ?? (fallback !== locale ? read(packs[fallback], key) : undefined) ?? key, + getLocales: () => Object.keys(packs), + getTranslations: (locale) => packs[locale] ?? {}, + getDefaultLocale: () => declared.defaultLocale, + getFallbackLocale: () => fallback, + getSourceLocale: () => declared.sourceLocale, + }; + }; + + it('an en reader picks no defaultLocale row: the declared label stands (real in-memory service)', () => { + const i18n = declaredMemory(); + // The defect's precondition, read at the same service: `t()` falls to the zh-CN row. + expect(i18n.t(objectLabelKey('account'), 'en')).toBe('客户'); + expect(readerLabelsFor(i18n, 'en')!.objectLabel('account')).toBeUndefined(); + }); + + it('an en reader picks no defaultLocale row (served adapter shape)', () => { + const i18n = servedI18n({ defaultLocale: 'zh-CN', sourceLocale: 'en' }); + expect(i18n.t(objectLabelKey('account'), 'en')).toBe('客户'); + expect(readerLabelsFor(i18n, 'en')!.objectLabel('account')).toBeUndefined(); + }); + + it('the inbox row keeps its authored object label for an en reader', () => { + const row = { + process_name: 'flow:account_approval', current_step: 'manager_review', object_name: 'account', + process_label: 'Account Approval', step_label: 'Manager Review', current_step_label: 'Manager Review', + object_label: 'Account', + }; + localizeRequestLabels(row, readerLabelsFor(servedI18n({ defaultLocale: 'zh-CN', sourceLocale: 'en' }), 'en')!); + expect(row.object_label).toBe('Account'); + }); + + it('CONTROL: a zh-CN reader still reads the zh-CN row', () => { + expect(readerLabelsFor(declaredMemory(), 'zh-CN')!.objectLabel('account')).toBe('客户'); + expect(readerLabelsFor(servedI18n({ defaultLocale: 'zh-CN', sourceLocale: 'en' }), 'zh-CN')!.objectLabel('account')) + .toBe('客户'); + }); + + it('CONTROL: with no sourceLocale declared, an en reader walks the declared fallback to the zh-CN row', () => { + expect(readerLabelsFor(servedI18n({ defaultLocale: 'zh-CN' }), 'en')!.objectLabel('account')).toBe('客户'); + }); + + it('reads no object label through t(): a service that cannot hand its translations over picks none', () => { + const tOnly: ReaderLabelI18n = { t: (key) => (key === objectLabelKey('account') ? '客户' : key) }; + expect(readerLabelsFor(tOnly, 'zh-CN')!.objectLabel('account')).toBeUndefined(); + }); + + it('picks nothing from a service whose translations throw, and does not throw itself', () => { + const throwing: ReaderLabelI18n = { + t: (key) => key, + getLocales: () => ['zh-CN'], + getTranslations: () => { throw new Error('translations exploded'); }, + }; + expect(readerLabelsFor(throwing, 'zh-CN')!.objectLabel('account')).toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/reader-locale-labels.ts b/packages/plugins/plugin-approvals/src/reader-locale-labels.ts index bb06321c133..bbaca4ee447 100644 --- a/packages/plugins/plugin-approvals/src/reader-locale-labels.ts +++ b/packages/plugins/plugin-approvals/src/reader-locale-labels.ts @@ -29,6 +29,16 @@ * - the text is `II18nService.t(key, locale)`; a miss is the key echoed back, * and then the authored text stands. * + * [#35384] Except the OBJECT's label, which is metadata `/meta` serves: it is + * resolved as `/meta` resolves it — `translateObject` + * (`@objectstack/spec/system`) over every locale the service holds, with the + * metadata route's `ResolveOptions` ({@link objectLabelTranslation}: the + * reader's locale, the DECLARED fallback chain, and the authored language, + * the declared `sourceLocale` else `defaultLocale`). So a reader in a + * deployment's declared `sourceLocale` reads the object's label as authored, + * never the `defaultLocale` row `t()` falls back to; `t()` carries the + * catalog sentences. + * * objectql names a refused write's object this way (`objectDisplayLabel`, * through `objectLabelKey`), the REST door names a NOT NULL field this way * (`not-null-refusal-label.ts`), and the automation engine picks a refusal's @@ -41,7 +51,8 @@ * - the flow: `flows..label`, the `flows` face's own `label`; * - the step: `flows..approvals..label`, the face's key for an * `approval` node's step label (`translation.zod.ts`, `approvals`); - * - the object: `objects..label` (`objectLabelKey`); + * - the object: `objects..label`, read by `translateObject` (no key + * is spelled for it here); * - [#35418] a position: `positions..label`, the security catalog face's * own `label` (`translation.zod.ts`, `positions`), which `translatePosition` * overlays on every served `position` document. @@ -70,10 +81,25 @@ */ import type { II18nService } from '@objectstack/spec/contracts'; -import { objectLabelKey, resolveBundleLocale } from '@objectstack/spec/system'; +import { + resolveBundleLocale, + translateObject, + type ObjectLike, + type ResolveOptions, + type TranslationBundle, +} from '@objectstack/spec/system'; -/** The slice of `II18nService` this read asks: `t()`, and `getLocales()` to negotiate when offered. */ -export type ReaderLabelI18n = Pick & Partial>; +/** + * The slice of `II18nService` this read asks: `t()`, `getLocales()` to + * negotiate when offered, and [#35384] the members an object label is + * resolved by, as the metadata route reads them: `getTranslations()` per + * locale, and the declared `getFallbackLocale()` / `getSourceLocale()` / + * `getDefaultLocale()`. + */ +export type ReaderLabelI18n = Pick & + Partial< + Pick + >; /** The `flows` face's flow label, `flows..label`. */ export function flowLabelKey(flowName: string): string { @@ -157,6 +183,50 @@ export function negotiatedReaderLocale( return resolveBundleLocale(offered, requested) ?? requested; } +/** What an object label is translated with: the bundle and the metadata route's `ResolveOptions`. */ +interface ObjectLabelTranslation { + bundle: TranslationBundle | undefined; + options: ResolveOptions; +} + +/** + * [#35384] What the metadata route (`GET /meta/object/:name`) translates an + * object document with, for a request in `locale`: the bundle — every locale + * `service` holds, keyed by locale (`translationBundleOf` in rest) — and the + * `ResolveOptions` that route builds (`metaTranslateOptions` in rest): the + * request's locale, the DECLARED fallback chain (`getFallbackLocale()`), and + * the authored language — the declared `sourceLocale` (`getSourceLocale()`), + * else `defaultLocale` (`getDefaultLocale()`). Each getter is + * feature-detected; a service that declares none gets none. + * + * The locale is the reader's, negotiated ({@link negotiatedReaderLocale}), + * the one every lookup of this read asks with — as objectql's refusal labels + * hand `translateObject` the negotiated locale (`labelTranslationOf`). + * + * `undefined` — the declared label stands — for a service that cannot hand + * its translations over (no `getLocales` / `getTranslations`). A throwing + * service is the caller's to survive. + */ +function objectLabelTranslation(service: ReaderLabelI18n, locale: string): ObjectLabelTranslation | undefined { + if (typeof service.getLocales !== 'function' || typeof service.getTranslations !== 'function') return undefined; + const bundle: Record = {}; + for (const code of service.getLocales()) { + const data = service.getTranslations(code); + if (data && typeof data === 'object') bundle[code] = data; + } + const fallback = typeof service.getFallbackLocale === 'function' ? service.getFallbackLocale() : undefined; + const source = typeof service.getSourceLocale === 'function' ? service.getSourceLocale() : undefined; + const authored = typeof source === 'string' && source.length > 0 + ? source + : typeof service.getDefaultLocale === 'function' ? service.getDefaultLocale() : undefined; + const options: ResolveOptions = { + locale, + ...(typeof fallback === 'string' && fallback.length > 0 ? { fallbackChain: [fallback] } : {}), + ...(typeof authored === 'string' && authored.length > 0 ? { defaultLocale: authored } : {}), + }; + return { bundle: Object.keys(bundle).length > 0 ? (bundle as TranslationBundle) : undefined, options }; +} + /** * The labels for a reader whose `ExecutionContext.locale` is `requested`, or * `undefined` when this read can pick nothing: no locale, or no service with a @@ -180,17 +250,38 @@ export function readerLabelsFor( } return undefined; }; - const picked = new Map(); - const pick = (key: string): string | undefined => { - if (picked.has(key)) return picked.get(key); - const answer = render(key); - picked.set(key, answer); - return answer; + const memo = ( + seen: Map, + key: string, + answer: () => string | undefined, + ): string | undefined => { + if (seen.has(key)) return seen.get(key); + const value = answer(); + seen.set(key, value); + return value; }; + const picked = new Map(); + const pick = (key: string): string | undefined => memo(picked, key, () => render(key)); + // [#35384] Built on the first object label this read asks, once. + let translation: { value: ObjectLabelTranslation | undefined } | undefined; + const objectLabels = new Map(); + const objectLabel = (objectName: string): string | undefined => + memo(objectLabels, objectName, () => { + try { + translation ??= { value: objectLabelTranslation(service, locale) }; + if (!translation.value) return undefined; + const doc: ObjectLike = { name: objectName }; + const label = translateObject(doc, translation.value.bundle, translation.value.options).label; + return typeof label === 'string' && label.trim().length > 0 ? label : undefined; + } catch { + // A misbehaving i18n service must not fail the read: the stored label stands. + return undefined; + } + }); return { flowLabel: (flowName) => pick(flowLabelKey(flowName)), stepLabel: (flowName, nodeId) => pick(approvalStepLabelKey(flowName, nodeId)), - objectLabel: (objectName) => pick(objectLabelKey(objectName)), + objectLabel, positionLabel: (positionName) => pick(positionLabelKey(positionName)), sentence: (key, params) => render(key, params), }; diff --git a/packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts b/packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts index 75f50d4e015..17b0e24ce35 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts @@ -46,6 +46,22 @@ import { bindApprovalLockHook, APPROVALS_HOOK_PACKAGE } from './lifecycle-hooks. import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { installDefaultOrganization } from './default-organization.testkit.js'; +/** + * [#35384] A flat `a.b.c` pack as the nested data `II18nService.getTranslations()` + * hands over: the object label is read off it by `translateObject`, as `/meta` + * reads it, never through `t()`. + */ +function nestedPack(flat: Record = {}): Record { + const out: Record = {}; + for (const [key, value] of Object.entries(flat)) { + const parts = key.split('.'); + let cur = out; + for (const part of parts.slice(0, -1)) cur = cur[part] ??= {}; + cur[parts[parts.length - 1]] = value; + } + return out; +} + const OPPORTUNITY = { name: 'opportunity', label: 'Opportunity', @@ -296,6 +312,7 @@ describe('[#34060] the per-row refusal is worded in the writer\'s locale', () => }; const i18n = { getLocales: () => Object.keys(PACKS), + getTranslations: (locale: string) => nestedPack(PACKS[locale]), t: (key: string, locale: string) => PACKS[locale]?.[key] ?? key, }; @@ -405,6 +422,7 @@ describe('[#34060] the per-row refusal is worded in the writer\'s locale', () => it('a deployment translation of `errors.record_locked` wins, interpolated', async () => { const override = { getLocales: () => ['zh-CN'], + getTranslations: i18n.getTranslations, t: (key: string, locale: string) => key === 'errors.record_locked' && locale === 'zh-CN' ? '{{object}}《{{title}}》审批中,暂不可改' : i18n.t(key, locale), }; @@ -446,6 +464,7 @@ describe('[#34454] the record-lock override is asked with the negotiated locale' /** `FileI18nAdapter`-shaped: exact tag match, `{{name}}` interpolation of `params`, the key echoed on a miss. */ const exactMatchI18n = { getLocales: () => Object.keys(PACKS), + getTranslations: (locale: string) => nestedPack(PACKS[locale]), t: (key: string, locale: string, params?: Record) => { const value = PACKS[locale]?.[key]; if (value === undefined) return key; diff --git a/packages/plugins/plugin-audit/src/activity-summary-message.test.ts b/packages/plugins/plugin-audit/src/activity-summary-message.test.ts index a00b064f8d6..c5ece995b7b 100644 --- a/packages/plugins/plugin-audit/src/activity-summary-message.test.ts +++ b/packages/plugins/plugin-audit/src/activity-summary-message.test.ts @@ -183,3 +183,85 @@ describe('localizeActivityRow — the read-side overlay', () => { expect(unprojected).not.toHaveProperty('summary'); }); }); + +/** + * [#35384] The object, field and option labels inside a reader's summary are + * resolved the way the metadata route serves them — `translateObject` over + * every locale the service holds, with `/meta`'s `ResolveOptions` (the + * reader's locale, the declared fallback chain, and the authored language: + * the declared `sourceLocale`, else `defaultLocale`) — and never through + * `t()`. + * + * The scenario: an app authored in English (`sourceLocale: 'en'`) that + * defaults its users to Chinese (`defaultLocale: 'zh-CN'`, the fallback `t()` + * falls to) and ships `zh-CN` labels only. `/meta` answers an `en` request + * with the authored labels (`packages/rest/src/meta-i18n-declared-fallback-chain.test.ts` + * §6 pins that half); the summary must name the same ones. CONTROLS: a + * `zh-CN` reader still reads the `zh-CN` labels, and with no `sourceLocale` + * declared an `en` reader walks the declared fallback to them, as `/meta` + * does. + */ +describe('[#35384] a reader in the declared sourceLocale reads the labels as authored', () => { + /** The real in-memory service, declared as `AppPlugin.loadTranslations` declares it. */ + const declaredMemory = () => { + const i18n = makeI18n(); + i18n.setDefaultLocale('zh-CN'); + i18n.setFallbackLocale('zh-CN'); + i18n.setSourceLocale('en'); + return i18n; + }; + /** The served adapter's shape (`FileI18nAdapter`): the declared fallback, read back by `getFallbackLocale()`. */ + const served = (declared: { sourceLocale?: string }) => { + const i18n = makeI18n(); + i18n.setDefaultLocale('zh-CN'); + i18n.setFallbackLocale('zh-CN'); + if (declared.sourceLocale) i18n.setSourceLocale(declared.sourceLocale); + return Object.assign(i18n, { getFallbackLocale: () => 'zh-CN' }); + }; + + it('an en reader names the object, the fields and the option as authored', () => { + const i18n = declaredMemory(); + // The defect's precondition, read at the same service: `t()` falls to the zh-CN rows. + expect(i18n.t('objects.biz_deal.label', 'en')).toBe('商机'); + expect(i18n.t('objects.biz_deal.fields.stage.options.won', 'en')).toBe('赢单'); + const en = readerSummaryLocale(i18n, 'en', getObjectDef)!; + expect(composeActivitySummary(CREATED, en)).toBe('Created Deal "Acme"'); + expect(composeActivitySummary(NAMED, en)).toBe('Updated Deal "Acme": Amount, Owner, and 2 more'); + expect(composeActivitySummary(CHANGES, en)).toBe('Stage: ∅ → Won; Owner: 张伟 → Ana'); + }); + + it('the same, through a service that declares its fallback chain', () => { + const en = readerSummaryLocale(served({ sourceLocale: 'en' }), 'en', getObjectDef)!; + expect(composeActivitySummary(CREATED, en)).toBe('Created Deal "Acme"'); + expect(composeActivitySummary(CHANGES, en)).toBe('Stage: ∅ → Won; Owner: 张伟 → Ana'); + }); + + it('CONTROL: a zh-CN reader still reads the zh-CN labels', () => { + const zhReader = readerSummaryLocale(declaredMemory(), 'zh-CN', getObjectDef)!; + expect(composeActivitySummary(CREATED, zhReader)).toBe('创建了 商机 "Acme"'); + expect(composeActivitySummary(CHANGES, zhReader)).toBe('阶段: ∅ → 赢单; Owner: 张伟 → Ana'); + }); + + it('CONTROL: with no sourceLocale declared, an en reader walks the declared fallback to the zh-CN labels', () => { + const en = readerSummaryLocale(served({}), 'en', getObjectDef)!; + expect(composeActivitySummary(CREATED, en)).toBe('Created 商机 "Acme"'); + expect(composeActivitySummary(CHANGES, en)).toBe('阶段: ∅ → 赢单; Owner: 张伟 → Ana'); + }); + + it('reads no label through t(): a service that cannot hand its translations over keeps the authored labels', () => { + const i18n = makeI18n(); + const tOnly = { t: i18n.t.bind(i18n), getLocales: i18n.getLocales.bind(i18n) }; + const zhReader = readerSummaryLocale(tOnly, 'zh-CN', getObjectDef)!; + expect(composeActivitySummary(CREATED, zhReader)).toBe('创建了 Deal "Acme"'); + }); + + it('a service whose translations throw keeps the authored labels, never a failed read', () => { + const i18n = makeI18n(); + const throwing = { + t: i18n.t.bind(i18n), + getLocales: i18n.getLocales.bind(i18n), + getTranslations: () => { throw new Error('translations exploded'); }, + }; + expect(composeActivitySummary(CREATED, readerSummaryLocale(throwing, 'zh-CN', getObjectDef)!)).toBe('创建了 Deal "Acme"'); + }); +}); diff --git a/packages/plugins/plugin-audit/src/activity-summary-message.ts b/packages/plugins/plugin-audit/src/activity-summary-message.ts index 18770b7a4fb..48d03319155 100644 --- a/packages/plugins/plugin-audit/src/activity-summary-message.ts +++ b/packages/plugins/plugin-audit/src/activity-summary-message.ts @@ -41,6 +41,17 @@ * `II18nService.t()`. ⛔ Nothing here is a second way to do that: it is the * sequence `plugin-approvals`'s `reader-locale-labels.ts` uses. * + * [#35384] The object, field and option LABELS inside the sentence are + * metadata `/meta` serves, so they are not read through `t()`: the reader's + * object definition is put in its language by `translateObject` + * (`@objectstack/spec/system`) over every locale the service holds, with the + * metadata route's `ResolveOptions` (the reader's locale, the DECLARED + * fallback chain, and the authored language — the declared `sourceLocale`, + * else `defaultLocale`), and every label is read off that definition. So a + * reader in a deployment's declared `sourceLocale` reads the labels as + * authored, never the `defaultLocale` row `t()` falls back to; `t()` carries + * the `messages.*` templates. + * * The writer composes the stored sentence through the SAME function * ({@link composeActivitySummary}), bound to the write locale, with the English * catalog as its fallback, so the stored text and a reader's text can never be @@ -56,7 +67,12 @@ * is the author's sentence and is never translated (#7290). */ -import { resolveBundleLocale } from '@objectstack/spec/system'; +import { + resolveBundleLocale, + translateObject, + type ResolveOptions, + type TranslationBundle, +} from '@objectstack/spec/system'; import { enMessages } from './translations/messages.js'; import { ensureJudgedColumnsProjected, isRecord } from './served-fields.js'; @@ -110,7 +126,11 @@ export interface ActivitySummaryLocale { translate(key: string, params?: Record): string | undefined; /** The locale a list is joined in; `undefined` joins in English. */ locale: string | undefined; - /** The object's registered definition, for its authored labels; `null` when there is none. */ + /** + * The object's definition its labels are read off, `null` when there is + * none: the authored one for the writer, and [#35384] for a reader the one + * `translateObject` put in the reader's language. + */ getObjectDef(objectName: string): any; } @@ -122,8 +142,8 @@ function interpolate(template: string, params: Record = {}): st /** * `locale` with this plugin's ENGLISH catalog answering every `messages.*` * key: what the stored sentence falls back to when the write locale has no - * template. Every other key (object, field and option labels) is still asked - * of `locale`, as the writer always has. + * template. Every other key is still asked of `locale`, and the labels are + * still read off `locale`'s definitions ([#35384] never a `t()` key). */ export function withEnglishMessages(locale: ActivitySummaryLocale): ActivitySummaryLocale { return { @@ -137,30 +157,35 @@ export function withEnglishMessages(locale: ActivitySummaryLocale): ActivitySumm }; } -/** An object's label: the locale bundle's, then the authored def label, then the name. */ +/** + * An object's label: the definition's ({@link ActivitySummaryLocale.getObjectDef}, + * in the reader's language for a reader), then the name. + */ export function objectLabelIn(locale: ActivitySummaryLocale, objectName: string): string { const def = locale.getObjectDef(objectName); - return ( - locale.translate(`objects.${objectName}.label`) ?? - (typeof def?.label === 'string' && def.label.length > 0 ? def.label : objectName) - ); + return typeof def?.label === 'string' && def.label.length > 0 ? def.label : objectName; } /** - * A field's label inside an activity summary: the locale bundle's - * (`objects..fields..label`), then the authored def label, then - * the machine key. One answer for every branch that names a field. + * A field's label inside an activity summary: the definition's (in the + * reader's language for a reader), then the machine key. One answer for every + * branch that names a field. */ -export function fieldLabelForSummary( - objectName: string, - key: string, - field: any, - translate: (key: string, params?: Record) => string | undefined, -): string { - return ( - translate(`objects.${objectName}.fields.${key}.label`) ?? - (typeof field?.label === 'string' && field.label.length > 0 ? field.label : key) - ); +export function fieldLabelForSummary(key: string, field: any): string { + return typeof field?.label === 'string' && field.label.length > 0 ? field.label : key; +} + +/** A select value's option label on the definition's field, `undefined` when the field declares none for it. */ +function optionLabelOn(field: any, option: string): string | undefined { + const options: unknown = field?.options; + if (!Array.isArray(options)) return undefined; + for (const candidate of options) { + if (candidate && typeof candidate === 'object' && String((candidate as { value?: unknown }).value) === option) { + const label = (candidate as { label?: unknown }).label; + return typeof label === 'string' && label.length > 0 ? label : undefined; + } + } + return undefined; } /** A locale's conjunction list ("A, B, and C" / "A、B和C"); `", "` where `Intl` cannot answer. */ @@ -211,7 +236,7 @@ export function composeActivitySummary( return translate('messages.activityUpdated', frame); } const fields = locale.getObjectDef(message.object)?.fields; - const items = message.fields.map((key) => fieldLabelForSummary(message.object, key, fields?.[key], translate)); + const items = message.fields.map((key) => fieldLabelForSummary(key, fields?.[key])); if (message.more > 0) { items.push( translate('messages.activityMoreFields', { count: message.more }) ?? @@ -224,14 +249,14 @@ export function composeActivitySummary( const fields = locale.getObjectDef(message.object)?.fields; const valueIn = (field: string, value: ActivitySummaryValue): string => value.option !== undefined - ? (translate(`objects.${message.object}.fields.${field}.options.${value.option}`) ?? value.text) + ? (optionLabelOn(fields?.[field], value.option) ?? value.text) : typeof value.boolean === 'boolean' ? (translate(`messages.${booleanMessageKey(value.boolean)}`) ?? value.text) : value.text; return message.changes .map( (c) => - `${fieldLabelForSummary(message.object, c.field, fields?.[c.field], translate)}: ` + + `${fieldLabelForSummary(c.field, fields?.[c.field])}: ` + `${valueIn(c.field, c.from)} → ${valueIn(c.field, c.to)}`, ) .join('; '); @@ -273,10 +298,59 @@ export function readActivitySummaryMessage(value: unknown): ActivitySummaryMessa return null; } -/** The slice of `II18nService` a read asks: `t()`, and `getLocales()` to negotiate when offered. */ +/** + * The slice of `II18nService` a read asks: `t()`, `getLocales()` to negotiate + * when offered, and [#35384] the members the labels are resolved by, as the + * metadata route reads them. + */ export interface ActivitySummaryI18n { t(key: string, locale: string, params?: Record): string; getLocales?(): unknown; + getTranslations?(locale: string): unknown; + getFallbackLocale?(): string | undefined; + getSourceLocale?(): string | undefined; + getDefaultLocale?(): string; +} + +/** + * [#35384] What the metadata route (`GET /meta/object/:name`) translates an + * object definition with, for a request in `locale`: the bundle — every locale + * `service` holds, keyed by locale (`translationBundleOf` in rest) — and the + * `ResolveOptions` that route builds (`metaTranslateOptions` in rest): the + * request's locale, the DECLARED fallback chain (`getFallbackLocale()`), and + * the authored language — the declared `sourceLocale` (`getSourceLocale()`), + * else `defaultLocale` (`getDefaultLocale()`). Each getter is + * feature-detected; a service that declares none gets none. The locale is + * the negotiated one, as objectql's refusal labels hand `translateObject`. + * + * `undefined` — the authored labels stand — for a service that cannot hand its + * translations over (no `getLocales` / `getTranslations`). A throwing service + * is the caller's to survive. + */ +function labelTranslationOf( + service: ActivitySummaryI18n, + locale: string, +): { bundle: TranslationBundle | undefined; options: ResolveOptions } | undefined { + if (typeof service.getLocales !== 'function' || typeof service.getTranslations !== 'function') return undefined; + const locales = service.getLocales(); + if (!Array.isArray(locales)) return undefined; + const bundle: Record = {}; + for (const code of locales) { + if (typeof code !== 'string' || code.length === 0) continue; + const data = service.getTranslations(code); + if (data && typeof data === 'object') bundle[code] = data; + } + const fallback = typeof service.getFallbackLocale === 'function' ? service.getFallbackLocale() : undefined; + const source = typeof service.getSourceLocale === 'function' ? service.getSourceLocale() : undefined; + const authored = typeof source === 'string' && source.length > 0 + ? source + : typeof service.getDefaultLocale === 'function' ? service.getDefaultLocale() : undefined; + const options: ResolveOptions = { + locale, + ...(typeof fallback === 'string' && fallback.length > 0 ? { fallbackChain: [fallback] } : {}), + ...(typeof authored === 'string' && authored.length > 0 ? { defaultLocale: authored } : {}), + }; + return { bundle: Object.keys(bundle).length > 0 ? (bundle as TranslationBundle) : undefined, options }; } /** @@ -304,6 +378,11 @@ function negotiatedLocale(service: ActivitySummaryI18n, requested: string): stri * The language a reader whose `ExecutionContext.locale` is `requested` reads * in, or `undefined` when this read can compose nothing: no locale, or no * service with a `t()`. + * + * [#35384] Its `getObjectDef` answers the definition `translateObject` put in + * the reader's language ({@link labelTranslationOf}), built once per object + * for the read; the authored definition when there is nothing to translate + * with, or the translator throws. */ export function readerSummaryLocale( service: ActivitySummaryI18n | undefined, @@ -313,6 +392,25 @@ export function readerSummaryLocale( if (typeof requested !== 'string' || requested.length === 0) return undefined; if (!service || typeof service.t !== 'function') return undefined; const locale = negotiatedLocale(service, requested); + let translation: { value: ReturnType } | undefined; + const definitions = new Map(); + const translatedObjectDef = (objectName: string): any => { + if (definitions.has(objectName)) return definitions.get(objectName); + const def = getObjectDef(objectName); + let served = def; + if (def && typeof def === 'object') { + try { + translation ??= { value: labelTranslationOf(service, locale) }; + if (translation.value) { + served = translateObject({ ...def, name: objectName }, translation.value.bundle, translation.value.options); + } + } catch { + // A misbehaving i18n service must not fail the read: the authored labels stand. + } + } + definitions.set(objectName, served); + return served; + }; return { translate: (key, params) => { try { @@ -325,7 +423,7 @@ export function readerSummaryLocale( } }, locale, - getObjectDef, + getObjectDef: translatedObjectDef, }; } diff --git a/packages/plugins/plugin-audit/src/audit-option-label-summary.test.ts b/packages/plugins/plugin-audit/src/audit-option-label-summary.test.ts index d796a48ff90..9eceb9efa74 100644 --- a/packages/plugins/plugin-audit/src/audit-option-label-summary.test.ts +++ b/packages/plugins/plugin-audit/src/audit-option-label-summary.test.ts @@ -425,15 +425,22 @@ describe('[#7289] tracked-change branch — select option labels resolve through expect(readerSummary()).toBe('阶段: 提案中 → On Hold'); }); - it('localizes the BARE-STRING option shape, whose authored label is the value', async () => { + /** + * [#35384] A reader's option labels are read off the definition + * `translateObject` serves, the one `/meta` serves the field with, and that + * translator translates an option OBJECT only: a bare string is not a + * `SelectOptionSchema` (a strict object with a `label`), so `/meta` serves + * `p1` as written, and the summary names it the same way. The field's own + * label is still translated. + */ + it('names a BARE-STRING option (not a spec option) by its value, as /meta serves it', async () => { const { engine, readerSummary } = await boot({ locale: 'zh-CN', i18n: makeI18n() }); await seed(engine); // `options: ['p1', 'p2']` → the authored label chain has only `ov` in it. - // `p1` is in the bundle, `p2` is not, so both directions are pinned here. await engine.update('biz_deal', { priority: 'p1' }, { where: { id: 'deal_1' } } as any); - expect(readerSummary()).toBe('优先级: p2 → 最高'); + expect(readerSummary()).toBe('优先级: p2 → p1'); }); it('renders String(value) for a value matching NO declared option, bundle key or not', async () => { diff --git a/packages/services/service-automation/src/flow-write-refusal-locale.integration.test.ts b/packages/services/service-automation/src/flow-write-refusal-locale.integration.test.ts index 088fea7176c..82b8216d98a 100644 --- a/packages/services/service-automation/src/flow-write-refusal-locale.integration.test.ts +++ b/packages/services/service-automation/src/flow-write-refusal-locale.integration.test.ts @@ -78,7 +78,8 @@ const ZH_BUNDLE: Record = { 'objects.crm_deal.fields.account.label': '所属客户', }; // [#34030] A refusal's labels are read off `getTranslations`, the bundle the -// metadata route serves them from; the rule message stays on `t()`. +// metadata route serves them from. [#35384] So is the authored rule message, +// metadata `/meta` serves by `translateObject`: `t()` carries no entry of it. const zhI18n = { t: (key: string, locale: string) => (locale?.startsWith('zh') ? ZH_BUNDLE[key] ?? key : key), getLocales: () => ['zh-CN'], @@ -86,7 +87,11 @@ const zhI18n = { ? { objects: { crm_account: { label: '客户' }, - crm_deal: { label: '商机', fields: { account: { label: '所属客户' } } }, + crm_deal: { + label: '商机', + fields: { account: { label: '所属客户' } }, + _validations: { amount_not_negative: { message: RULE_ZH } }, + }, }, } : {}),