Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .changeset/37909-rule-message-template-holes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
'@objectstack/lint': minor
'@objectstack/spec': minor
---

feat(lint)!: a validation rule's message is a `{{ }}` template over the judged record, and a single brace there is refused

Clause-②: no (narrowing)
Metadata-protocol: narrowed

<!-- adr-0087: registered validation-rule-message-template-holes -->

**BREAKING** accept-set narrowing, shipped as `minor`: a validation rule's `message`, and each `objects.OBJECT._validations.RULE.message` translation, that carries a single-brace `{…}` or `${…}` token was accepted before and is refused now by `objectstack validate`, `objectstack compile` and the runtime publish gate (rule `expression-invalid`, an error; `422` on an `object`, `object_extension` or `translation` write). The schema is unchanged: `message` stays a string and the parse does not judge it, so a stored rule or bundle keeps loading and is judged at its next save.

The message is now a `{{ }}` template (ADR-0032 §3) over the record the rule judged. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or `previous` (the stored row before an update), with an optional whitelisted formatter: `{{ record.total_price | currency }}`. The doors judge every rule message (a nested `conditional` branch's and an `objectExtensions[]` entry's included) and every translation of one with `closedScopeTemplateRefusal`, then compile it as a `template`, and refuse:

- a single-brace `{…}` or `${…}` token, with its `{{ }}` spelling where the token names a field under `record` or `previous`;
- a hole over any other root (`{{ amount }}`, `{{ current_user.name }}`);
- a hole naming the whole root (`{{ record }}`), reading through a field (`{{ record.account.name }}`), or naming a field the object does not declare (`{{ record.totl }}`, with the nearest field named);
- a hole holding logic or an unknown formatter.

Filling the holes at run time is the next change on this card; until it lands, a hole that passes the doors is returned as written.

- **Exports.** `@objectstack/spec/data` gains `VALIDATION_MESSAGE_TEMPLATE_ROOTS` (`['record', 'previous']`). The `message` describe of the six validation-rule variants and of the `_validations` translation entry now state the template.
- **The ADR-0087 ledger** gains the semantic entry `validation-rule-message-template-holes` under step 19.

FROM → TO:

- `message: 'Support Config must be { tier: standard|premium|enterprise, seats?: >=1 }.'` → `message: 'Support Config must name a tier (standard, premium or enterprise) and, if it sets seats, at least 1 seat.'`
- `message: 'Total {total_price} is below {received_amount}'` → `message: 'Total {{ record.total_price | currency }} is below {{ record.received_amount | currency }}'`

One-line fix: run `objectstack validate`, then reword each refused message without braces or write each token as the `{{ record.FIELD }}` hole the finding names, in the authored message and in every translation of it.
44 changes: 22 additions & 22 deletions content/docs/references/data/validation.mdx

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion examples/app-showcase/src/data/objects/account.object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export const Account = ObjectSchema.create({
label: 'Support Config Shape',
description: 'Support config must declare a known tier and a positive seat count.',
field: 'support_config',
message: 'Support Config must be { tier: standard|premium|enterprise, seats?: >=1 }.',
message: 'Support Config must name a tier (standard, premium or enterprise) and, if it sets seats, at least 1 seat.',
schema: {
type: 'object',
properties: {
Expand Down
10 changes: 6 additions & 4 deletions examples/app-showcase/src/system/translations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ export const ShowcaseTranslationBundle = {
message: 'Billing Email must be a valid email address.',
},
support_config_shape: {
message: 'Support Config must be { tier: standard|premium|enterprise, seats?: >=1 }.',
message: 'Support Config must name a tier (standard, premium or enterprise) and, if it sets seats, at least 1 seat.',
},
churn_reason_consistency: {
message: 'Churn reason consistency.',
Expand Down Expand Up @@ -644,13 +644,15 @@ export const ShowcaseTranslationBundle = {
// there. Vocabulary is the one this bundle already established:
// 生命周期 / 税号 / 账单邮箱 / 支持配置 / 流失原因 are the field labels
// right above, so a refusal names the field with the same word the form
// does. The `support_config_shape` shape stays in its source spelling —
// it is a machine contract the author must type back, not prose.
// does. The `support_config_shape` sentence keeps the machine words
// `tier` / `seats` and the tier values in their source spelling — they
// are what the author types back — but no braces: a rule message is a
// `{{ }}` template, and a single-brace token there is refused.
_validations: {
account_lifecycle: { message: '客户生命周期的状态流转无效。' },
tax_id_format: { message: '税号格式应为 12-3456789。' },
billing_email_format: { message: '账单邮箱必须是有效的邮箱地址。' },
support_config_shape: { message: '支持配置必须为 { tier: standard|premium|enterprise, seats?: >=1 }。' },
support_config_shape: { message: '支持配置必须指定 tier(standard、premium 或 enterprise);如填写 seats,至少为 1。' },
churn_reason_consistency: { message: '流失原因一致性。' },
churn_reason_present: { message: '客户标记为流失时必须填写流失原因。' },
churn_reason_absent: { message: '只有客户已流失时才能填写流失原因。' },
Expand Down
13 changes: 13 additions & 0 deletions packages/lint/src/authored-site-expression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,15 @@ const WALK_PUSHES: Record<string, string> = {
actionRefusalTemplateIssues: "an action refusal's template sentences over its declared params: no rule or field expression",
// [#35356] ADR-0157 D4/D6: working-day calls at value sites the engine loads no calendar for.
workingDayValueSiteIssues: "a field's expression `defaultValue` and a seed record's expression values: no rule or formula `expression`",
// [#37909] A translation bundle's `_validations.RULE.message` templates.
ruleMessageTranslationIssues: "a translated validation-rule message's template holes: no rule or field expression",
};

/** The passes the walk pushes whole from INSIDE a site's regions: classified with that site's calls, in `SITE_CALLS`. */
const WALK_PUSHES_IN_REGION: Record<string, ObjectSite> = {
formulaCycleIssues: 'formula',
// [#37909] The rule's own `message` templates, judged in the rule pass.
ruleMessageTemplateIssues: 'validation',
};

/** An object whose own formulas read each other: a cycle the gate refuses on each of its members. */
Expand Down Expand Up @@ -229,6 +233,15 @@ const SITE_CALLS: Record<ObjectSite, Record<string, Classified>> = {
kind: 'pass',
fixture: { objects: [REQ, BAL], expression: 'record.days > 3', severity: 'error', names: 'days' },
},
// [#37909] The rule's `message` is a `{{ }}` template the rule pass
// judges; the tool judges one predicate, and its probe rule carries a
// plain message (its own name), so the pass has nothing to say here.
ruleMessages: { kind: 'plumbing', why: "lists the rule's messages, nested branches included" },
ruleMessageTemplateIssues: {
kind: 'pass-silent-here',
why: "judges the rule's `message`, not its predicate; the probe rule's message is plain text",
fixture: { objects: [REQ, BAL], expression: "record.title == 'x'" },
},
},
formula: {
validateExpression: VALIDATOR,
Expand Down
18 changes: 17 additions & 1 deletion packages/lint/src/authoring-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -922,8 +922,24 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [
// build alike (`object 'TARGET' · objectExtensions[0] · validation 'N'`).
// MEASURED first: 0 first-party `objectExtensions` entries carry a
// validation rule (examples/**, packages/**, HotCRM).
//
// [#37909, ruling P3] A validation rule's `message` is a `{{ }}` template
// over `record` / `previous` (`validate-rule-message-templates.ts`): the
// object and extension walks judge each rule's message, nested branches
// included, so an `object` or `object_extension` write carrying a refused
// one answers 422. `translation` joins, for ONE pass: each translated rule
// message of the written item (`objects.OBJECT._validations.RULE.message`),
// judged as the authored message is; on a translation write
// `runStackExpressionPasses` runs that pass alone, by construction. Every
// finding is an `error` (a narrowing no conversion carries: the message
// stays a string, so a stored rule or bundle keeps loading until its next
// save). MEASURED first over the shipped corpus at `1fef2ed7c4`: 40 rule
// messages and 196 translations (examples/**, platform-objects, the
// plugins and services) → 3 refused, the showcase `support_config_shape`
// message and its two translations, reworded in the same change; 0 carry
// a `{{ }}` hole.
surfaces: CLI_AND_RUNTIME,
runtimeTypes: ['flow', 'action', 'hook', 'object', 'view', 'page', 'object_extension'],
runtimeTypes: ['flow', 'action', 'hook', 'object', 'view', 'page', 'object_extension', 'translation'],
run: (stack, ctx) =>
runStackExpressionPasses(stack, {
runtimeWriteType: ctx.runtimeWriteType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,12 @@ const rulesOf = (fs: Array<{ rule: string }>) => fs.map((f) => f.rule);
describe('a translation write reaches the translation rule at the door (#38623)', () => {
it('the write type dispatches the suite, and the suite dispatches exactly the translation member', () => {
expect(stackKeyForType('translation')).toBe('translations');
expect(runtimeAuthoringRulesFor('translation').map((r) => r.name)).toEqual(['validateReferenceIntegrity']);
// [#37909] The expression rule joins for one pass, the translated
// validation-rule messages (`validate-rule-message-templates.test.ts`).
expect(runtimeAuthoringRulesFor('translation').map((r) => r.name)).toEqual([
'validateStackExpressions',
'validateReferenceIntegrity',
]);
const members = REFERENCE_INTEGRITY_RULES
.filter((m) => (m.runtimeTypes ?? ['flow']).includes('translation'))
.map((m) => m.name);
Expand All @@ -62,7 +67,7 @@ describe('a translation write reaches the translation rule at the door (#38623)'
expect(rulesOf(result.advisories)).toEqual([TRANSLATION_TARGET_UNKNOWN]);
expect(result.advisories[0]!.severity).toBe('warning');
expect(result.advisories[0]!.path).toBe('translations[0].objects.crm_lead.fields.zzz_removed');
expect(result.rulesRun).toEqual(['validateReferenceIntegrity']);
expect(result.rulesRun).toEqual(['validateStackExpressions', 'validateReferenceIntegrity']);
});

it('⭐ LIT — an object, a validation rule and a milestone nothing declares are advised too', () => {
Expand Down
35 changes: 35 additions & 0 deletions packages/lint/src/validate-expressions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,12 @@ import { bulkConfirmTemplateRoots } from '@objectstack/spec/ui';
// is a `template` slot too, judged in its own module by the same judge.
import { actionCopyTemplateIssues } from './validate-action-copy-templates.js';
import { actionRefusalTemplateIssues, hookRefusalTemplateIssues } from './validate-hook-refusal-templates.js';
import {
ruleMessages,
ruleMessageTemplateIssues,
ruleMessageTranslationIssues,
VALIDATION_MESSAGE_SLOT,
} from './validate-rule-message-templates.js';
import { workingDayElsewhereMessage, workingDayValueSiteIssues } from './validate-working-day-sites.js';
// [#15137] The `value`-role half. Same two published primitives the engine
// composes at `registerFlow` (`AutomationEngine.valueEnvelopeRefusals`), in the
Expand Down Expand Up @@ -2648,6 +2654,14 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
if (options.runtimeWriteType === 'page') {
return actionCopyTemplateIssues(stack, { actions: false, objects: false, pages: true });
}
// [#37909, ruling P3] On a `translation` write exactly ONE pass judges too —
// the translated validation-rule messages of the written item
// (`validate-rule-message-templates.ts`), each a `{{ }}` template over the
// judged record, against the door's live objects. Every other pass reads a
// collection a translation write does not carry.
if (options.runtimeWriteType === 'translation') {
return ruleMessageTranslationIssues(stack, { atSaveDoor: true, fields: buildFieldIndex(recordsOf(stack.objects)) });
}
// [#33154] The extension door hands the objects as the registry SERVES
// them, and a served definition carries the system columns the registry
// injects (`created_at`, `owner_id`, …) as declared fields; the build reads
Expand Down Expand Up @@ -4110,6 +4124,22 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
checkNullGuards(`${locus} · ${p.label}`, p.label, p.raw, objectName, ruleOutcome);
atSlot(p.key, first);
}
// [#37909, ruling P3] The rule's `message` — and each nested branch's —
// is a `{{ }}` template over `record` / `previous`: a single-brace token,
// a hole over another root, a hole that is not one of the object's own
// fields one segment deep, logic and an unknown formatter are errors
// (`validate-rule-message-templates.ts`). The object's fields are read as
// served (`fieldIndex`), so a field an extension adds resolves.
const fields = objectName !== undefined ? fieldIndex.get(objectName) : undefined;
for (const { key, label, text } of ruleMessages(rule)) {
issues.push(...ruleMessageTemplateIssues(text, {
where: `${where} ${label}message`,
...(rulePath ? { path: `${rulePath}.${key}` } : {}),
slot: VALIDATION_MESSAGE_SLOT,
objectName,
fields,
}));
}
};

// ── Object validation-rule + formula predicates ────────────────────
Expand Down Expand Up @@ -4931,6 +4961,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
// `defaultValue` (every run) or a seed record's expression value (off an
// object write), the two value sites the passes above do not walk.
issues.push(...workingDayValueSiteIssues(stack, { data: !objectWrite }));
// [#37909, ruling P3] Each translated validation-rule message
// (`objects.OBJECT._validations.RULE.message`), judged as the authored
// message is, off an object write (the object write's snapshot carries no
// bundle; a `translation` write ran this pass alone, above).
if (!objectWrite) issues.push(...ruleMessageTranslationIssues(stack, { atSaveDoor: false, fields: fieldIndex }));

return issues;
}
Expand Down
Loading
Loading