Skip to content

Commit 139bc18

Browse files
fix(objectql): name a refused state_machine move by its option labels (#28173)
Fixes #28052 Clause-②: no Metadata-protocol: none Skills-docs: none — `skills/**` and `content/docs/**` carry no copy of the built-in `invalid_transition` sentence (grep for `invalid_transition`, `Invalid transition for` and `不允许从`: four doc hits, all naming the code or a user hook's own message, none quoting the built-in wording) ## 维护者速读 - 改了什么:状态机规则拒绝非法状态流转时,内置提示句里的「从哪到哪」改用选项的显示名(按调用者语言翻译),不再用原始选项值。 - 为什么改:用户被拒时看到「Invalid transition for Status: presented → draft」这种机器值,看不懂哪一步错了;现在读到「Presented → Draft」,中文读到「已提交 → 草稿」。 - 风险与回滚:只改提示文字;`code` 与机器可读的 `constraint: { from, to }` 仍是原始值,作者自写的 message 原样不动;回滚即 revert 本 PR。 - 先看:`packages/objectql/src/validation/rule-validator.ts` 的 `checkStateMachine` 末尾与新函数 `resolveOptionLabel`;再看新测试文件。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run src/validation/rule-validator.state-machine-option-labels.test.ts`,预期 6 个用例全绿。 - 需要你做的:无,席位落地。 ## What changes - `checkStateMachine` (`packages/objectql/src/validation/rule-validator.ts`): on the built-in path (no authored `message`), the `invalid_transition` template's `{{from}}` / `{{to}}` are now filled with each state's option label; `constraint` is still built from, and shipped with, the raw option values. The authored-message path is untouched and does not even run the label lookup. - New `resolveOptionLabel(field, def, value, messages)`: the field's own option translation (`objects.OBJECT.fields.FIELD.options.VALUE`) → for a picklist-bound field, the list's (`picklists.NAME.options.VALUE`) → the option's declared `label` → the raw value. That is the chain `translateObject` serves a field's options by on `/meta`, asked through the same `ValidationMessageContext.translate` hook `resolveFieldLabel` uses (no second i18n path), with the same echo-on-miss test and the same swallow-a-throwing-service guard. - `buildFieldError` interpolates its `constraint` over its `messageParams`, so the built-in path renders with `messageParams: { ...constraint, ...labels }` and no constraint, then attaches the raw `constraint` itself. The returned key order (`field, code, message, label, constraint`) is unchanged. - `ConditionalFieldDef` gains the `picklist` key and `ConditionalFieldOption` the `label` key it already receives at runtime (types only). - `.changeset/28052-state-machine-option-labels.md`: `@objectstack/objectql` patch. Not in scope, per triage: `{{from}}` / `{{to}}` holes in an author-written `message` (new authorable vocabulary, `Clause-②: yes`, back to triage). `packages/spec` is untouched; the template text is unchanged. ## Tests New `packages/objectql/src/validation/rule-validator.state-machine-option-labels.test.ts`, six pins: 1. built-in sentence names declared option labels: `Invalid transition for Status: Presented → Draft`; `constraint` is `{ from: 'presented', to: 'draft' }`; 2. translated option labels under `zh-CN`: `状态不允许从 已提交 变更为 草稿`; 3. picklist-bound field: the field-level entry wins, the picklist entry answers for an option the field does not translate; 4. fallback: a missing translation falls to the declared label, an unlabelled option and a bare scalar option fall to the raw value; 5. a throwing i18n service leaves the declared labels standing (a 400 never becomes a 500); 6. an authored `message` containing `{{from}}` / `{{to}}` is returned exactly as written, with the raw `constraint` beside it. Measured on `main` 277275a before the fix (test file only): pins 1–5 red, pin 6 green (a preservation pin). Received on main for pin 1: ```text Expected: "Invalid transition for Status: Presented → Draft" Received: "Invalid transition for Status: presented → draft" ``` Ablations, each reverted from the committed fix and restored with `git restore --source=HEAD --staged --worktree` (tree clean afterwards, 6/6 green on restore): | Ablation | Red pins | |---|---| | A1 built-in path renders from `constraint` again (as on main) | 1, 2, 3, 4, 5 | | A2 no translate lookup for options | 2, 3 | | A3 no picklist key | 3 | | A4 no raw-value fallback | 4 | | A5 `constraint` carries the labels | 1, 2, 4 | | A6 no try/catch around the option lookup | 5 | | A7 an authored message gets its holes filled | 6 | ## Acceptance notes - The `invalid_initial_state` built-in sentence still lists `{{value}}` / `{{allowed}}` as raw option values. Same wording shape, left alone because the card and its claim scope this PR to `invalid_transition` only; noted, not filed. - No helper in `packages/spec` spells the option-label bundle key (only `objectFieldLabelKey` / `objectLabelKey` / `objectValidationMessageKey` exist), so the key is spelled inline here, as `plugin-audit`'s activity summary already does. A spec helper would be a `domain:spec` change; noted, not filed. ## Verification All at head f118099 (worktree off `origin/main` 277275a): - `pnpm --filter @objectstack/objectql test`: 495 files / 9629 tests passed. - `pnpm --filter @objectstack/objectql typecheck` (tsc plus `check:test-typecheck`): exit 0. - eslint on the two changed `.ts` files: exit 0. `pnpm lint`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands`: 62 families, each run with its exit code recorded before any pipe; `--ran` reconciliation: "62 derived, 62 run, 0 NOT-MEASURED, 0 UNRUN" (exit 0). `check:dual-build-cjs-loads` first exited 3 (PREREQUISITE NOT MET, no full build yet); re-run after a full `pnpm turbo run build` (116/116 tasks): exit 0, "113 published require entry point(s) across 70 package(s) load". The ten commits `main` gained since 277275a touch neither `packages/objectql` nor the `invalid_transition` template. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4czVnUdQQCVKSW5J2uk --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent dc4755c commit 139bc18

3 files changed

Lines changed: 223 additions & 1 deletion

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a refused `state_machine` move is named by the states' option labels, not their raw values
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The built-in `invalid_transition` sentence filled its `{{from}}` / `{{to}}` from the raw option values, so a user refused a status change read `Invalid transition for Status: presented → draft`. It now reads `Invalid transition for Status: Presented → Draft` — each state named the way the form's dropdown shows it, in the caller's locale:
11+
12+
- the field's own option translation (`objects.<object>.fields.<field>.options.<value>`), then, for a picklist-bound field, the shared list's (`picklists.<name>.options.<value>`), then the option's declared `label`, then the raw value for an option with no label;
13+
- asked through the same translation hook the field label resolves through, so a `zh-CN` caller reads `状态不允许从 已提交 变更为 草稿`.
14+
15+
What a client acts on is unchanged: `code` stays `invalid_transition` and `constraint: { from, to }` keeps the raw option values. An author-written rule `message` is handed over exactly as before — it gains no `{{from}}` / `{{to}}` holes. The `invalid_initial_state` sentence is unchanged.
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A `state_machine` rule's BUILT-IN `invalid_transition` sentence names the
5+
* refused move by the states' option LABELS, in the caller's locale — never by
6+
* the raw option values a user has never seen.
7+
*
8+
* What a client ACTS on is unchanged: `code` stays `invalid_transition` and
9+
* `constraint: { from, to }` keeps the raw option values (a detail page greys
10+
* out a move by value, not by label). An author-written `message` is handed
11+
* over exactly as before — it gains no `{{from}}` / `{{to}}` holes here.
12+
*/
13+
14+
import { describe, it, expect } from 'vitest';
15+
import { evaluateValidationRules } from './rule-validator.js';
16+
import { ValidationError } from './record-validator.js';
17+
// Pay the first transform of the dist-resolved spec at MODULE LOAD, not inside
18+
// a clocked `it()` (`scripts/check-test-source-alias.mjs`).
19+
import '@objectstack/spec';
20+
21+
const failing = (
22+
schema: any,
23+
data: Record<string, unknown>,
24+
opts: Record<string, unknown>,
25+
) => {
26+
try {
27+
evaluateValidationRules(schema, data, 'update', opts);
28+
} catch (e) {
29+
return (e as ValidationError).fields;
30+
}
31+
throw new Error('expected a ValidationError');
32+
};
33+
34+
/** A quote whose status moves draft → presented → accepted, with labelled options. */
35+
const quoteSchema = (message: string, options?: unknown[]) => ({
36+
fields: {
37+
status: {
38+
type: 'select',
39+
label: 'Status',
40+
options: options ?? [
41+
{ value: 'draft', label: 'Draft' },
42+
{ value: 'presented', label: 'Presented' },
43+
{ value: 'accepted', label: 'Accepted' },
44+
],
45+
},
46+
},
47+
validations: [{
48+
type: 'state_machine',
49+
name: 'quote_status_progression',
50+
message,
51+
field: 'status',
52+
transitions: { draft: ['presented'], presented: ['accepted'], accepted: [] },
53+
}],
54+
});
55+
56+
/** An `II18nService.t`-shaped lookup over a flat `locale|key` map; echoes the key on a miss. */
57+
const service = (entries: Record<string, string>) => (key: string, locale: string) =>
58+
entries[`${locale}|${key}`] ?? key;
59+
60+
describe('state_machine invalid_transition — the built-in sentence names option labels', () => {
61+
it('names the states by their declared option labels; constraint keeps the raw values', () => {
62+
const [err] = failing(quoteSchema(''), { status: 'draft' }, { previous: { status: 'presented' } });
63+
expect(err.message).toBe('Invalid transition for Status: Presented → Draft');
64+
expect(err.code).toBe('invalid_transition');
65+
expect(err.constraint).toEqual({ from: 'presented', to: 'draft' });
66+
expect(err.label).toBe('Status');
67+
});
68+
69+
it('names the states by their TRANSLATED option labels under a non-English locale', () => {
70+
const translate = service({
71+
'zh-CN|objects.quote.fields.status.label': '状态',
72+
'zh-CN|objects.quote.fields.status.options.presented': '已提交',
73+
'zh-CN|objects.quote.fields.status.options.draft': '草稿',
74+
});
75+
const [err] = failing(quoteSchema(''), { status: 'draft' }, {
76+
previous: { status: 'presented' },
77+
messages: { locale: 'zh-CN', objectName: 'quote', translate },
78+
});
79+
expect(err.message).toBe('状态不允许从 已提交 变更为 草稿');
80+
expect(err.constraint).toEqual({ from: 'presented', to: 'draft' });
81+
});
82+
83+
it('falls back to the picklist\'s translated option label for a picklist-bound field', () => {
84+
const schema = quoteSchema('');
85+
(schema.fields.status as any).picklist = 'quote_status';
86+
const translate = service({
87+
// A field-level entry is the more specific and wins …
88+
'zh-CN|objects.quote.fields.status.options.draft': '草稿',
89+
// … and the shared list answers for an option the field does not translate.
90+
'zh-CN|picklists.quote_status.options.draft': 'WRONG — the field entry wins',
91+
'zh-CN|picklists.quote_status.options.presented': '已提交',
92+
});
93+
const [err] = failing(schema, { status: 'draft' }, {
94+
previous: { status: 'presented' },
95+
messages: { locale: 'zh-CN', objectName: 'quote', translate },
96+
});
97+
expect(err.message).toBe('Status不允许从 已提交 变更为 草稿');
98+
});
99+
100+
it('falls back to the declared label, then the raw value, when a translation or a label is missing', () => {
101+
const options = [
102+
{ value: 'draft' }, // no label at all
103+
{ value: 'presented', label: 'Presented' },
104+
'accepted', // a bare scalar option
105+
];
106+
const translate = service({});
107+
const [err] = failing(quoteSchema('', options), { status: 'draft' }, {
108+
previous: { status: 'presented' },
109+
messages: { locale: 'zh-CN', objectName: 'quote', translate },
110+
});
111+
expect(err.message).toBe('Status不允许从 Presented 变更为 draft');
112+
expect(err.constraint).toEqual({ from: 'presented', to: 'draft' });
113+
114+
const [bare] = failing(quoteSchema('', options), { status: 'presented' }, { previous: { status: 'accepted' } });
115+
expect(bare.message).toBe('Invalid transition for Status: accepted → Presented');
116+
});
117+
118+
it('survives a throwing i18n service — the declared label stands, a 400 never becomes a 500', () => {
119+
const [err] = failing(quoteSchema(''), { status: 'draft' }, {
120+
previous: { status: 'presented' },
121+
messages: { locale: 'zh-CN', objectName: 'quote', translate: () => { throw new Error('i18n exploded'); } },
122+
});
123+
expect(err.message).toBe('Status不允许从 Presented 变更为 Draft');
124+
});
125+
126+
it('leaves an author-written message exactly as written — no holes are filled in it', () => {
127+
const authored = 'Cannot move a quote from {{from}} to {{to}}.';
128+
const [err] = failing(quoteSchema(authored), { status: 'draft' }, { previous: { status: 'presented' } });
129+
expect(err.message).toBe(authored);
130+
expect(err.code).toBe('invalid_transition');
131+
expect(err.constraint).toEqual({ from: 'presented', to: 'draft' });
132+
});
133+
});

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

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2911,6 +2911,8 @@ function ruleNeedsPrior(r: unknown): boolean {
29112911
* CEL predicate is TRUE over the record. */
29122912
interface ConditionalFieldOption {
29132913
value?: unknown;
2914+
/** Author-declared display label — names a state in a `state_machine` refusal. */
2915+
label?: string;
29142916
/** Per-option visibility predicate (CEL) — objectui#2284. */
29152917
visibleWhen?: string | Expression;
29162918
}
@@ -2938,6 +2940,9 @@ interface ConditionalFieldDef {
29382940
type?: string;
29392941
/** select/multiselect/radio/checkboxes options; an option may gate itself with `visibleWhen`. */
29402942
options?: Array<ConditionalFieldOption | null | undefined>;
2943+
/** The shared picklist the field's options are folded from — the bundle
2944+
* address of an option label the field itself does not translate. */
2945+
picklist?: string;
29412946
}
29422947

29432948
/**
@@ -3848,6 +3853,9 @@ function checkStateMachine(
38483853
code: 'invalid_initial_state' | 'invalid_transition',
38493854
constraint: Record<string, unknown>,
38503855
value?: string,
3856+
// The built-in sentence's words where they differ from the machine facts —
3857+
// read only on the built-in path, so an authored message costs no lookup.
3858+
wording?: () => Record<string, unknown>,
38513859
): FieldValidationError => {
38523860
const def = ctx?.fields?.[rule.field];
38533861
if (rule.message) {
@@ -3870,6 +3878,18 @@ function checkStateMachine(
38703878
...(value !== undefined ? { value } : {}),
38713879
};
38723880
}
3881+
if (wording) {
3882+
// The sentence is rendered from `wording` over the constraint, and the
3883+
// constraint is shipped as it is: `buildFieldError` interpolates its
3884+
// `constraint` over its `messageParams`, so the two cannot ride one call.
3885+
return {
3886+
...buildFieldError(
3887+
{ field: rule.field, code, def, value, messageParams: { ...constraint, ...wording() } },
3888+
ctx?.messages,
3889+
),
3890+
...(Object.keys(constraint).length > 0 ? { constraint } : {}),
3891+
};
3892+
}
38733893
return buildFieldError({ field: rule.field, code, def, constraint, value }, ctx?.messages);
38743894
};
38753895
if (mode === 'insert') {
@@ -3899,11 +3919,65 @@ function checkStateMachine(
38993919
if (!Array.isArray(allowed)) return null;
39003920

39013921
if (!allowed.includes(String(to))) {
3902-
return fallback('invalid_transition', { from: fromKey, to: String(to) });
3922+
const toKey = String(to);
3923+
// `constraint` carries the raw option values a client acts on; the
3924+
// built-in sentence names the same two states the way the user sees them.
3925+
return fallback('invalid_transition', { from: fromKey, to: toKey }, undefined, () => {
3926+
const def = ctx?.fields?.[rule.field];
3927+
return {
3928+
from: resolveOptionLabel(rule.field, def, fromKey, ctx?.messages),
3929+
to: resolveOptionLabel(rule.field, def, toKey, ctx?.messages),
3930+
};
3931+
});
39033932
}
39043933
return null;
39053934
}
39063935

3936+
/**
3937+
* One option of a choice field, named the way the user sees it, in the
3938+
* caller's locale: the field's own translation
3939+
* (`objects.<object>.fields.<field>.options.<value>`) → for a picklist-bound
3940+
* field, the shared list's (`picklists.<name>.options.<value>`) → the option's
3941+
* declared `label` → the raw value.
3942+
*
3943+
* The chain `translateObject` serves a field's options by on `/meta`, so the
3944+
* refusal names a state with the word the form's dropdown showed. Asked through
3945+
* the same `ValidationMessageContext.translate` hook `resolveFieldLabel` uses —
3946+
* no second i18n path. The raw value is the last resort, as the API name is
3947+
* for a field label: it stays available to clients in `constraint`.
3948+
*/
3949+
function resolveOptionLabel(
3950+
fieldName: string,
3951+
def: ConditionalFieldDef | undefined,
3952+
value: string,
3953+
ctx: ValidationMessageContext | undefined,
3954+
): string {
3955+
if (ctx?.translate && ctx.objectName && ctx.locale) {
3956+
const keys = [`objects.${ctx.objectName}.fields.${fieldName}.options.${value}`];
3957+
if (typeof def?.picklist === 'string' && def.picklist.length > 0) {
3958+
keys.push(`picklists.${def.picklist}.options.${value}`);
3959+
}
3960+
for (const key of keys) {
3961+
try {
3962+
const translated = ctx.translate(key, ctx.locale);
3963+
// II18nService echoes the key back on a miss.
3964+
if (typeof translated === 'string' && translated.length > 0 && translated !== key) {
3965+
return translated;
3966+
}
3967+
} catch {
3968+
// A misbehaving i18n service must not turn a 400 into a 500.
3969+
}
3970+
}
3971+
}
3972+
// A bare scalar option carries no label of its own.
3973+
const option = (Array.isArray(def?.options) ? (def.options as unknown[]) : []).find(
3974+
(o): o is ConditionalFieldOption =>
3975+
typeof o === 'object' && o !== null && String((o as ConditionalFieldOption).value) === value,
3976+
);
3977+
const declared = typeof option?.label === 'string' ? option.label.trim() : '';
3978+
return declared.length > 0 ? declared : value;
3979+
}
3980+
39073981
/**
39083982
* The rejection a predicate that CANNOT BE EVALUATED produces (#4649).
39093983
*

0 commit comments

Comments
 (0)