Validate an Arc command or query in TypeScript (Node.js server)
A rule in Arc for TypeScript lives where the information it needs is available,
and as early as that allows. Validators run before handle() and also answer on
the command's POST <route>/validate, so a form can ask before the user
submits. Every rejection comes back as a ValidationResult with a message and
the member it concerns — never as a thrown error.
Arc for TypeScript ships as stable 1.0.0 packages on npm (@cratis/arc.core
and the other server packages). The published
@cratis/arc client is separate; it runs the client-safe rules the proxy
generator copies into generated proxies. Setup is in
cratis-arc-command-typescript.
Verified product sources
Source: Cratis/Arc.TypeScript, reading Source/Core/validation/** (including
index.ts, ValidationResult.ts, Severity.ts, RuleBuilder.ts),
Source/Core/commands/Outcome.ts, Documentation/commands/command-validation.md,
validation-severity-filtering.md, command-outcomes.md,
Documentation/queries/validation.md, Documentation/concepts.md,
Documentation/proxy-generation/validation.md, Source/Testing, and the
Samples/Tasks validators.
ValidationResult is both the exported interface and a value with the helpers
ValidationResult.information/warning/error(message, options?); the positional
validation(...) function remains available.
Choose where to reject
| The decision depends on |
Put it in |
Runs on /validate |
Caller sees |
| The request's shape: types, required/optional fields |
@field plus @optional()/@nullable()/@defaultValue() |
Yes |
400 malformedRequest, no message or members |
| Who is calling |
@roles, @authorize, a policy |
Yes |
401 or 403 |
| One value, wherever it appears |
ConceptValidator on the concept |
Yes |
400 with your message and member |
| The command's own fields, or a service |
CommandValidator |
Yes |
400 with your message and member |
| Stored state for the command's key |
CommandValidator rule calling readModelForValidation |
Yes |
400 with your message and member |
| Data you load anyway to do the work |
provide() returning rejected(...) or denied(...) |
No |
400 or 403 |
| A decision only the handler can make |
handle() returning rejected(...) or denied(...) |
No |
400 or 403 |
- Reject as early as the information allows. Everything through the
readModelForValidation row answers on /validate.
- Keep access control out of validators. A trusted caller can lower the
blocking severity and let validation results through; nothing lowers
authorization or
denied(...).
- A stored-state check tells you what was true when it ran. A rule that must hold
under concurrency belongs at the storage boundary (for Chronicle, a constraint
or concurrency scope —
cratis-chronicle-event-constraints).
Command rules — CommandValidator
Samples/Tasks/Features/Tasks/Registration/Registration.ts keeps the validator
in the slice file with its command:
import { command, CommandValidator, validator } from '@cratis/arc.core';
@validator(RegisterTask)
export class RegisterTaskValidator extends CommandValidator<RegisterTask> {
constructor() {
super();
this.ruleFor(command => command.title).notEmpty().withMessage('A title is required');
this.ruleFor(command => command.title).maxLength(100).withMessage('A title can have at most 100 characters');
}
}
@validator(Target) supplies the runtime target that the erased generic
cannot. It registers nothing globally: discover() picks the exported class up
from the folder, or pass it to builder.add(RegisterTask, RegisterTaskValidator)
and to CommandScenario.for(...). A validator that is never imported is never
registered.
- One validator per exact target class; a duplicate target fails at build.
- Rules on a concept member receive the unwrapped primitive —
TaskTitle rules
accept a string.
- Every rule runs; a failure does not stop the others, so a form sees every
problem at once. Any result above the allowed severity blocks
handle().
Value rules — ConceptValidator
A rule that belongs to the value goes on the concept, once.
Samples/Tasks/Features/Tasks/TaskTitleValidator.ts:
import { ConceptValidator, validator } from '@cratis/arc.core';
import { TaskTitle } from './TaskTitle.js';
@validator(TaskTitle)
export class TaskTitleValidator extends ConceptValidator<TaskTitle> {
constructor() {
super();
this.ruleFor(title => title.value).must(value => !value.startsWith('!'))
.withMessage('A title cannot begin with an exclamation mark');
}
}
Arc walks the declared @field members of commands, query arguments and nested
models, and runs the concept validator on every TaskTitle it meets, including
inside arrays. A failure inside entries[] reports entries.title, not an
index. The owner's own rules still run. To skip only the direct member's
concept rules, call .ignoreConceptRules() on the owner's ruleFor(...) chain;
descendants are still traversed. The Library sample keeps AuthorName and its
AuthorNameValidator together in AuthorName.ts.
ModelValidator<T> validates a nested model class the same way, wherever it
appears in a command or query-argument graph.
Query rules — QueryValidator
A QueryValidator targets an explicit arguments model whose @field
declarations match the query's argument(...) descriptors:
import { ConceptAs, field } from '@cratis/fundamentals';
import { QueryValidator, argument, query, readModel, validator } from '@cratis/arc.core';
export class Name extends ConceptAs<string> { static readonly valueType = String; }
export class SearchArguments {
@field(Name) term!: Name;
}
@validator(SearchArguments)
export class SearchArgumentsValidator extends QueryValidator<SearchArguments> {
constructor() {
super();
this.ruleFor(arguments_ => arguments_.term).notEmpty().withMessage('Term required');
}
}
@readModel()
export class Search {
@query({ argumentsModel: SearchArguments }, argument('term', Name))
static byTerm(term: Name): string { return term.value; }
}
Without an arguments model, Arc still runs concept validators on each supplied,
non-null argument under that argument's name, but a QueryValidator has nothing
to target. Queries always use Warning as the allowed severity.
Rules that read stored state — readModelForValidation
import { field } from '@cratis/fundamentals';
import { command, CommandValidator, key, readModelForValidation, validator } from '@cratis/arc.core';
@command()
export class RenameTask {
@field(String) @key() id!: string;
@field(String) title!: string;
handle(): void { /* rename in storage */ }
}
@validator(RenameTask)
export class RenameTaskValidator extends CommandValidator<RenameTask> {
constructor() {
super();
this.ruleFor(command => command.title).mustAsync(async title => {
const current = await readModelForValidation(TaskView, { optional: true });
return current === null || current.title !== title;
}).withMessage('The task already has this title');
}
}
- Arc resolves the command key (
@key(), getKey(), or a resolver) and asks the
resolver that owns TaskView — registered by MongoDB, Drizzle, experimental
Chronicle, or builder.addReadModelForCommandResolver(token). The resolver
receives the caller's tenant.
{ optional: true } returns null for a missing model. Without it, a missing
model makes the rule throw, and the caller gets validatorFailed instead of
your message.
- It works only inside a validator of a model-bound command, during
validation. Validators do not receive read models through their constructors.
- Reads are scoped to the current command/tenant and cancellation signal, on
both validate and execute routes; do not retain a validation read across calls.
Rule vocabulary
| Rules |
Where they run |
notNull, notEmpty, minLength, maxLength, length, emailAddress, phone, url, matches, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual |
Server; literal, unconditional uses are also copied into generated proxies |
empty, null, equal, notEqual, inclusiveBetween, exclusiveBetween, must, mustAsync |
Server only |
withMessage, withSeverity(Severity.Warning), and withState(value)
decorate the most recent rule.
when(predicate) / unless(predicate) condition every rule on the chain
by default; pass ApplyConditionTo.CurrentValidator to condition only the
latest. Conditions and predicates run on the server only.
must and mustAsync receive (value, model, signal); pass the signal to
cancelable I/O.
- String rules exist only for strings; comparison rules only for numbers and
temporal values.
notEmpty() rejects Guid.empty.
- Email, phone, URL, regex and Unicode-length behavior is not guaranteed to match
the client or Arc on .NET exactly. Write an explicit message and specify the
inputs you accept.
- The generator copies rules for commands (including direct concept fields) and
for query arguments with an explicit
argumentsModel. A rule that stays
server-only produces a source diagnostic. The server validates every request
regardless.
Services in a validator
Declare constructor dependencies with @injectable(Service) or
static inject = [Service] as const, and register the service with
builder.services. Arc constructs each validator once during build() (catching
invalid selectors early), then resolves fresh validators per execution scope. A
validator that throws, or whose dependency cannot be resolved, never reports
success: the caller gets 400 with reason validatorFailed or
dependencyUnavailable, no exception text, and the error goes to the logger.
Reject from provide() or handle()
import { denied, rejected, validation, Severity, ValidationResult } from '@cratis/arc.core';
return rejected(ValidationResult.error('The task does not exist', { members: ['id'], reason: 'notFound' }));
return rejected(ValidationResult.warning('Unusually long title', { members: ['title'], reasonDetail: 'TitleLength' }));
return rejected(validation('Unusually long title', ['title'], 'rule', Severity.Warning));
return denied('Only the owner can rename a task');
ValidationResult.information/warning/error(message, options?) (Requires Arc for
TypeScript 0.34.0) build a result at that severity; options sets
members, state (must be JSON-serializable), reason (default rule) and
reasonDetail. members defaults to [] and reason to rule; omitted
state and reasonDetail are left out of the result.
validation(message, members = [], reason = 'rule', severity = Severity.Error)
builds a ValidationResult ({ severity, message, members, reason }) with
positional arguments; it cannot set reasonDetail or state.
rejected(...results) answers 400; it throws when given no results, so an
empty rejection can never pass as success. denied(reason?) answers 403 with
authorizationFailureReason.
- Rejected results go through the same severity filter. When nothing above the
allowed severity remains,
handle() runs (from provide(), with undefined
as the provided value) or the command succeeds without a response (from
handle()).
- Throwing is for failures, not decisions: a thrown error is a 500.
Severity filtering
Severity is Unknown (0), Information (1), Warning (2), Error (3).
Results at or below the allowed severity are removed and do not block;
results above it block and are returned. The default is Warning, so only
errors block.
| Caller |
Allowed severity |
| HTTP command |
X-Allowed-Severity header 0, 1 or 2; missing or invalid means 2; 3 is capped to 2, so errors always block |
| HTTP query |
Always Warning; the header is ignored |
executeCommand from code, or CommandScenario.withAllowedValidationSeverity(...) |
As given, including Severity.Error |
performQuery from code |
Always Warning |
The HTTP cap at Warning is a deliberate safety difference from Arc on .NET,
which lets X-Allowed-Severity: 3 run a command whose only problems are
errors. Do not "fix" it toward .NET behavior. @command({ treatWarningsAsErrors: true })
and @query({ treatWarningsAsErrors: true }) set the generated client's flag.
Specify the rule
import { given, type ScenarioCommandResult } from '@cratis/arc.testing';
describe('when validating a task with an empty title', given(a_task_registration, context => {
let result: ScenarioCommandResult;
beforeEach(async () => {
result = await context.scenario.validate({ id: TaskId.create(), title: new TaskTitle('') });
});
afterAll(async () => { await context.scenario.dispose(); });
it('should report the authored rule for title', () => {
result.shouldHaveValidationErrors().shouldHaveValidationErrorForMember('title');
});
it('should not invoke the handler', () => { context.tasks.all().should.have.lengthOf(0); });
}));
- Use
scenario.validate(...) to prove the rule answers on /validate, and
execute(...) to prove handle() never ran.
- Assert the member with
shouldHaveValidationErrorForMember('title') by
default, not presentation text. Assert exact wording only when it is the
specified behavior, and name that requirement in the fact.
shouldHaveValidationErrorFor(text) passes for any message containing the
text; even a full-message argument does not prove exact equality. Compare
the actual message for equality when exact wording is the requirement.
validatorFailed and dependencyUnavailable never satisfy
shouldHaveValidationErrors() or the member assertion — they mean no authored
rule was established. Assert them explicitly with
shouldHaveValidationErrorBecauseOf('validatorFailed').
shouldHaveRuleFailure(result, { reason, member?, severity? }) from
@cratis/arc.testing asserts an authored rule on a plain result.
- For a query,
QueryScenario.perform(...) returns a result whose
validationResults you assert the same way.
Route near misses
- Defining the command or query the rule attaches to:
cratis-arc-command-typescript, cratis-arc-query-typescript.
- Append-time uniqueness or concurrency in Chronicle:
cratis-chronicle-event-constraints and the Chronicle reference in
cratis-arc-command-typescript.
- The .NET validation shape:
cratis-arc-command-validation; Kotlin/Java:
cratis-arc-validation-kotlin.
Verify
- Each rule sits in the earliest row of the table that has the information it
needs; access control is in authorization or
denied(...), not a validator.
- Every validator is exported (or passed to
add()), extends the right base
class, and carries @validator(ExactTarget).
- Rejections are
ValidationResults built with ValidationResult.error/warning/information(...),
validation(...) or rule messages — never thrown errors.
readModelForValidation is called only inside a model-bound command's
validator, with { optional: true } wherever absence is a legitimate state.
- Generated metadata and proxies are regenerated after a validator changes, so
the client-copied rules match the server's.
- Specs assert the authored rule and member through
validate() and prove
handle() did not run.
1---2name: cratis-arc-validation-typescript3description: Use when adding rejection rules, state checks or validation assertions to an Arc Node.js server. Not for defining commands or queries, C# and JVM validators, or append-time uniqueness.4license: MIT5metadata:6 source: https://skillmd.com/skills/cratis/cratis-arc-validation-typescript7---89# Validate an Arc command or query in TypeScript (Node.js server)1011A rule in Arc for TypeScript lives where the information it needs is available,12and as early as that allows. Validators run before `handle()` and also answer on13the command's `POST <route>/validate`, so a form can ask before the user14submits. Every rejection comes back as a `ValidationResult` with a message and15the member it concerns — never as a thrown error.1617Arc for TypeScript ships as stable 1.0.0 packages on npm (`@cratis/arc.core`18and the other server packages). The published19`@cratis/arc` client is separate; it runs the client-safe rules the proxy20generator copies into generated proxies. Setup is in21`cratis-arc-command-typescript`.2223## Verified product sources2425Source: `Cratis/Arc.TypeScript`, reading `Source/Core/validation/**` (including26`index.ts`, `ValidationResult.ts`, `Severity.ts`, `RuleBuilder.ts`),27`Source/Core/commands/Outcome.ts`, `Documentation/commands/command-validation.md`,28`validation-severity-filtering.md`, `command-outcomes.md`,29`Documentation/queries/validation.md`, `Documentation/concepts.md`,30`Documentation/proxy-generation/validation.md`, `Source/Testing`, and the31`Samples/Tasks` validators.32`ValidationResult` is both the exported interface and a value with the helpers33`ValidationResult.information/warning/error(message, options?)`; the positional34`validation(...)` function remains available.3536## Choose where to reject3738| The decision depends on | Put it in | Runs on `/validate` | Caller sees |39| --- | --- | --- | --- |40| The request's shape: types, required/optional fields | `@field` plus `@optional()`/`@nullable()`/`@defaultValue()` | Yes | 400 `malformedRequest`, no message or members |41| Who is calling | `@roles`, `@authorize`, a policy | Yes | 401 or 403 |42| One value, wherever it appears | `ConceptValidator` on the concept | Yes | 400 with your message and member |43| The command's own fields, or a service | `CommandValidator` | Yes | 400 with your message and member |44| Stored state for the command's key | `CommandValidator` rule calling `readModelForValidation` | Yes | 400 with your message and member |45| Data you load anyway to do the work | `provide()` returning `rejected(...)` or `denied(...)` | No | 400 or 403 |46| A decision only the handler can make | `handle()` returning `rejected(...)` or `denied(...)` | No | 400 or 403 |4748- **Reject as early as the information allows.** Everything through the49 `readModelForValidation` row answers on `/validate`.50- **Keep access control out of validators.** A trusted caller can lower the51 blocking severity and let validation results through; nothing lowers52 authorization or `denied(...)`.53- A stored-state check tells you what was true when it ran. A rule that must hold54 under concurrency belongs at the storage boundary (for Chronicle, a constraint55 or concurrency scope — `cratis-chronicle-event-constraints`).5657## Command rules — `CommandValidator`5859`Samples/Tasks/Features/Tasks/Registration/Registration.ts` keeps the validator60in the slice file with its command:6162```typescript63import { command, CommandValidator, validator } from '@cratis/arc.core';6465@validator(RegisterTask)66export class RegisterTaskValidator extends CommandValidator<RegisterTask> {67 constructor() {68 super();69 this.ruleFor(command => command.title).notEmpty().withMessage('A title is required');70 this.ruleFor(command => command.title).maxLength(100).withMessage('A title can have at most 100 characters');71 }72}73```7475- `@validator(Target)` supplies the runtime target that the erased generic76 cannot. It registers nothing globally: `discover()` picks the exported class up77 from the folder, or pass it to `builder.add(RegisterTask, RegisterTaskValidator)`78 and to `CommandScenario.for(...)`. A validator that is never imported is never79 registered.80- One validator per **exact** target class; a duplicate target fails at build.81- Rules on a concept member receive the unwrapped primitive — `TaskTitle` rules82 accept a `string`.83- Every rule runs; a failure does not stop the others, so a form sees every84 problem at once. Any result above the allowed severity blocks `handle()`.8586## Value rules — `ConceptValidator`8788A rule that belongs to the value goes on the concept, once.89`Samples/Tasks/Features/Tasks/TaskTitleValidator.ts`:9091```typescript92import { ConceptValidator, validator } from '@cratis/arc.core';93import { TaskTitle } from './TaskTitle.js';9495@validator(TaskTitle)96export class TaskTitleValidator extends ConceptValidator<TaskTitle> {97 constructor() {98 super();99 this.ruleFor(title => title.value).must(value => !value.startsWith('!'))100 .withMessage('A title cannot begin with an exclamation mark');101 }102}103```104105Arc walks the declared `@field` members of commands, query arguments and nested106models, and runs the concept validator on every `TaskTitle` it meets, including107inside arrays. A failure inside `entries[]` reports `entries.title`, not an108index. The owner's own rules still run. To skip only the **direct** member's109concept rules, call `.ignoreConceptRules()` on the owner's `ruleFor(...)` chain;110descendants are still traversed. The Library sample keeps `AuthorName` and its111`AuthorNameValidator` together in `AuthorName.ts`.112113`ModelValidator<T>` validates a nested model class the same way, wherever it114appears in a command or query-argument graph.115116## Query rules — `QueryValidator`117118A `QueryValidator` targets an explicit **arguments model** whose `@field`119declarations match the query's `argument(...)` descriptors:120121```typescript122import { ConceptAs, field } from '@cratis/fundamentals';123import { QueryValidator, argument, query, readModel, validator } from '@cratis/arc.core';124125export class Name extends ConceptAs<string> { static readonly valueType = String; }126127export class SearchArguments {128 @field(Name) term!: Name;129}130131@validator(SearchArguments)132export class SearchArgumentsValidator extends QueryValidator<SearchArguments> {133 constructor() {134 super();135 this.ruleFor(arguments_ => arguments_.term).notEmpty().withMessage('Term required');136 }137}138139@readModel()140export class Search {141 @query({ argumentsModel: SearchArguments }, argument('term', Name))142 static byTerm(term: Name): string { return term.value; }143}144```145146Without an arguments model, Arc still runs concept validators on each supplied,147non-null argument under that argument's name, but a `QueryValidator` has nothing148to target. Queries always use `Warning` as the allowed severity.149150## Rules that read stored state — `readModelForValidation`151152```typescript153import { field } from '@cratis/fundamentals';154import { command, CommandValidator, key, readModelForValidation, validator } from '@cratis/arc.core';155156@command()157export class RenameTask {158 @field(String) @key() id!: string;159 @field(String) title!: string;160 handle(): void { /* rename in storage */ }161}162163@validator(RenameTask)164export class RenameTaskValidator extends CommandValidator<RenameTask> {165 constructor() {166 super();167 this.ruleFor(command => command.title).mustAsync(async title => {168 const current = await readModelForValidation(TaskView, { optional: true });169 return current === null || current.title !== title;170 }).withMessage('The task already has this title');171 }172}173```174175- Arc resolves the command key (`@key()`, `getKey()`, or a resolver) and asks the176 resolver that owns `TaskView` — registered by MongoDB, Drizzle, experimental177 Chronicle, or `builder.addReadModelForCommandResolver(token)`. The resolver178 receives the caller's tenant.179- `{ optional: true }` returns `null` for a missing model. Without it, a missing180 model makes the rule throw, and the caller gets `validatorFailed` instead of181 your message.182- It works **only** inside a validator of a model-bound command, during183 validation. Validators do not receive read models through their constructors.184- Reads are scoped to the current command/tenant and cancellation signal, on185 both validate and execute routes; do not retain a validation read across calls.186187## Rule vocabulary188189| Rules | Where they run |190| --- | --- |191| `notNull`, `notEmpty`, `minLength`, `maxLength`, `length`, `emailAddress`, `phone`, `url`, `matches`, `greaterThan`, `greaterThanOrEqual`, `lessThan`, `lessThanOrEqual` | Server; literal, unconditional uses are also copied into generated proxies |192| `empty`, `null`, `equal`, `notEqual`, `inclusiveBetween`, `exclusiveBetween`, `must`, `mustAsync` | Server only |193194- `withMessage`, `withSeverity(Severity.Warning)`, and `withState(value)`195 decorate the most recent rule.196- `when(predicate)` / `unless(predicate)` condition **every rule on the chain**197 by default; pass `ApplyConditionTo.CurrentValidator` to condition only the198 latest. Conditions and predicates run on the server only.199- `must` and `mustAsync` receive `(value, model, signal)`; pass the signal to200 cancelable I/O.201- String rules exist only for strings; comparison rules only for numbers and202 temporal values. `notEmpty()` rejects `Guid.empty`.203- Email, phone, URL, regex and Unicode-length behavior is not guaranteed to match204 the client or Arc on .NET exactly. Write an explicit message and specify the205 inputs you accept.206- The generator copies rules for commands (including direct concept fields) and207 for query arguments with an explicit `argumentsModel`. A rule that stays208 server-only produces a source diagnostic. The server validates every request209 regardless.210211## Services in a validator212213Declare constructor dependencies with `@injectable(Service)` or214`static inject = [Service] as const`, and register the service with215`builder.services`. Arc constructs each validator once during `build()` (catching216invalid selectors early), then resolves fresh validators per execution scope. A217validator that throws, or whose dependency cannot be resolved, never reports218success: the caller gets 400 with reason `validatorFailed` or219`dependencyUnavailable`, no exception text, and the error goes to the logger.220221## Reject from `provide()` or `handle()`222223```typescript224import { denied, rejected, validation, Severity, ValidationResult } from '@cratis/arc.core';225226return rejected(ValidationResult.error('The task does not exist', { members: ['id'], reason: 'notFound' }));227return rejected(ValidationResult.warning('Unusually long title', { members: ['title'], reasonDetail: 'TitleLength' }));228return rejected(validation('Unusually long title', ['title'], 'rule', Severity.Warning));229return denied('Only the owner can rename a task');230```231232- `ValidationResult.information/warning/error(message, options?)` (Requires Arc for233 TypeScript 0.34.0) build a result at that severity; `options` sets234 `members`, `state` (must be JSON-serializable), `reason` (default `rule`) and235 `reasonDetail`. `members` defaults to `[]` and `reason` to `rule`; omitted236 `state` and `reasonDetail` are left out of the result.237- `validation(message, members = [], reason = 'rule', severity = Severity.Error)`238 builds a `ValidationResult` (`{ severity, message, members, reason }`) with239 positional arguments; it cannot set `reasonDetail` or `state`.240- `rejected(...results)` answers 400; it throws when given no results, so an241 empty rejection can never pass as success. `denied(reason?)` answers 403 with242 `authorizationFailureReason`.243- Rejected results go through the same severity filter. When nothing above the244 allowed severity remains, `handle()` runs (from `provide()`, with `undefined`245 as the provided value) or the command succeeds without a response (from246 `handle()`).247- Throwing is for failures, not decisions: a thrown error is a 500.248249## Severity filtering250251`Severity` is `Unknown` (0), `Information` (1), `Warning` (2), `Error` (3).252Results at or below the **allowed severity** are removed and do not block;253results above it block and are returned. The default is `Warning`, so only254errors block.255256| Caller | Allowed severity |257| --- | --- |258| HTTP command | `X-Allowed-Severity` header `0`, `1` or `2`; missing or invalid means `2`; `3` is **capped** to `2`, so errors always block |259| HTTP query | Always `Warning`; the header is ignored |260| `executeCommand` from code, or `CommandScenario.withAllowedValidationSeverity(...)` | As given, including `Severity.Error` |261| `performQuery` from code | Always `Warning` |262263The HTTP cap at `Warning` is a deliberate safety difference from Arc on .NET,264which lets `X-Allowed-Severity: 3` run a command whose only problems are265errors. Do not "fix" it toward .NET behavior. `@command({ treatWarningsAsErrors: true })`266and `@query({ treatWarningsAsErrors: true })` set the generated client's flag.267268## Specify the rule269270```typescript271import { given, type ScenarioCommandResult } from '@cratis/arc.testing';272273describe('when validating a task with an empty title', given(a_task_registration, context => {274 let result: ScenarioCommandResult;275 beforeEach(async () => {276 result = await context.scenario.validate({ id: TaskId.create(), title: new TaskTitle('') });277 });278 afterAll(async () => { await context.scenario.dispose(); });279 it('should report the authored rule for title', () => {280 result.shouldHaveValidationErrors().shouldHaveValidationErrorForMember('title');281 });282 it('should not invoke the handler', () => { context.tasks.all().should.have.lengthOf(0); });283}));284```285286- Use `scenario.validate(...)` to prove the rule answers on `/validate`, and287 `execute(...)` to prove `handle()` never ran.288- Assert the member with `shouldHaveValidationErrorForMember('title')` by289 default, not presentation text. Assert exact wording only when it is the290 specified behavior, and name that requirement in the fact.291 `shouldHaveValidationErrorFor(text)` passes for any message **containing** the292 text; even a full-message argument does not prove exact equality. Compare293 the actual message for equality when exact wording is the requirement.294- `validatorFailed` and `dependencyUnavailable` never satisfy295 `shouldHaveValidationErrors()` or the member assertion — they mean no authored296 rule was established. Assert them explicitly with297 `shouldHaveValidationErrorBecauseOf('validatorFailed')`.298 `shouldHaveRuleFailure(result, { reason, member?, severity? })` from299 `@cratis/arc.testing` asserts an authored rule on a plain result.300- For a query, `QueryScenario.perform(...)` returns a result whose301 `validationResults` you assert the same way.302303## Route near misses304305- Defining the command or query the rule attaches to:306 `cratis-arc-command-typescript`, `cratis-arc-query-typescript`.307- Append-time uniqueness or concurrency in Chronicle:308 `cratis-chronicle-event-constraints` and the Chronicle reference in309 `cratis-arc-command-typescript`.310- The .NET validation shape: `cratis-arc-command-validation`; Kotlin/Java:311 `cratis-arc-validation-kotlin`.312313## Verify314315- Each rule sits in the earliest row of the table that has the information it316 needs; access control is in authorization or `denied(...)`, not a validator.317- Every validator is exported (or passed to `add()`), extends the right base318 class, and carries `@validator(ExactTarget)`.319- Rejections are `ValidationResult`s built with `ValidationResult.error/warning/information(...)`,320 `validation(...)` or rule messages — never thrown errors.321- `readModelForValidation` is called only inside a model-bound command's322 validator, with `{ optional: true }` wherever absence is a legitimate state.323- Generated metadata and proxies are regenerated after a validator changes, so324 the client-copied rules match the server's.325- Specs assert the authored rule and member through `validate()` and prove326 `handle()` did not run.