Skip to content

Commit 6d0089c

Browse files
fix(objectql,approvals,audit): rule messages, approval object labels and activity-summary labels read as /meta serves them in a declared sourceLocale (#36464)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9Ubb3T2gwH6MWTYde4qF8edEDN)_ Part of #35384 — this PR moves three of the card's readers onto the `/meta` resolve path. The approval NOTIFICATION subject param stays open: it is resolved per recipient at delivery by service-messaging's general keyed-param path, so it is left for the area to file (see Acceptance notes). Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:应用以英文编写、默认面向中文用户时,英文用户在审批收件箱、审批页、活动记录摘要和自定义校验规则的报错里看到英文原文,不再夹杂默认语言的中文;中文用户看到的不变。 - 为什么做:这是多语言标签统一的后续:让这三处和对象元数据接口用同一种方式取标签。 - 出错会怎样:最坏情况是某处标签显示成原文而不是译文,不影响数据和权限,合并后可直接回退。 - 要你做什么:无 ## What changes The #34030 rule, quoted from the card: "resolve the label through `translateObject` with the same resolve options `/meta` builds, so `t()` carries messages only." - **objectql** (`validation/rule-validator.ts`, `authoredRuleMessage`): an author-written rule message (`objects.OBJECT._validations.RULE.message`) now resolves through `translatedLabels` over `ValidationMessageContext.labelTranslation`. That is the bundle plus `ResolveOptions` that the same refusal's field, option and object labels already read (#34030), so this half adds no copy of the options. The ADR-0029 D9.2a tenant-rewrite check is unchanged. `translate` (that is, `t()`) now carries only the built-in messages. - **plugin-approvals** (`reader-locale-labels.ts`, `readerLabelsFor().objectLabel`): the object label resolves through `translateObject` over every locale the service holds, with the metadata route's options: the negotiated reader locale, the declared fallback chain, and `sourceLocale` else `defaultLocale`. This one change covers the inbox row, the request page, the generic data door's request rows and the two lifecycle refusals that name an object. Flow, step and position labels and the catalog sentences stay on `t()`. - **plugin-audit** (`activity-summary-message.ts`): `readerSummaryLocale` hands the composer the object definition that `translateObject` put in the reader's language. The object, field and select-option labels are read off that definition and no longer come from `t()` keys. The writer's stored sentence is unchanged, because its locale already reads only authored labels. - A service that cannot hand its translations over (no `getLocales()` / `getTranslations()`) no longer gets these labels translated through `t()`: the authored text stands. Every service the platform ships implements both. ## Tests - objectql `engine-label-source-locale.test.ts`: new top-level describe for the authored rule message under `sourceLocale: 'en'` / `defaultLocale: 'zh-CN'`. An `en` write reads the authored sentence. Controls: a `zh-CN` write reads the zh-CN row, and with no `sourceLocale` an `en` write walks to the zh-CN row. - objectql `validation/rule-validator.test.ts` (#14253 and D9.2a describes) moved from `translate` doubles to `labelTranslation`. The first case wires a `t()` decoy beside it, so a regression back to `t()` turns it red. - objectql `engine-validation-locale-negotiation.test.ts` and `engine-validation-tenant-rewrite.test.ts`: the served-adapter doubles gain `getTranslations` / `getFallbackLocale`, which `FileI18nAdapter` has. The three `t()`-locale probes in the negotiation suite now trip a built-in `max_length` message, the sentence the `t()` bridge still carries. - plugin-approvals `reader-locale-labels.test.ts` and plugin-audit `activity-summary-message.test.ts`: a new `[#35384]` describe in each. Each covers the real in-memory service and the served-adapter shape, and asserts that `t()` itself answers the zh-CN row at the same service, so the defect's precondition is measured and not assumed. Also covered: the two controls, a `t()`-only service, and a throwing `getTranslations`. - `/meta`'s half of the same scenario is pinned in `packages/rest/src/meta-i18n-declared-fallback-chain.test.ts` §6. ## Acceptance notes - **Not fixed here, left for the area to file:** the approval notification subject param (`approval-notification-text.ts` `subjectParams`, `{ key: objects.OBJECT.label, fallback }`). It is resolved at delivery by `packages/services/service-messaging/src/notification-text.ts` (`renderWith`: `lookup(i18n, param.key, locale) ?? param.fallback`, through `t()`). The producer holds no recipient locale at emit, so it cannot hand over a resolved label. The only messaging fix would parse the key shape inside the per-delivery param resolver that every producer's keyed params share, which goes past the narrow widening the area allowed. **Routed (seat):** this is the #35384 remainder, released back to `pm:queue` on merge as a typed object-label param in `NotificationTextKeys` that service-messaging resolves through `translateObject` (`domain:server`), together with `readerLabelsFor`'s flow, step and position labels. - **Folded into the same #35384 remainder (L1 7081082388):** the two readers this PR moves hand `translateObject` the metadata route's resolve options but not its packaged base. plugin-approvals `objectLabel` passes `{ name }` alone, and plugin-audit `translatedObjectDef` passes no `packagedBase`. So for a renamed object (a served label that diverged from the packaged one) they read the translation of the old label, where `/meta` serves the rename. This is not a regression: `t('objects.<o>.label')` did the same. The fix is the `getPackagedObjectBase` read #36460 threads for the share-link label. Until then, the docblocks' "as `/meta` resolves it" holds for the resolve options only. - **Measured: `en-US` under `sourceLocale: 'en'`.** `/meta` hands `translateObject` the request tag as written. objectql (#34030) and now these readers hand it the tag negotiated against the service's locales. When the service holds an `en` locale (any `en` catalog), an `en-US` request gets `客户` (the defaultLocale row) from `/meta` and `Account` from objectql. With no `en` locale held, both give `客户`. Reading taken with `translateObject` from this branch's `@objectstack/spec` dist at c0111e2. Raised as a decision; not changed here. **Filed:** #36466 (`/meta` negotiates the request locale first; no spec change). - No resolve-options builder is reachable from plugin-approvals or plugin-audit: rest's `metaTranslateOptions` is not a dependency, and objectql's `labelTranslationOf` is private. So each plugin carries the same few lines that plugin-security and objectql inlined in #34030, with a docblock naming `metaTranslateOptions`. **Filed:** #36467 (one exported spec builder, contract tier). ## Verification Two-minute check: `pnpm --filter @objectstack/plugin-approvals exec vitest run --maxWorkers=2 src/reader-locale-labels.test.ts`. Expect every case to pass, including `[#35384] … an en reader picks no defaultLocale row`. Read first: 1. `packages/plugins/plugin-audit/src/activity-summary-message.ts`, the `readerSummaryLocale` / `translatedObjectDef` hunk (the reader's definitions are now the translated ones). 2. `packages/objectql/src/validation/rule-validator.ts`, the `authoredRuleMessage` hunk. 3. `packages/plugins/plugin-approvals/src/reader-locale-labels.ts`, the `objectLabel` hunk. <details><summary>Test readings (b815112 unless stated; fix round at final head 67d23af first)</summary> - Fix round at 67d23af (CI Test Core 6/10 red on b815112: 4 cases in `packages/services/service-automation/src/flow-write-refusal-locale.integration.test.ts`, whose i18n double held the rule message only as a `t()` key, so the bundle read now returned the authored English). The double's zh-CN bundle gains `objects.crm_deal._validations.amount_not_negative.message`. It is a fixture change of spelling only: no assertion changed and nothing was skipped. In that file, Tests 8 passed (8). `@objectstack/service-automation` 290/290 files, 4222/4222 tests. `@objectstack/plugin-approvals` 126/126 files, 1853/1853. `@objectstack/plugin-audit` 109/109 files, 1800/1800. Lock VERDICT command-exit 0. overlap-check at 67d23af is clean. A sweep of the other tests that combine validations, an i18n service and a non-en locale found no further consumer. - objectql `pnpm --filter @objectstack/objectql test` at 8be4929 (objectql is unchanged after it): Test Files 628 passed (628), Tests 14286 passed (14286); lock VERDICT command-exit 0. - plugin-audit `pnpm --filter @objectstack/plugin-audit test` at b61713e: 107/109 files, 1798/1800 tests. Two failures: the new pin's expected list wording, and the bare-string option case (triaged below). After the fix, those two files at b815112: Tests 31 passed (31). - plugin-approvals `pnpm --filter @objectstack/plugin-approvals test` at b61713e: 125/126 files, 1846/1853 tests. Seven failures, all in `record-lock-user-facing-message.test.ts`, whose doubles answered labels through `t()` only. After those doubles gained `getTranslations`, that file and `reader-locale-labels.test.ts` at b815112: Tests 41 passed (41). - typecheck at b815112: objectql exit 0, plugin-audit exit 0, plugin-approvals exit 0. At b61713e approvals failed with TS2339 on the label-only doc literal; fixed with an `ObjectLike` annotation. - Fixture triage: the bare-string option `options: ['p1', 'p2']` is not a `SelectOptionSchema` (strict object with `label`). `translateObject`, and so `/meta`, serves it as written. The #7289 case now pins `p1` as `/meta` serves it, where it used to pin the `t()` row. </details> <details><summary>Reverse verification (each fixed source file put back to origin/main, its pins run, then restored)</summary> At b61713e, under one lock call, the scratch script used `git restore --source=BASE` (tree only), checked the BASE blob hash on disk, then `git checkout HEAD --` and checked the HEAD blob hash. Pins resolve `src/` directly, so no dist step is involved. - `rule-validator.ts` at BASE: `engine-label-source-locale.test.ts` 1 failed / 8 (`an en write reads the authored English sentence`). - `reader-locale-labels.ts` at BASE: `reader-locale-labels.test.ts` 4 failed / 22 (both `en reader picks no defaultLocale row` cases, the inbox-row case, and the `t()`-only case). - `activity-summary-message.ts` at BASE: `activity-summary-message.test.ts` 4 failed / 18 (both `en reader` cases, the `t()`-only case, and the throwing-translations case). - Controls stayed green on every leg. After restore, `git diff HEAD` was empty. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 74 families; reconciliation with `--ran` reported 74 derived, 74 run. - 70 exit 0 at b61713e. Re-run at b815112, exit 0: `check:type-check-debt` (a PREREQUISITE exit 3 on the first pass, while a sibling build held dist), `check:type-check-coverage`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check:undeclared-dep-imports`, `check:nul-bytes`, `check:engine-double-contract`, `check:doc-authoring`, `check:issue-citations`. - NOT MEASURED locally, left to CI: `check:i18n` (needs the built CLI closure), `check:dual-build-cjs-loads` (needs a full build), and `check-plugin-teardown-shape --self-test` (needs a commit this shallow clone does not have). - `overlap-check --branch=HEAD`: clean against origin/main and #36399. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jTyyBmoPBsURQjeJGq)_ <!-- signed: repo:objectstack#7 · zhuangjianguo · session_01QsR2jTyyBmoPBsURQjeJGq --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent dda5e74 commit 6d0089c

13 files changed

Lines changed: 629 additions & 97 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/objectql': patch
3+
'@objectstack/plugin-approvals': patch
4+
'@objectstack/plugin-audit': patch
5+
---
6+
7+
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`
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
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:
13+
14+
- objectql: the author-written message of a validation rule (`objects.<object>._validations.<rule>.message`) in a `400 VALIDATION_FAILED` refusal;
15+
- 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;
16+
- plugin-audit: the object, field and select-option labels inside an activity summary composed in the reader's language.
17+
18+
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.
19+
20+
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.

‎packages/objectql/src/engine-label-source-locale.test.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,31 @@ const deal = {
6060
}],
6161
};
6262

63+
/**
64+
* [#35384] An object whose rule carries an AUTHORED message: the sentence is
65+
* metadata (`objects.<o>._validations.<rule>.message`), served by `/meta`'s
66+
* `translateObjectValidations`.
67+
*/
68+
const task = {
69+
name: 'lsl_task',
70+
label: 'Task',
71+
fields: {
72+
id: { name: 'id', type: 'text' as const, primaryKey: true },
73+
due: { name: 'due', type: 'text' as const, label: 'Due' },
74+
},
75+
validations: [{
76+
type: 'script',
77+
name: 'task_needs_due',
78+
message: 'A task needs a due date.',
79+
condition: "record.due == null || record.due == ''",
80+
fields: ['due'],
81+
}],
82+
};
83+
6384
/** The deployment ships `zh-CN` rows only. */
6485
const ZH_CN = {
6586
objects: {
87+
lsl_task: { label: '任务', _validations: { task_needs_due: { message: '任务必须设置截止日期。' } } },
6688
lsl_account: { label: '客户', fields: { name: { label: '名称' } } },
6789
lsl_deal: {
6890
label: '商机',
@@ -147,7 +169,7 @@ async function makeEngine(i18n: ReturnType<typeof servedI18n>) {
147169
const engine = new ObjectQL();
148170
engine.registerDriver(makeStubDriver(), true);
149171
await engine.init();
150-
for (const o of [account, deal]) engine.registry.registerObject(o as any);
172+
for (const o of [account, deal, task]) engine.registry.registerObject(o as any);
151173
engine.setI18nService(i18n);
152174
return engine;
153175
}
@@ -213,3 +235,34 @@ describe('a refusal in the declared sourceLocale names labels as authored', () =
213235
for (const word of ['客户', '商机', '所属客户']) expect(object.message).toContain(word);
214236
});
215237
});
238+
239+
/**
240+
* [#35384] The authored rule message resolves by the same rule: through
241+
* `translateObject` over the metadata route's `ResolveOptions`, so an `en`
242+
* write in a deployment authored in English reads the sentence as written —
243+
* what `/meta` serves the same rule's `message` as for an `en` request
244+
* (`packages/rest/src/meta-i18n-declared-fallback-chain.test.ts` §6 pins that
245+
* half) — never the `zh-CN` row `t()` falls back to.
246+
*/
247+
describe('an authored rule message in the declared sourceLocale reads as authored', () => {
248+
const refusal = async (declared: Parameters<typeof servedI18n>[0], locale: string) =>
249+
refused((await makeEngine(servedI18n(declared))).insert('lsl_task', { due: '' }, { context: { locale } as any }));
250+
251+
it('an en write reads the authored English sentence', async () => {
252+
const err = await refusal(SOURCE_EN, 'en');
253+
expect(err.code).toBe('VALIDATION_FAILED');
254+
expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: 'A task needs a due date.' });
255+
});
256+
257+
it('CONTROL: a zh-CN write still reads the zh-CN row', async () => {
258+
const err = await refusal(SOURCE_EN, 'zh-CN');
259+
expect(err.code).toBe('VALIDATION_FAILED');
260+
expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: '任务必须设置截止日期。' });
261+
});
262+
263+
it('CONTROL: with no sourceLocale declared, an en write walks to the zh-CN row as before', async () => {
264+
const err = await refusal({ defaultLocale: 'zh-CN' }, 'en');
265+
expect(err.code).toBe('VALIDATION_FAILED');
266+
expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: '任务必须设置截止日期。' });
267+
});
268+
});

‎packages/objectql/src/engine-validation-locale-negotiation.test.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,10 @@ function servedI18n(bundle: Record<string, any>, fallbackLocale = 'en') {
9595
return typeof fallback === 'string' ? fallback : key;
9696
},
9797
getLocales: () => Object.keys(bundle),
98+
// [#35384] The authored rule message is metadata: it is read off the
99+
// bundle by `translateObject`, as `/meta` reads it, never through `t()`.
100+
getTranslations: (locale: string) => bundle[locale] ?? {},
101+
getFallbackLocale: () => fallbackLocale,
98102
};
99103
}
100104

@@ -105,6 +109,9 @@ const DUTY_SCHEMA = {
105109
form: { type: 'select', label: 'Form' },
106110
status: { type: 'select', label: 'Status' },
107111
return_note: { type: 'text', label: 'Return note' },
112+
// [#35384] Refused by a BUILT-IN message (`max_length`), the sentence the
113+
// `t()` bridge still carries: the probe of what locale the bridge asks.
114+
code: { type: 'text', label: 'Code', maxLength: 3 },
108115
},
109116
validations: [{
110117
type: 'script',
@@ -168,6 +175,22 @@ async function refusalFor(header: string, i18n: ReturnType<typeof servedI18n>):
168175
return (await refusalEnvelopeFor(header, i18n)).message;
169176
}
170177

178+
/**
179+
* [#35384] A write refused by a BUILT-IN message (`code` over its
180+
* `maxLength`), which renders through the `t()` bridge — the one the locale
181+
* negotiation below is asserted on, now that the authored rule message reads
182+
* the bundle through `translateObject` instead.
183+
*/
184+
async function builtinRefusalFor(locale: string | undefined, i18n: Parameters<typeof makeEngine>[0]): Promise<unknown> {
185+
const ql = await makeEngine(i18n);
186+
try {
187+
await ql.update('duly_duty', { id: 'r1', code: 'too long' }, { context: { locale } } as any);
188+
} catch (e) {
189+
return e;
190+
}
191+
throw new Error('expected the write to be rejected');
192+
}
193+
171194
/** PATH B — the cross-path control: a document translator, same bundle, same header. */
172195
function datasetStyleLabelsFor(header: string): string[] {
173196
const locale = preferredLocaleFromHeader(header);
@@ -278,7 +301,7 @@ describe('#15757 the validation-message bridge negotiates the locale like every
278301
it('asks the service for the locale it actually has, not the tag the client sent', async () => {
279302
const i18n = servedI18n(BUNDLE);
280303
expect(preferredLocaleFromHeader('zh')).toBe('zh');
281-
await refusalFor('zh', i18n);
304+
await builtinRefusalFor(preferredLocaleFromHeader('zh'), i18n);
282305
expect(i18n.asked).not.toContain('zh');
283306
expect(i18n.asked).toContain('zh-CN');
284307
});
@@ -291,6 +314,7 @@ describe('#15757 the validation-message bridge negotiates the locale like every
291314
it('leaves a locale with no match alone', async () => {
292315
const i18n = servedI18n(BUNDLE);
293316
expect(await refusalFor('de', i18n)).toBe(AUTHORED_EN);
317+
await builtinRefusalFor('de', i18n);
294318
expect(i18n.asked).toContain('de');
295319
});
296320

@@ -303,12 +327,9 @@ describe('#15757 the validation-message bridge negotiates the locale like every
303327
*/
304328
it('passes the tag through when the service cannot report its locales', async () => {
305329
const asked: string[] = [];
306-
const ql = await makeEngine({
330+
await builtinRefusalFor('zh', {
307331
t: (key: string, locale: string) => { asked.push(locale); return key; },
308332
});
309-
try {
310-
await ql.update('duly_duty', { id: 'r1', status: 'returned' }, { context: { locale: 'zh' } } as any);
311-
} catch { /* expected */ }
312333
expect(asked).toContain('zh');
313334
});
314335
});

‎packages/objectql/src/engine-validation-tenant-rewrite.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,10 @@ function servedI18n(bundle: Record<string, any>, fallbackLocale = 'en') {
130130
return typeof fallback === 'string' ? fallback : key;
131131
},
132132
getLocales: () => Object.keys(bundle),
133+
// [#35384] The refusal reads a rule message off the bundle by
134+
// `translateObject`, as `/meta` does, never through `t()`.
135+
getTranslations: (locale: string) => bundle[locale] ?? {},
136+
getFallbackLocale: () => fallbackLocale,
133137
};
134138
}
135139

‎packages/objectql/src/validation/rule-validator.test.ts‎

Lines changed: 59 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2464,25 +2464,38 @@ describe('evaluateValidationRules — built-in messages are localized (#3957)',
24642464
*
24652465
* The evaluator emitted the authored sentence verbatim, so a deployment with a
24662466
* complete `zh-CN` bundle read platform-generated refusals in Chinese and
2467-
* author-written refusals in English **inside one error envelope**. The
2468-
* built-in field catalog has resolved through `messages.translate` since #3957;
2469-
* what was missing was a key shape for an author's own rule, not a channel.
2467+
* author-written refusals in English **inside one error envelope**. What was
2468+
* missing was a key shape for an author's own rule, not a channel.
24702469
*
2471-
* These tests drive the SAME `ValidationMessageContext.translate` hook the
2472-
* built-in catalog uses (the engine's `i18nService`, `II18nService.t`
2473-
* semantics: the key is echoed back on a miss). If a second i18n path were ever
2474-
* added to objectql, this fixture would keep passing through the old one — so
2475-
* the address is asserted explicitly, not just the output.
2470+
* [#35384] The sentence is metadata (`objects.<o>._validations.<rule>.message`,
2471+
* the key `/meta`'s `translateObjectValidations` reads), so these tests drive
2472+
* `ValidationMessageContext.labelTranslation` — the bundle and the metadata
2473+
* route's `ResolveOptions` the refusal's labels read (#34030) — and never the
2474+
* `translate` (`t()`) hook, which carries the built-in messages only. A `t()`
2475+
* that would answer a rule message is wired beside it in the first test, so a
2476+
* reader that went back to `t()` reads the decoy.
24762477
*/
24772478
describe('evaluateValidationRules — authored rule messages resolve from the bundle (#14253)', () => {
2478-
/** An `II18nService.t`-shaped lookup over a flat key→string map. */
2479-
const service = (entries: Record<string, string>) => {
2480-
const seen: string[] = [];
2479+
/** A `locale|a.b.c` map as the nested per-locale bundle `getTranslations()` hands over. */
2480+
const bundleOf = (entries: Record<string, string>): Record<string, Record<string, unknown>> => {
2481+
const bundle: Record<string, Record<string, any>> = {};
2482+
for (const [address, value] of Object.entries(entries)) {
2483+
const [locale, key] = address.split('|');
2484+
const parts = key.split('.');
2485+
let cur = (bundle[locale] ??= {});
2486+
for (const part of parts.slice(0, -1)) cur = cur[part] ??= {};
2487+
cur[parts[parts.length - 1]] = value;
2488+
}
2489+
return bundle;
2490+
};
2491+
/** `labelTranslation` over `entries`, read in `locale`; counts its calls. */
2492+
const service = (entries: Record<string, string>, locale = 'zh-CN') => {
2493+
const calls = { count: 0 };
24812494
return {
2482-
seen,
2483-
t: (key: string, locale: string) => {
2484-
seen.push(`${locale}|${key}`);
2485-
return entries[`${locale}|${key}`] ?? key;
2495+
calls,
2496+
labelTranslation: () => {
2497+
calls.count += 1;
2498+
return { bundle: bundleOf(entries) as any, options: { locale } };
24862499
},
24872500
};
24882501
};
@@ -2512,49 +2525,62 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
25122525
}],
25132526
});
25142527

2515-
it('asks for objects.<object>._validations.<rule>.message, and returns what it gets', () => {
2528+
it('reads objects.<object>._validations.<rule>.message through labelTranslation, never t()', () => {
25162529
const i18n = service({
25172530
'zh-CN|objects.duly_duty._validations.standing_no_frequency.message':
25182531
'常规任务必须设置频率。',
2532+
// Another object's rule of the same name: not this refusal's address.
2533+
'zh-CN|objects.other_duty._validations.standing_no_frequency.message': 'WRONG — another object',
25192534
});
25202535
const [err] = failing(scriptSchema('A standing duty must declare a frequency.'), {}, 'insert', {
2521-
messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t },
2536+
messages: {
2537+
locale: 'zh-CN',
2538+
objectName: 'duly_duty',
2539+
labelTranslation: i18n.labelTranslation,
2540+
translate: (key: string) => (key.includes('._validations.') ? 'WRONG — read through t()' : key),
2541+
},
25222542
});
25232543
expect(err.message).toBe('常规任务必须设置频率。');
2524-
expect(i18n.seen).toContain('zh-CN|objects.duly_duty._validations.standing_no_frequency.message');
25252544
// The wire vocabulary is unchanged — ADR-0114's `code` does not split
25262545
// because a sentence is now translatable.
25272546
expect(err.code).toBe('rule_violation');
25282547
expect(err.field).toBe('frequency');
25292548
});
25302549

2531-
it('keeps the authored sentence when the bundle has no entry (the key echoes back)', () => {
2550+
it('keeps the authored sentence when the bundle has no entry', () => {
25322551
const i18n = service({});
25332552
const [err] = failing(scriptSchema('A standing duty must declare a frequency.'), {}, 'insert', {
2534-
messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t },
2553+
messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation },
25352554
});
25362555
expect(err.message).toBe('A standing duty must declare a frequency.');
25372556
});
25382557

2558+
it('keeps the authored sentence when the service cannot hand its translations over', () => {
2559+
const [err] = failing(scriptSchema('authored'), {}, 'insert', {
2560+
messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: () => undefined },
2561+
});
2562+
expect(err.message).toBe('authored');
2563+
});
2564+
25392565
it('does not consult the bundle without an object name or a locale', () => {
25402566
const i18n = service({
25412567
'zh-CN|objects.duly_duty._validations.standing_no_frequency.message': '常规任务必须设置频率。',
25422568
});
25432569
expect(failing(scriptSchema('authored'), {}, 'insert', {
2544-
messages: { locale: 'zh-CN', translate: i18n.t },
2570+
messages: { locale: 'zh-CN', labelTranslation: i18n.labelTranslation },
25452571
})[0].message).toBe('authored');
25462572
expect(failing(scriptSchema('authored'), {}, 'insert', {
2547-
messages: { objectName: 'duly_duty', translate: i18n.t },
2573+
messages: { objectName: 'duly_duty', labelTranslation: i18n.labelTranslation },
25482574
})[0].message).toBe('authored');
2549-
expect(i18n.seen).toEqual([]);
2575+
expect(i18n.calls.count).toBe(0);
25502576
});
25512577

25522578
it('survives a throwing i18n service — a 400 must not become a 500', () => {
25532579
const [err] = failing(scriptSchema('authored'), {}, 'insert', {
25542580
messages: {
25552581
locale: 'zh-CN',
25562582
objectName: 'duly_duty',
2557-
translate: () => { throw new Error('i18n exploded'); },
2583+
labelTranslation: () => { throw new Error('i18n exploded'); },
25582584
},
25592585
});
25602586
expect(err.message).toBe('authored');
@@ -2566,7 +2592,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
25662592
'zh-CN|objects.duly_duty._validations.contact_email.message': '联系邮箱格式不正确。',
25672593
'zh-CN|objects.duly_duty._validations.payload_shape.message': '负载结构不符合约定。',
25682594
});
2569-
const messages = { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t };
2595+
const messages = { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation };
25702596

25712597
const fsm = {
25722598
fields: { status: { type: 'select', label: '状态' } },
@@ -2623,7 +2649,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
26232649
}],
26242650
};
26252651
const [err] = failing(schema, { account_type: 'enterprise', approver: null }, 'insert', {
2626-
messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t },
2652+
messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation },
26272653
});
26282654
expect(err.message).toBe('企业客户需要审批人。');
26292655
});
@@ -2643,7 +2669,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
26432669
}],
26442670
};
26452671
const [err] = failing(schema, {}, 'insert', {
2646-
messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t },
2672+
messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation },
26472673
});
26482674
expect(err.message).toMatch(/could not be evaluated/);
26492675
expect(err.message).not.toBe('这条不该出现。');
@@ -2666,8 +2692,11 @@ describe('evaluateValidationRules — a tenant-rewritten rule message beats the
26662692
const PACKAGED = 'A standing duty must declare a frequency.';
26672693
const REWRITE = 'Pick how often this duty repeats.';
26682694
const ZH = '常规任务必须设置频率。';
2669-
const KEY = 'zh-CN|objects.duly_duty._validations.standing_no_frequency.message';
2670-
const t = (key: string, locale: string) => ({ [KEY]: ZH } as Record<string, string>)[`${locale}|${key}`] ?? key;
2695+
// [#35384] The catalog entry as the bundle `labelTranslation` hands over.
2696+
const labelTranslation = () => ({
2697+
bundle: { 'zh-CN': { objects: { duly_duty: { _validations: { standing_no_frequency: { message: ZH } } } } } } as any,
2698+
options: { locale: 'zh-CN' },
2699+
});
26712700

26722701
const failing = (schema: any, data: Record<string, unknown>, opts: Record<string, unknown>) => {
26732702
try {
@@ -2691,7 +2720,7 @@ describe('evaluateValidationRules — a tenant-rewritten rule message beats the
26912720
});
26922721
const packagedRule = (name: string) => (name === 'standing_no_frequency' ? scriptRule(PACKAGED) : undefined);
26932722
const messages = (extra: Record<string, unknown> = {}) =>
2694-
({ locale: 'zh-CN', objectName: 'duly_duty', translate: t, ...extra });
2723+
({ locale: 'zh-CN', objectName: 'duly_duty', labelTranslation, ...extra });
26952724

26962725
it('returns the rewrite as written in a non-default locale', () => {
26972726
const [err] = failing(schemaWith(REWRITE), {}, { messages: messages({ packagedRule }) });

0 commit comments

Comments
 (0)