@cratis/pi 8.8.0 → 8.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package/corpus/skills/cratis-arc-declare-command/references/csharp-chronicle.md +1 -1
- package/package/corpus/skills/cratis-arc-host-application/SKILL.md +2 -2
- package/package/corpus/skills/cratis-arc-host-application/references/csharp-availability.md +1 -0
- package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-navigation.md +4 -0
- package/package/corpus/skills/cratis-arc-testing-typescript/SKILL.md +1 -1
- package/package/corpus/skills/cratis-arc-testing-typescript/references/typescript.md +17 -0
- package/package/corpus/skills/cratis-authproxy-configure/SKILL.md +8 -5
- package/package/corpus/skills/cratis-authproxy-configure/references/admission.md +42 -0
- package/package/corpus/skills/cratis-authproxy-configure/references/services-and-routing.md +66 -2
- package/package/corpus/skills/cratis-authproxy-configure/references/tenant-resolution.md +62 -5
- package/package/corpus/skills/cratis-chronicle-cli-operations/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-cli-operations/references/project-tooling.md +52 -3
- package/package/corpus/skills/cratis-chronicle-connect-application/references/go.md +1 -1
- package/package/corpus/skills/cratis-chronicle-connect-application/references/typescript.md +1 -1
- package/package/corpus/skills/cratis-chronicle-project-view/SKILL.md +1 -1
- package/package/corpus/skills/cratis-chronicle-project-view/references/csharp.md +7 -1
- package/package/corpus/skills/cratis-chronicle-react-to-fact/SKILL.md +2 -0
- package/package/corpus/skills/cratis-chronicle-react-to-fact/references/typescript.md +1 -1
- package/package/corpus/skills/cratis-chronicle-reduce-state/SKILL.md +1 -0
- package/package/corpus/skills/cratis-code-review/SKILL.md +1 -0
- package/package/corpus/skills/cratis-components-choose-control/SKILL.md +1 -1
- package/package/corpus/skills/cratis-components-choose-control/references/typescript-common.md +1 -1
- package/package/corpus/skills/cratis-components-submit-form/SKILL.md +2 -2
- package/package/corpus/skills/cratis-components-submit-form/references/typescript-commanddialog.md +2 -2
- package/package/corpus/skills/cratis-components-submit-form/references/typescript-commandform.md +11 -1
- package/package/corpus/skills/cratis-components-theme-application/SKILL.md +1 -1
- package/package/corpus/skills/cratis-fundamentals-concept/references/csharp-serialization.md +3 -1
- package/package/corpus/skills/cratis-fundamentals-concept/references/typescript-serialization.md +2 -0
- package/package/corpus/skills/cratis-platform-upgrade-application/SKILL.md +1 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-events.md +9 -1
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-query-scenario.md +31 -0
- package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp.md +15 -0
- package/package/corpus/skills/cratis-specifications-test-typescript-behavior/SKILL.md +2 -1
- package/package/corpus/skills/cratis-specifications-test-typescript-behavior/references/typescript.md +38 -0
- package/package.json +1 -1
|
@@ -143,7 +143,7 @@ One top-level command is one transaction: Arc starts it before `Handle` runs, en
|
|
|
143
143
|
| --- | --- |
|
|
144
144
|
| A command executed from inside another command's `Handle` | It joins the outer transaction, and its returned events commit only when the outer command does. An aggregate the nested command commits explicitly is different: it can commit the shared transaction at once, and a later failure of the outer command cannot then undo it. Do not commit an aggregate inside a nested command. Its successful result means "enrolled", not "committed". Inspect the nested result and propagate a failure, or the outer command commits despite it. Not when either command's `Handle` can return an operation: the nested command is then rejected with `InvalidCommandOperation` before it runs. |
|
|
145
145
|
| Several commands returned by one reactor | Separate transactions: earlier ones stay committed when a later one fails. Return one command when the events must commit together. |
|
|
146
|
-
| A command executed through `ICommandPipeline` from a controller action | Its own transaction, committed when `Execute` returns. A later failure of the action does not undo it. The action's own transactional appends commit when the action ends. |
|
|
146
|
+
| A command executed through `ICommandPipeline` from a controller action | Its own transaction, committed when `Execute` returns. A later failure of the action does not undo it. The action's own transactional appends commit when the action ends. `Execute` reports a refusal or failure in the returned `CommandResult` and the action carries on: an unchecked failed result leaves the action successful and its own appends committed. Check `IsSuccess` after every `Execute`. Returning the failed inner `CommandResult` from the action does not fail the action: Arc wraps it as the response data of a successful outer result, and the action's own staged appends still commit. When they must roll back, throw an application exception, with an `IExceptionResponseMapper` giving it the intended status and error code. When the action staged nothing, returning early is enough. |
|
|
147
147
|
| A POST controller action as the command | It has a transaction (not with `[AspNetResult]`), but no read protection and no `[GeneratedValue]` parameters. |
|
|
148
148
|
| Chronicle's request-level unit-of-work middleware | A different boundary. A command starts its own transaction and never joins it. |
|
|
149
149
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-arc-host-application
|
|
3
|
-
description: Use when creating, configuring or starting an Arc application host - choosing the bootstrap, setting host options, wiring authentication and identity details, serving a frontend, giving a known application exception a public failure status, stable error code and optional Retry-After instead of the default 500 - and when verifying that the host serves a registered endpoint. Not for connecting a Chronicle kernel (use cratis-chronicle-connect-application), protecting one operation (use cratis-arc-authorize-request), selecting a tenant (use cratis-arc-isolate-tenant) or adding services or configuration to a Stage-rendered application, whose host and settings files are generated (use cratis-stage-render-slice).
|
|
3
|
+
description: Use when creating, configuring or starting an Arc application host - choosing the bootstrap, setting host options, wiring authentication and identity details, serving a frontend, giving a known application exception a public failure status, stable error code and optional Retry-After instead of the default 500, gating product parts with feature availability (audiences, and audience or suspension sources that every replica shares) - and when verifying that the host serves a registered endpoint. Not for connecting a Chronicle kernel (use cratis-chronicle-connect-application), protecting one operation (use cratis-arc-authorize-request), selecting a tenant (use cratis-arc-isolate-tenant) or adding services or configuration to a Stage-rendered application, whose host and settings files are generated (use cratis-stage-render-slice).
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Host an Arc application
|
|
@@ -51,7 +51,7 @@ Python has no Arc application SDK and cannot host operations: host them in a ser
|
|
|
51
51
|
- **Development rosters:** supply users and tenants for local tooling, never as proof of authentication or membership.
|
|
52
52
|
- **Named policies and filters:** register shared policies or pipeline participants at composition; use `cratis-arc-authorize-request` for operation requirements.
|
|
53
53
|
- **Tenant resolution and membership:** select a candidate tenant, then check the caller's access before opening tenant resources; use `cratis-arc-isolate-tenant`.
|
|
54
|
-
- **Availability:** install audience and suspension sources when access to a product part depends on rollout or entitlement; availability does not replace authorization. Those sources hold runtime data, not declarations: the audiences a caller holds (granted per tenant, user or system where the SDK records levels) and suspensions of a module, feature, slice or part; a suspension wins over every grant. Ask whether one part is offered for given input before showing it; the server still gates execution. Build the availability manifest file for review and contract tests and evaluate parts from it, never as the runtime decision. Declaration language: `cratis-screenplay-availability`.
|
|
54
|
+
- **Availability:** install audience and suspension sources when access to a product part depends on rollout or entitlement; availability does not replace authorization. Those sources hold runtime data, not declarations: the audiences a caller holds (granted per tenant, user or system where the SDK records levels) and suspensions of a module, feature, slice or part; a suspension wins over every grant. Ask whether one part is offered for given input before showing it; the server still gates execution. Build the availability manifest file for review and contract tests and evaluate parts from it, never as the runtime decision. C#: read `references/csharp-availability.md` for registration, custom sources, suspension and running more than one replica. Declaration language: `cratis-screenplay-availability`.
|
|
55
55
|
- **Capabilities:** gate a dedicated endpoint group on verified caller kinds; select specific routes only when other routes on the group port should remain outside the gate.
|
|
56
56
|
|
|
57
57
|
## Operational catalog
|
|
@@ -14,6 +14,7 @@ Availability decides whether a part (module, feature, slice, command or read mod
|
|
|
14
14
|
|
|
15
15
|
- `arc.WithAvailability()` (types in `Cratis.Arc.Availability`) adds the command and query gates, the `/.cratis/availability` query, startup validation of the declared blocks, and in-memory audience and suspension sources. Without an Arc builder use `services.AddArcAvailability()`; `services.AddAvailability()` registers only the engine, for a process without Arc's pipelines.
|
|
16
16
|
- Replace the in-memory sources when rollout is externally managed. Before Arc registration call `builder.Services.AddSingleton<IAudienceSource, DispatchAudiences>();` and `builder.Services.AddSingleton<ISuspensionSource, DispatchSuspensions>();`. `IAudienceSource.GetGrants` (`Cratis.Arc.Availability.Audiences`) returns the audiences granted to a subject; `ISuspensionSource.GetDecisions` (`Cratis.Arc.Availability.Suspensions`) returns suspend and resume decisions. Invoke the handlers subscribed through each source's `OnChanged` when grants or decisions change, so open sessions decide again.
|
|
17
|
+
- The in-memory sources live in one process. With more than one replica, a grant or suspension made on one instance is unknown to the others, so back both sources with state every replica reads. Each replica must also invoke its own `OnChanged` handlers when that shared state changes, whichever instance made the change; otherwise sessions open on the other replicas keep their earlier decision until they decide again.
|
|
17
18
|
- A source that cannot answer must throw. The result is then retryable (HTTP 503, `IsRetryable` true), never a refusal.
|
|
18
19
|
|
|
19
20
|
## Declare gates
|
package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-navigation.md
CHANGED
|
@@ -47,7 +47,11 @@ const location = useLocation();
|
|
|
47
47
|
</main>
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
+
- **Use the Components `ErrorBoundary`.** It already covers reporting, a fallback and retry, so do not write your own boundary class. Its full prop contract is in `cratis-components-choose-control`.
|
|
50
51
|
- **Key the boundary by the path.** A boundary that has caught an error keeps showing its fallback until it is reset. Without the key, choosing another menu entry would still show the fallback; with it, a new path mounts a fresh boundary.
|
|
52
|
+
- **Report with `onError`.** `onError={(error, errorInfo) => report(error, errorInfo.componentStack)}` receives each caught render error and React's component stack. Supplying it replaces the default `console.error`, so the handler must log or report the error itself. Keep it free of state updates in the failed subtree.
|
|
53
|
+
- **Recover with `fallback` and `onReset`.** `fallback` is a node, or a function `reset => <RetryPanel onRetry={reset} />` that receives the reset callback. Omitted, the boundary shows a generic message with a "Try again" button. `reset` calls `onReset` and then renders the children again. Clear whatever made the render fail in `onReset`, for example a cached value or a selection; otherwise the same error is thrown again at once.
|
|
54
|
+
- **Key and reset differ.** A changed `key` remounts the boundary and everything in it and does not call `onReset`. `reset` keeps the boundary mounted, but the failed children still mount fresh, because the fallback replaced them.
|
|
51
55
|
- `ErrorBoundary` catches errors thrown while rendering, not errors in event handlers or asynchronous work. Expected command and query failures arrive as results, but a call can still reject, so keep a `catch` in the handler and show the failure there (see [Commands](typescript-commands.md)).
|
|
52
56
|
|
|
53
57
|
## Menu
|
|
@@ -35,7 +35,7 @@ Read `references/<language>.md` for the project's SDK (`.csproj` → csharp, Nod
|
|
|
35
35
|
- **Scoped registration** — use a factory for a dependency shared within one request or subscription scope.
|
|
36
36
|
- **Transient registration** — use a factory for an instance per resolution.
|
|
37
37
|
- **Builder extension** — add generated metadata or integration wiring before lazy construction on the first act.
|
|
38
|
-
- **Trusted principal** — supply identity, roles and authentication state; this tests authorization, not authentication.
|
|
38
|
+
- **Trusted principal** — supply identity, roles and authentication state; this tests authorization, not authentication. The authentication handler never runs, so prove it and the 401 or 403 status over HTTP; the SDK reference lists which status applies.
|
|
39
39
|
- **Trusted tenant** — select the tenant for a direct call; to test how the tenant is resolved, use HTTP.
|
|
40
40
|
- **Correlation and cancellation** — supply known values to verify propagation or termination.
|
|
41
41
|
- **Trusted connection metadata** — exercise direct subscription admission with a known peer instead of treating user input as transport identity.
|
|
@@ -172,6 +172,23 @@ try {
|
|
|
172
172
|
- `handle(request)` — send a `Request` through HTTP routing and authentication; `null` means not handled. Assert the response status and serialized contract. For a native host adapter or transport framing, test the actual adapter.
|
|
173
173
|
- `dispose()` — close the server; dispose a separately supplied `ServiceRegistry` yourself.
|
|
174
174
|
|
|
175
|
+
### Authentication handlers and status codes
|
|
176
|
+
|
|
177
|
+
A trusted principal in a scenario context bypasses the application's authentication handlers. A case that sets no principal therefore proves only the anonymous authorization rule, whatever credential the spec meant to represent. Use two kinds of spec:
|
|
178
|
+
|
|
179
|
+
- **Authorization rule** (roles, policies): vary the trusted principal with `withContext` or the per-call context, and assert `isAuthorized` on the result.
|
|
180
|
+
- **Authentication handler and status code**: build the server with the application's `authentication` handlers and send a `Request` through `handle(request)`. Assert `response.status`.
|
|
181
|
+
|
|
182
|
+
| Request | Status |
|
|
183
|
+
| --- | --- |
|
|
184
|
+
| A handler returns `Failed` (a wrong credential), whatever the operation requires | 401 |
|
|
185
|
+
| Anonymous caller on a protected operation, when the server can authenticate it: a default `authentication` handler is configured, the operation selects a named scheme, or `nativePrincipal` is on | 401 |
|
|
186
|
+
| Anonymous caller on a protected operation in any other configuration (for example, named schemes registered but not selected by the operation) | 403 |
|
|
187
|
+
| Authenticated caller without a required role, or a policy returned `false` | 403 |
|
|
188
|
+
| `provide()` or `handle()` returned `denied(reason)` | 403 |
|
|
189
|
+
|
|
190
|
+
The body of every row is an Arc result with `isAuthorized: false`. A protected operation is one that requires authentication, a role, a policy or a scheme and is not marked anonymous. Do not assume an anonymous caller always gets 401: without one of the three configurations above, the Arc authorization result is 403. Arc on .NET differs: every result Arc itself refuses as unauthorized, an anonymous caller included, maps to 403 with `isAuthorized: false`. The host's authentication middleware can still challenge an anonymous caller with 401 before Arc runs, and that response is the middleware's own, without an Arc result body.
|
|
191
|
+
|
|
175
192
|
Session consumers can inspect `rejection` for any unsuccessful opening result; `current()` obtains a rendered current value without starting the iterator, or returns `undefined` when unavailable. `results()` returns a single-consumer async generator; calling it twice throws. If consumed despite an opening rejection, it yields the redacted rejection and ends. Always await `close()` in `finally` to abort, release the iterator and dispose the scope; cleanup can fail. Use the caller's `signal` to cancel a direct open or stream. Arc's internal `cancel()` aborts without cleanup; consumers should use `close()` instead. `reportTransportFailure(error)` forwards transport or serialization failures to the configured logger; it is for transport adapters, not ordinary result assertions. Leave transaction coordination and other internal shutdown methods to Arc.
|
|
176
193
|
|
|
177
194
|
Direct opening throws for an already canceled request, disposed server or registry, an unknown or non-observable query, or exhausted capacity (`ObservableSubscriptionLimitError`, not a pipeline rejection). The limit error is internal, not a package import. Configure `query.maxObservableSubscriptions` for the total and `query.maxObservableSubscriptionsPerCaller` to test per-caller admission; close the first session before proving another can enter. Pipeline failures are exposed as `session.rejection`, not as that admission error. See `cratis-arc-host-application` for host configuration, `cratis-arc-authorize-request` for authentication and authorization, and `cratis-arc-expose-query` for transport settings.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-authproxy-configure
|
|
3
|
-
description: "Use when putting Cratis AuthProxy in front of an application or changing its configuration: sign-in providers, who is admitted, tenant resolution and switching, sessions and sign-out, routing to services, running it in production or under Aspire. Not for authorizing a command or query (`cratis-arc-authorize-request`) or reading identity in the backend (`cratis-arc-host-application`)."
|
|
3
|
+
description: "Use when putting Cratis AuthProxy in front of an application or changing its configuration: sign-in providers, who is admitted (required claims, GitHub organization or team membership), tenant resolution and switching (including the endpoint that lists a person's tenants), machine clients that get tokens from the proxy (client credentials, `/.cratis/token`), sessions and sign-out, routing to services, running it in production or under Aspire. Not for authorizing a command or query (`cratis-arc-authorize-request`) or reading identity in the backend (`cratis-arc-host-application`)."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Configure Cratis AuthProxy: the ingress that signs people in
|
|
@@ -90,14 +90,17 @@ One application, one sign-in provider, one tenant. Run the `cratis/authproxy` im
|
|
|
90
90
|
|---|---|---|
|
|
91
91
|
| Add Microsoft, Google, GitHub or another provider | Declare it under `Authentication` | [sign-in-providers.md](references/sign-in-providers.md) |
|
|
92
92
|
| Only some people at the provider may enter | Require a claim | [admission.md](references/admission.md) |
|
|
93
|
+
| Only members of a GitHub organization or team may enter | `read:org` scope and a required `urn:github:` claim | [admission.md](references/admission.md) |
|
|
93
94
|
| The application decides who may enter | Answer `/.cratis/me`; keep `Required` | [admission.md](references/admission.md) |
|
|
94
95
|
| Several tenants | Choose a resolution strategy | [tenant-resolution.md](references/tenant-resolution.md) |
|
|
95
96
|
| A person switches between tenants | `Selection` strategy and `/.cratis/select-tenant` | [tenant-resolution.md](references/tenant-resolution.md) |
|
|
97
|
+
| The application serves the list of a person's tenants | `GET` endpoint, signed in the `Selection` options, `5xx` on failure | [tenant-resolution.md](references/tenant-resolution.md) |
|
|
96
98
|
| Add a sign-out link | Navigate to `/.cratis/logout` | [sessions-and-logout.md](references/sessions-and-logout.md) |
|
|
97
99
|
| A sensitive page needs a recent sign-in | `FreshAuthentication` on the path | [sessions-and-logout.md](references/sessions-and-logout.md) |
|
|
98
100
|
| Several applications behind one sign-in | Route by host, path prefix or header | [services-and-routing.md](references/services-and-routing.md) |
|
|
99
101
|
| A webhook or public page without sign-in | `AnonymousPaths` on the service | `cratis-arc-authorize-request` |
|
|
100
|
-
| A CLI, agent or other program calls the API | A bearer route | `cratis-arc-authorize-request` |
|
|
102
|
+
| A CLI, agent or other program calls the API with a token from an authorization server | A bearer route | `cratis-arc-authorize-request` |
|
|
103
|
+
| A program calls the API with a client id and secret the application owns | `ClientCredentials` on the service; the client posts to `/.cratis/token` | [services-and-routing.md](references/services-and-routing.md) |
|
|
101
104
|
| The backend calls another API as the user | `AccessToken` on the service | [services-and-routing.md](references/services-and-routing.md) |
|
|
102
105
|
| A live query drops after minutes of silence | Raise `ActivityTimeout` | [services-and-routing.md](references/services-and-routing.md) |
|
|
103
106
|
| More than one replica, or people are signed out at restart | Share the data protection key ring | [operations.md](references/operations.md) |
|
|
@@ -110,10 +113,10 @@ One application, one sign-in provider, one tenant. Run the `cratis/authproxy` im
|
|
|
110
113
|
| Reference | Read when |
|
|
111
114
|
|---|---|
|
|
112
115
|
| [references/sign-in-providers.md](references/sign-in-providers.md) | Adding or changing a sign-in provider, registering callbacks, or offering sign-in by e-mail code. |
|
|
113
|
-
| [references/admission.md](references/admission.md) | Deciding who gets past the proxy: required claims, GitHub
|
|
114
|
-
| [references/tenant-resolution.md](references/tenant-resolution.md) | Choosing how the tenant is resolved, verifying it exists, or building a tenant switcher. |
|
|
116
|
+
| [references/admission.md](references/admission.md) | Deciding who gets past the proxy: required claims, admitting only a GitHub organization or team, the `/.cratis/me` verdict, what a refused person sees. |
|
|
117
|
+
| [references/tenant-resolution.md](references/tenant-resolution.md) | Choosing how the tenant is resolved, verifying it exists, serving or securing the endpoint that lists a person's tenants, handling its outages and removed tenant access, or building a tenant switcher. |
|
|
115
118
|
| [references/sessions-and-logout.md](references/sessions-and-logout.md) | Setting session lifetime, adding sign-out, requiring a recent sign-in, or handling a `401` in the frontend. |
|
|
116
|
-
| [references/services-and-routing.md](references/services-and-routing.md) | Routing several services, limiting forwarded paths, reading the forwarded headers, or keeping long-lived connections open. |
|
|
119
|
+
| [references/services-and-routing.md](references/services-and-routing.md) | Routing several services, limiting forwarded paths, reading the forwarded headers, or keeping long-lived connections open. Also any machine client: client credentials, `/.cratis/token`, the verification endpoint, refresh tokens. |
|
|
117
120
|
| [references/operations.md](references/operations.md) | Deploying: key ring, ingress, health probes, TLS to the backend, custom pages, telemetry. |
|
|
118
121
|
| [references/aspire.md](references/aspire.md) | Wiring the proxy in an Aspire AppHost. |
|
|
119
122
|
|
|
@@ -58,6 +58,48 @@ Add the `read:org` scope to the GitHub provider. The proxy then reads the person
|
|
|
58
58
|
|
|
59
59
|
Without the scope the claims are absent and every requirement on them refuses.
|
|
60
60
|
|
|
61
|
+
Admit one team of one organization with the scope on the provider and one requirement:
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"Cratis": {
|
|
66
|
+
"AuthProxy": {
|
|
67
|
+
"Authentication": {
|
|
68
|
+
"OAuthProviders": [
|
|
69
|
+
{
|
|
70
|
+
"Name": "GitHub",
|
|
71
|
+
"Type": "GitHub",
|
|
72
|
+
"AuthorizationEndpoint": "https://github.com/login/oauth/authorize",
|
|
73
|
+
"TokenEndpoint": "https://github.com/login/oauth/access_token",
|
|
74
|
+
"UserInformationEndpoint": "https://api.github.com/user",
|
|
75
|
+
"ClientId": "<client-id>",
|
|
76
|
+
"Scopes": [ "read:user", "user:email", "read:org" ],
|
|
77
|
+
"ClaimMappings": { "sub": "id", "name": "name", "preferred_username": "login", "email": "email" }
|
|
78
|
+
}
|
|
79
|
+
]
|
|
80
|
+
},
|
|
81
|
+
"Authorization": {
|
|
82
|
+
"RequiredClaims": [
|
|
83
|
+
{ "Claim": "urn:github:team", "AnyOf": [ "Acme/operations" ] }
|
|
84
|
+
]
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Supply `ClientSecret` from a secret store. See [sign-in-providers.md](sign-in-providers.md) for the provider itself.
|
|
92
|
+
|
|
93
|
+
- **Team value.** Write `organization/team-slug`. The slug is the last segment of the team's URL, not its display name. A team requirement already names its organization, so a second requirement on the organization adds nothing.
|
|
94
|
+
- **Several teams.** List them in one `AnyOf` to admit a member of any of them. Separate entries in `RequiredClaims` must all be satisfied.
|
|
95
|
+
- **`Type` must be `GitHub`.** It is what makes the proxy read memberships. `ClaimMappings` cannot produce them: GitHub's user endpoint returns nothing about membership.
|
|
96
|
+
- **Read at sign-in, not per request.** The claims live in the session. A person removed from the team keeps access until the session ends, at most `Session:Lifetime` (12 hours by default). Shorten it when removal must take effect sooner.
|
|
97
|
+
- **A failed read refuses.** When GitHub cannot be reached during sign-in the claims are absent, and the requirement refuses the person. Signing in again reads them again.
|
|
98
|
+
- **Organization approval.** GitHub lists only organizations that let the OAuth app see them. An organization that restricts third-party applications must approve the app, or its members are refused.
|
|
99
|
+
- **Limits.** The proxy reads up to 500 organizations and 500 teams per person.
|
|
100
|
+
- **GitHub Enterprise Server.** Point the three endpoints at the server; the membership endpoints follow `UserInformationEndpoint`.
|
|
101
|
+
- **In the backend.** The claims are part of the forwarded principal, so the application can read them without calling GitHub.
|
|
102
|
+
|
|
61
103
|
## Narrow one service
|
|
62
104
|
|
|
63
105
|
The same block on a service applies in addition to the root requirements:
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
- What the backend receives
|
|
9
9
|
- The caller's Authorization header
|
|
10
10
|
- Machine callers
|
|
11
|
+
- Client credentials the application verifies
|
|
11
12
|
- Live connections, replicas and gRPC
|
|
12
13
|
- Anti-patterns
|
|
13
14
|
|
|
@@ -92,9 +93,72 @@ With `AccessToken` the proxy obtains a token for the backend's audience and forw
|
|
|
92
93
|
| Situation | Use |
|
|
93
94
|
|---|---|
|
|
94
95
|
| An authorization server already issues tokens for the callers | A bearer route on the service. The default. See `cratis-arc-authorize-request` (`references/authproxy.md`). |
|
|
95
|
-
| The application owns its client ids and secrets and there is no authorization server | `ClientCredentials` on the service. |
|
|
96
|
+
| The application owns its client ids and secrets and there is no authorization server | `ClientCredentials` on the service: the proxy issues tokens at `POST /.cratis/token`. See below. |
|
|
96
97
|
|
|
97
|
-
|
|
98
|
+
### Client credentials the application verifies
|
|
99
|
+
|
|
100
|
+
```json
|
|
101
|
+
"Services": {
|
|
102
|
+
"main": {
|
|
103
|
+
"Backend": { "BaseUrl": "http://backend:8080/" },
|
|
104
|
+
"ClientCredentials": { "RoutePrefix": "/api", "VerificationPath": "/.cratis/client-credentials/verify" }
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
| Property | Default | Meaning |
|
|
110
|
+
|---|---|---|
|
|
111
|
+
| `RoutePrefix` | `/api` | The paths the issued tokens are valid on. It is matched against the path the client sends, before `StripPathPrefix` applies: a service with `PathPrefix: /reporting` uses `/reporting/api`. |
|
|
112
|
+
| `VerificationPath` | `/.cratis/client-credentials/verify` | The endpoint the application serves to check a client id and secret. A relative value resolves against `Backend:BaseUrl`; an absolute `http` or `https` URL is used as it is. |
|
|
113
|
+
| `RefreshTokenFamilyLifetime` | `30.00:00:00` | How long refresh tokens from one grant keep working. Must be greater than zero. |
|
|
114
|
+
|
|
115
|
+
The service needs a `Backend`. The application stores and verifies the secrets; the proxy only issues and validates the tokens.
|
|
116
|
+
|
|
117
|
+
**1. The client asks for a token.** `POST /.cratis/token` with a form-encoded body:
|
|
118
|
+
|
|
119
|
+
- `grant_type=client_credentials`
|
|
120
|
+
- `client_id` and `client_secret`, in the body. An `Authorization: Basic` header is not read.
|
|
121
|
+
- `service=<service key>`, required only when more than one service has `ClientCredentials`
|
|
122
|
+
|
|
123
|
+
**2. The proxy asks the application.** It sends `POST` to `VerificationPath` with this JSON body, and the status of the answer decides:
|
|
124
|
+
|
|
125
|
+
```json
|
|
126
|
+
{ "service": "main", "routePrefix": "/api", "clientId": "orders-importer", "clientSecret": "<secret>" }
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
| The application answers | The client gets from `/.cratis/token` |
|
|
130
|
+
|---|---|
|
|
131
|
+
| `2xx` | `200` with `access_token`, `token_type: "Bearer"`, `expires_in` and `refresh_token`. |
|
|
132
|
+
| `4xx` | `401` with `error: "invalid_client"`. |
|
|
133
|
+
| `5xx`, or the connection fails (refused, unresolved host) | `502` with `error: "server_error"`. |
|
|
134
|
+
| Nothing within ten seconds | The token request fails as a server error without this body. Do not rely on its exact status. |
|
|
135
|
+
|
|
136
|
+
- Answer `4xx` only for credentials that are wrong, and `5xx` when the credential store cannot be read. The client then sees an outage as an outage.
|
|
137
|
+
- Answer well within ten seconds, and fail fast with `5xx` when a dependency is slow. A client should treat a `5xx` answer from `/.cratis/token` as an outage and retry later, whatever its body.
|
|
138
|
+
- Compare the secret in constant time against a stored hash, and never log the request body.
|
|
139
|
+
- The endpoint receives secrets. Make it reachable from the proxy only, and list its path in the service's `DeniedPaths` so the proxy never forwards a public request to it.
|
|
140
|
+
|
|
141
|
+
**3. The client calls the API** with `Authorization: Bearer <access_token>`. The token is valid only on the service and `RoutePrefix` it was issued for, and is refused everywhere else. It expires after one hour, or at the end of `RefreshTokenFamilyLifetime` when that comes first: `expires_in` is then shorter than an hour, so read it instead of assuming 3600.
|
|
142
|
+
|
|
143
|
+
**4. The client renews** with `POST /.cratis/token`, `grant_type=refresh_token` and `refresh_token=<token>`. The answer has the same shape, with a new refresh token.
|
|
144
|
+
|
|
145
|
+
- A refresh does not call the application again. Rotating or deleting a client's secret does not stop its refresh tokens, and there is no revocation list. Set `RefreshTokenFamilyLifetime` to the longest time a removed client may keep its access.
|
|
146
|
+
- Refreshing never extends `RefreshTokenFamilyLifetime`, which is counted from the original grant. After it, `/.cratis/token` answers `401` with `error: "invalid_grant"` and the client sends its credentials again.
|
|
147
|
+
- Treat a refresh token as a secret of the same weight as the client secret.
|
|
148
|
+
|
|
149
|
+
**Tenant.** A machine client has no tenant unless the application names one. Return `{ "tenant": "<value>" }` from the verification endpoint and the token carries it as the claim `cratis/tenant`. Resolve it with a `Claim` strategy:
|
|
150
|
+
|
|
151
|
+
```json
|
|
152
|
+
"TenantResolutions": [
|
|
153
|
+
{ "Strategy": "Claim", "Options": { "ClaimType": "cratis/tenant" } }
|
|
154
|
+
]
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
The value is matched against the tenants' `SourceIdentifiers` like every other claim value. See [tenant-resolution.md](tenant-resolution.md).
|
|
158
|
+
|
|
159
|
+
**More than one replica.** The tokens are protected with the proxy's key ring. Without a shared, persisted key ring a token issued by one replica is refused by another, and every restart invalidates every token. See [operations.md](operations.md).
|
|
160
|
+
|
|
161
|
+
**Both kinds on one prefix.** A bearer route may share a prefix with client credentials only when its `PathPrefix` is exactly the service's `ClientCredentials:RoutePrefix`. No other overlap is allowed.
|
|
98
162
|
|
|
99
163
|
## Live connections, replicas and gRPC
|
|
100
164
|
|
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
- Verify that the tenant exists
|
|
9
9
|
- When no tenant resolves
|
|
10
10
|
- Let a person choose among several tenants
|
|
11
|
+
- Serve the tenant list
|
|
12
|
+
- Confirmation and removed access
|
|
13
|
+
- In-app tenant switcher
|
|
11
14
|
- Anti-patterns
|
|
12
15
|
|
|
13
16
|
## How resolution works
|
|
@@ -108,28 +111,82 @@ Use `Selection` when one account can belong to several tenants:
|
|
|
108
111
|
{ "Strategy": "Selection", "Options": { "TenantsEndpoint": "https://platform.example.com/api/tenants/selectable" } }
|
|
109
112
|
```
|
|
110
113
|
|
|
111
|
-
`TenantsEndpoint` is an absolute URL the application serves. It
|
|
114
|
+
`TenantsEndpoint` is an absolute URL the application serves. It answers with the tenants the signed-in person may enter.
|
|
112
115
|
|
|
113
116
|
| The endpoint answers | Result |
|
|
114
117
|
|---|---|
|
|
115
118
|
| Exactly one tenant | The tenant is selected automatically. No page is shown. |
|
|
116
119
|
| Several tenants | A browser navigation gets the tenant-selection page. Any other caller gets `403`. |
|
|
117
120
|
| An empty list, `401` or `403` | The person has no tenant: see [When no tenant resolves](#when-no-tenant-resolves). |
|
|
118
|
-
| Unreachable, a timeout,
|
|
121
|
+
| Unreachable, a timeout, any other status or unparseable JSON | `503`. The person is not reported as having no tenant. |
|
|
119
122
|
|
|
120
|
-
The selection page links to `/.cratis/select-tenant?tenantId=<id>&returnUrl=<path>`. The proxy
|
|
123
|
+
The selection page links to `/.cratis/select-tenant?tenantId=<id>&returnUrl=<path>`. The proxy asks the endpoint again before it stores the selection: a tenant that is not in the answer gets `400`, and an endpoint that cannot answer gets `503`.
|
|
121
124
|
|
|
122
|
-
|
|
125
|
+
### Serve the tenant list
|
|
126
|
+
|
|
127
|
+
The proxy calls the endpoint itself, server to server. The browser never calls it.
|
|
128
|
+
|
|
129
|
+
- **Request.** A `GET` with no body and no tenant. The person arrives in the same identity headers a proxied request carries: `x-ms-client-principal`, `x-ms-client-principal-id` and `x-ms-client-principal-name`. Derive the person from those headers, never from a query parameter or a body.
|
|
130
|
+
- **Response.** `200` with a JSON array of `{ "id": "...", "name": "..." }`. An entry with a blank `name`, or an `id` outside the tenant-identifier rule above, is dropped. An empty body counts as an empty list.
|
|
131
|
+
- **Answer only what is known.** An empty list, `401` and `403` are all the authoritative answer "this person has no tenant". Return them only when the membership lookup succeeded and found none.
|
|
132
|
+
- **Fail with `5xx`.** When the membership store cannot be read, answer `5xx`. Never answer `[]` or `200` from an error handler: the proxy would treat the person as having no tenant and, at the next confirmation, drop the tenant they had selected.
|
|
133
|
+
|
|
134
|
+
**The call is not covered by a service's signing.** A `ForwardedIdentity` block on a service signs the requests forwarded to that service and nothing else. Until the tenant-list call is signed on its own, any caller that can reach the endpoint can write the identity headers and list another person's tenants. Do both of the following:
|
|
135
|
+
|
|
136
|
+
1. Sign the call. Put a `ForwardedIdentity` block in the `Selection` options and verify it in the endpoint:
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{
|
|
140
|
+
"Strategy": "Selection",
|
|
141
|
+
"Options": {
|
|
142
|
+
"TenantsEndpoint": "https://platform.example.com/api/tenants/selectable",
|
|
143
|
+
"ForwardedIdentity": { "Audience": "tenant-directory", "KeyId": "tenants-2026-01" }
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Supply `SecretBase64` (32 random bytes, base64) from a secret store: `Cratis__AuthProxy__TenantResolutions__<index>__Options__ForwardedIdentity__SecretBase64`, where `<index>` is the position of the `Selection` entry.
|
|
149
|
+
2. Make the endpoint reachable from the proxy only, like the rest of the backend. See [operations.md](operations.md).
|
|
150
|
+
|
|
151
|
+
- Give the tenant list its own `Audience`, `KeyId` and secret. The one exception: an endpoint under the `Backend:BaseUrl` of a signed service may repeat that service's `Audience`, `KeyId` and secret exactly.
|
|
152
|
+
- A signed tenant-list call needs an `https://` endpoint and the proxy's client certificate, as every signed hop does. See [operations.md](operations.md).
|
|
153
|
+
- A call the proxy cannot sign is not sent unsigned. It counts as an endpoint that cannot answer.
|
|
154
|
+
- At startup the proxy logs each flow as signed or not signed. Check that the tenant-list row says signed; a signed service does not imply it.
|
|
155
|
+
- Under Aspire, the `WithSelectionTenantResolution` overload that takes a resource signs the call when that backend is paired. See [aspire.md](aspire.md).
|
|
156
|
+
|
|
157
|
+
For verifying the signature in an Arc backend see `cratis-arc-host-application` (identity reference).
|
|
158
|
+
|
|
159
|
+
### Confirmation and removed access
|
|
160
|
+
|
|
161
|
+
The selected tenant is stored in `.cratis-tenant`, a protected cookie tied to the account that selected it. The proxy does not trust it for the whole session. It confirms the selection against `TenantsEndpoint` when `Session:TenantRevalidationInterval` (default 10 minutes) has lapsed, and remembers a successful confirmation in memory for that long.
|
|
162
|
+
|
|
163
|
+
| At confirmation the endpoint | Result |
|
|
164
|
+
|---|---|
|
|
165
|
+
| Lists the selected tenant | The request proceeds. The next confirmation is one interval away. |
|
|
166
|
+
| Answers without the selected tenant (another list, an empty list, `401` or `403`) | The proxy deletes `.cratis-tenant` and `.cratis-tenants` and redirects to the same URL, so the person selects again or gets the no-tenant response. |
|
|
167
|
+
| Cannot answer | `503`. Both cookies are kept and the tenant is not forwarded until the endpoint confirms it. Anonymous, invitation and registration paths proceed without a tenant. |
|
|
168
|
+
|
|
169
|
+
- Removed access takes effect within one interval, not on the next request. Lower `TenantRevalidationInterval` to shorten the delay; each confirmation is one call to the endpoint per person and replica.
|
|
170
|
+
- An outage of the endpoint therefore stops tenant-scoped requests within one interval. Keep the endpoint as available as sign-in itself.
|
|
171
|
+
- Zero or a negative interval turns the periodic confirmation off: a selection is trusted until the person changes it. Use it only when access to a tenant is never removed during a session.
|
|
172
|
+
- When a `Host`, `SubHost` or `Route` strategy addresses the tenant and `Selection` is also configured, the addressed tenant is confirmed the same way. A person who is not in it gets `403`.
|
|
173
|
+
|
|
174
|
+
### In-app tenant switcher
|
|
175
|
+
|
|
176
|
+
For a person with more than one tenant the proxy keeps a `.cratis-tenants` cookie: a URL-encoded JSON array of `{ id, name }` that script on the page can read.
|
|
123
177
|
|
|
124
178
|
1. Show the switcher only when the cookie lists more than one tenant. A person with one tenant never gets the cookie.
|
|
125
179
|
2. Switch by navigating the browser to `/.cratis/select-tenant?tenantId=<id>&returnUrl=<current path>`.
|
|
126
180
|
|
|
127
|
-
Every switch is
|
|
181
|
+
- The cookie is a display list, not a grant. Every switch is checked against `TenantsEndpoint`, so a stale entry cannot give access to a tenant the person has left.
|
|
182
|
+
- The proxy deletes the cookie when a confirmation finds the selected tenant gone. Do not cache its content in the frontend.
|
|
128
183
|
|
|
129
184
|
## Anti-patterns
|
|
130
185
|
|
|
131
186
|
- Sending `x-cratis-tenant-id` from the frontend to switch tenant. The proxy removes it. Navigate to `/.cratis/select-tenant`.
|
|
132
187
|
- `SubHost` without tenant verification. Any subdomain then becomes a tenant id.
|
|
133
188
|
- Treating tenant verification as a membership check.
|
|
189
|
+
- Answering the tenant list with `[]` when the membership store is down. Answer `5xx`.
|
|
190
|
+
- Relying on a service's `ForwardedIdentity` block to protect `TenantsEndpoint`. Sign the tenant-list call in the `Selection` options.
|
|
134
191
|
- Putting `Default` or `Specified` before another strategy. They always resolve, so nothing after them runs.
|
|
135
192
|
- Configuring tenant selection in the backend as well. Keep Arc's default header selector and choose the strategy in the proxy only.
|
|
@@ -122,6 +122,6 @@ These commands outside `cratis chronicle` set the target, set up the tool and co
|
|
|
122
122
|
- **Reading results:** [Inspection results](references/inspection.md) covers output formats, every exit code, which command answers which question, and the `diagnose` readiness gate.
|
|
123
123
|
- **Release gate or model comparison:** [Recovery outcomes and comparison](references/recovery-and-comparison.md) covers `check-release` before a deploy and the read-only Screenplay namespace comparison after one.
|
|
124
124
|
- **Authorized recovery:** Check [command effects and write preflight](references/command-effects.md#preflight-for-a-write), then [recovery outcomes](references/recovery-and-comparison.md) for the exact operation. A diagnosis request does not authorize changes. Re-read after an accepted request and verify the actual outcome.
|
|
125
|
-
- **CLI upgrades, templates and managed AI installation:** [Project tooling](references/project-tooling.md) covers what `cratis update` changes and leaves alone, `cratis ai install`/`update` in unattended setups and pinning a reviewed corpus revision.
|
|
125
|
+
- **CLI upgrades, templates and managed AI installation:** [Project tooling](references/project-tooling.md) covers what `cratis update` changes and leaves alone, running `cratis new` unattended (template version, JSON result, step outcomes), `cratis ai install`/`update` in unattended setups and pinning a reviewed corpus revision.
|
|
126
126
|
|
|
127
127
|
Leave mutating interactive keys in the terminal Workbench to an operator.
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
## Contents
|
|
7
7
|
|
|
8
8
|
- Inspect the upgrade, not a remembered bundle
|
|
9
|
+
- `cratis new` in CI and scripts
|
|
9
10
|
- Managed AI installation and MCP
|
|
10
11
|
- Deterministic AI checks versus harness behavior
|
|
11
12
|
|
|
@@ -51,15 +52,63 @@ What `cratis update` changes beyond the CLI and the templates, and what it leave
|
|
|
51
52
|
`cratis version` from the executable you intend to use.
|
|
52
53
|
- **Existing applications.** Newer templates change the default set that the
|
|
53
54
|
next `cratis new` uses. When `cratis new` acquires a template package, its
|
|
54
|
-
`--version` overrides that pin
|
|
55
|
-
|
|
56
|
-
templates never change an application
|
|
55
|
+
`--version` overrides that pin for one run; `--template-path` uses the local
|
|
56
|
+
package and bypasses package selection altogether. `--version '*'` is not
|
|
57
|
+
"latest": see the next section. Newer templates never change an application
|
|
58
|
+
that is already scaffolded.
|
|
57
59
|
- **Installed AI guidance.** It does not touch a Cratis-managed AI corpus
|
|
58
60
|
installation in a repository. Run `cratis ai update` from each directory that
|
|
59
61
|
contains `.cratis/ai.json`; it does not search parent directories, so from a
|
|
60
62
|
subdirectory, or without that file, the command fails and asks for
|
|
61
63
|
`cratis ai install`. What `cratis init` wrote is not such an installation.
|
|
62
64
|
|
|
65
|
+
## `cratis new` in CI and scripts
|
|
66
|
+
|
|
67
|
+
Creating an application is owned by `cratis-platform-start-application`; this
|
|
68
|
+
section holds what an unattended run must get right.
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
cratis new cratis --language csharp -n <Name> -o <directory> \
|
|
72
|
+
--version <version> --allow-scripts yes --no-prompts --format json
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- **Pin the template version.** Pass an exact `--version` for a reproducible
|
|
76
|
+
job. `--version '*'` selects the newest stable template package already in the
|
|
77
|
+
local template cache and does not contact the feed; the feed is asked only
|
|
78
|
+
when no stable version is cached. On a runner with a restored or shared cache
|
|
79
|
+
it therefore keeps returning an old version. Run `cratis update` first when
|
|
80
|
+
the job must move to a newer set, then record the version it used. Quote `*`
|
|
81
|
+
so the shell does not expand it.
|
|
82
|
+
- **`-o` is the output directory on this command**, not the output format as
|
|
83
|
+
elsewhere in the CLI. `--format json` selects the JSON result. Creation prints
|
|
84
|
+
the same human-readable summary for `table` (the default) and `plain`, with
|
|
85
|
+
no tab-separated form: a script reads the result with `--format json` only.
|
|
86
|
+
- **Pass `--no-prompts`** so the run takes given values and defaults whatever
|
|
87
|
+
the terminal state, and name `--language`: without a template and a language
|
|
88
|
+
the command is the wizard, which cannot run unattended.
|
|
89
|
+
- **Choose the script policy.** Frontend dependencies are installed by a script
|
|
90
|
+
step, and `--allow-scripts` defaults to `no`, which declines it. `prompt` is
|
|
91
|
+
an error without a terminal.
|
|
92
|
+
- **Exit 0 does not prove every step ran.** A declined script, a step that
|
|
93
|
+
could not be performed and a failed step the template marks
|
|
94
|
+
`continueOnError` all leave the exit code at 0. Exit 1 means a post-action
|
|
95
|
+
the template does not mark `continueOnError` ended `failed` or `unknown`: the
|
|
96
|
+
files are written, so read the result before retrying. Exit 2 means nothing
|
|
97
|
+
was created (unknown template, template acquisition, an invalid manifest or
|
|
98
|
+
template parameters). Exit 5 means an option value was rejected before
|
|
99
|
+
anything ran: a missing or unsupported `--language`, an invalid
|
|
100
|
+
`--database`, `--format` or `--allow-scripts` value, or `--template-path`
|
|
101
|
+
combined with `--package`. Read `postActions` in the JSON: each entry has `description`,
|
|
102
|
+
`outcome`, `message`, `instructions` and `continueOnError`. Accept
|
|
103
|
+
`succeeded`, `skipped` (its condition was false, or the run was a dry run:
|
|
104
|
+
check the top-level `dryRun` before treating the scaffold as written) and
|
|
105
|
+
`displayed`; treat
|
|
106
|
+
`denied`, `notperformed`, `failed` and `unknown` as work the job still has to
|
|
107
|
+
do or report. `aiUpdate.status` (`updated`, `skipped`, `conflicts` or
|
|
108
|
+
`failed`) never changes the exit code: check it too. Then inspect the
|
|
109
|
+
generated project for a floating package version before building on it
|
|
110
|
+
(`cratis-platform-upgrade-application`).
|
|
111
|
+
|
|
63
112
|
For `cratis render` / `run`, use the `cratis-stage-render-slice` skill. The bundled renderer determines support;
|
|
64
113
|
a CLI upgrade can change admission, generated output and the default container
|
|
65
114
|
without changing the model. Never infer support from the ESM version alone or
|
|
@@ -59,7 +59,7 @@ Below, `With…` options are in `chronicle` and are passed to `Dial` or `NewClie
|
|
|
59
59
|
- `WithDefaultConcurrencyStrategy(strategy)` replaces automatic optimistic scope selection; explicit scopes bypass it. `WithCheckFirstAppendIntoAScope(true)` protects competing first writes in empty resolved scopes, not explicit unchecked appends.
|
|
60
60
|
- `WithIdentityProvider(actor)`, `WithCorrelationProvider(correlation)` and `WithCausationProvider(chain)` supply actor, correlation and full causation from application context. Handled provider values override context; explicit append correlation bypasses the provider. `WithRootCausation(metadata.RootCausation{ProgramIdentifier:"yard-worker", SoftwareVersion:build, SoftwareCommit:revision})` captures root attribution once; existing upstream roots win. Machine name and process ID are separate opt-ins.
|
|
61
61
|
- `WithEventEnrichers(first, second)` runs borrowed enrichers in order. `WithAppendOriginResolver(resolve)` selects local immediate-append attribution; unit commits bypass it. Providers must support concurrent synchronous calls.
|
|
62
|
-
- `WithLogger(logger)` borrows a `*slog.Logger` instead of the captured `slog.Default()`. `WithGRPCStatsHandler(handler)` instruments every owned generation, not a borrowed channel; owner flushes exporters. `WithOnConnected(onUp)` and `WithOnDisconnected(onDown)` receive `func(context.Context, chronicle.ConnectionEvent)` notifications, not registration receipts.
|
|
62
|
+
- `WithLogger(logger)` borrows a `*slog.Logger` instead of the captured `slog.Default()`. `WithGRPCStatsHandler(handler)` instruments every owned generation, not a borrowed channel; owner flushes exporters. `WithOnConnected(onUp)` and `WithOnDisconnected(onDown)` receive `func(context.Context, chronicle.ConnectionEvent)` notifications, not registration receipts. Never gate readiness, start-up or health on a hook: Connected means the protocol session is ready, not that artifacts are registered or observers attached, and a hook can be skipped. When a connection ends before its Connected hooks start, both its Connected and Disconnected notifications are dropped, so a counter or flag driven by hooks can miss a connection. Every delivered Connected does get exactly one Disconnected. Hooks run on the client's own dispatcher, never on the caller's goroutine. Connecting, reconnecting, RPCs and `Ready` do not wait for them. Two things do: the dispatcher runs one notification's hooks concurrently and waits for all of them before it delivers the next notification, so a slow hook delays every later one; and `Close` and `Shutdown` wait for running hooks to return (`CloseContext(ctx)` bounds that wait). Never call `Close` or `Shutdown` from a hook: it waits for the hook it is running in. Signal another goroutine to close the client instead, and keep hooks short. Wait on `c.Ready(ctx)` or a store handle's `s.WaitForRegistration(ctx)` instead.
|
|
63
63
|
|
|
64
64
|
## Errors to react to
|
|
65
65
|
|
|
@@ -72,7 +72,7 @@ Pass these as the second argument of `ChronicleOptions.fromConnectionString(uri,
|
|
|
72
72
|
- **Naming:** `readModelNamingPolicy: identifier => identifier.toLowerCase()` changes read-model names, not event field serialization; the callback also receives the optional model type.
|
|
73
73
|
- **Concurrency:** `concurrencyScopeStrategy: ConcurrencyScopeStrategies.none` (enum from `@cratis/chronicle`) disables the default optimistic scope. Alternatively supply a sync/async callback returning a scope or `undefined` for no check. Explicit scopes bypass it; callback failure prevents the append.
|
|
74
74
|
- **Enrichment:** `eventEnrichmentProviders: [(content, ctx) => { content.partition = ctx.namespace; }]` sets a declared cross-cutting field on serialized content, not on `ctx.event`. Providers may be async; the default list is empty.
|
|
75
|
-
- **Reactor results:** `reactorResultHandler: (result, ctx, type, storeName, ns) => handleEffect(result, ctx, type, storeName, ns)` returns true only for a fully handled result; throw on failure. `readModelReactorResultHandler` receives `(result, changeset, type, store, ns)` instead. Set `readModelReactorOnError: (error, changeset, type) => reportFailure(error, changeset, type)` for non-terminal activation, handler or effect failures; reporting does not retry.
|
|
75
|
+
- **Reactor results:** `reactorResultHandler: (result, ctx, type, storeName, ns) => handleEffect(result, ctx, type, storeName, ns)` returns true only for a fully handled result; throw on failure. In an Arc application that passes its own client to `withChronicle`, this option must be `reactorCommandResultHandler(() => app.server, '<event store>')` from `@cratis/arc.chronicle`, or commands returned by reactors are silently not executed; Arc never changes a caller-owned client. See `cratis-arc-invoke-command`. `readModelReactorResultHandler` receives `(result, changeset, type, store, ns)` instead. Set `readModelReactorOnError: (error, changeset, type) => reportFailure(error, changeset, type)` for non-terminal activation, handler or effect failures; reporting does not retry.
|
|
76
76
|
- **Diagnostics:** `logger: { log: entry => applicationLog(entry) }` routes the client's own diagnostics to the application logger; each client has its own sink and `log` is called synchronously. An entry has `category`, `level` (`Verbose`, `Debug`, `Info`, `Warn`, `Error`), `message` and `attributes`. Entries are sanitized: a failure appears as its error type (attribute `error.type`) and, for gRPC, `rpc.grpc.status_code`; exception messages, stacks and event payloads are left out, so the text is only on the errors your own code catches. Do not log those verbatim: a caught error can contain the authorization server's raw response body, because a token request answered with an error status puts that body in its message and a call the kernel then rejects as unauthenticated can repeat it. Inspect them privately and log only the type, the status code and a redacted message. The sink should not throw; a failing sink does not change call results or acknowledgements. Without `logger` the entries go to OpenTelemetry `diag`, which discards them until the application calls `diag.setLogger(...)`; use one of the two paths, not both. Built-in telemetry uses convention span names; `telemetry.spanNames` accepts `legacy`/`convention` but neither changes naming. Source IDs are omitted by default; `telemetry: { eventSourceId: { mode: 'hmac', key: deploymentKey } }` uses SHA-256 with a nonempty `Uint8Array`. Select `raw` only if exposing identifiers is intended.
|
|
77
77
|
|
|
78
78
|
## Behavior patterns
|
|
@@ -31,7 +31,7 @@ A read model has exactly one builder: one projection or one reducer.
|
|
|
31
31
|
- **Asynchronous and eventually consistent.** An append can succeed while the stored view still shows the previous state. A successful append is never proof that the read model shows the change. To read your own change, wait for observer completion on the append result and check the completion outcome, or watch for the expected change. Waiting does not make append and query atomic.
|
|
32
32
|
- **Ordered per key, retried on failure.** Events are handled in order within a partition. A failing event is retried and can be delivered again; when retries are exhausted the partition stops until it is attended to, and its instances lag.
|
|
33
33
|
- **Persisted (default).** Instances are materialized in a sink: the document sink (MongoDB) by default, the graph sink (Neo4j) for graphs. SQL and other named sinks are set up on the kernel; a read model opts in where its SDK allows.
|
|
34
|
-
- **Passive.** No sink. Each read replays the stream whose event source id equals the requested key. The result
|
|
34
|
+
- **Passive.** No sink. Each read replays the stream whose event source id equals the requested key. The result reflects revisions, redactions and erased personal data. Never combine passive with a redirected key, a join or events from other sources: the fold can miss the creation, and a join misses joined events appended later. A passive read is not a protected command decision.
|
|
35
35
|
- **Input is chosen by event type.** A projection receives every event of the types its mappings name, from every event source in its one selected sequence (the event log unless the SDK infers or you pick another; see your language reference); each event lands on the instance its key selects. Tags, event source type and stream type on an append do not narrow it: use a reducer or reactor when only a subset may count. Several event types can feed one model; a property an event does not carry is left unchanged.
|
|
36
36
|
- **Replay rebuilds from history.** The sequence is handled again from the start; the rebuilt state is incomplete until the replay finishes. Replay does not undo anything outside the sink.
|
|
37
37
|
- **Identity.** The projection id is a deployed identity. Keep the previous id when renaming or moving a type; a new id is a new projection.
|
|
@@ -87,7 +87,13 @@ Label a projection or read model with `[Cratis.Chronicle.Tag("shipping")]` or `[
|
|
|
87
87
|
|
|
88
88
|
For an active typed projection that must handle a specific event generation, set `options.EventGenerationDelivery = Cratis.Chronicle.Observation.EventGenerationDelivery.Pinned` in the client options and map the CLR event type for that generation. All clauses must agree on one generation per event type. Compatibility delivery is the default; passive and wildcard definitions retain it.
|
|
89
89
|
|
|
90
|
-
A passive read
|
|
90
|
+
A passive read folds only the events of the event source whose id equals the requested key; registration and specs still pass when the declaration needs more than that. Do not combine `[Passive]` with:
|
|
91
|
+
|
|
92
|
+
- **A redirected root key (`key:`, `UsingKey`):** a read by the redirected key reaches no events and returns an empty result, not an error.
|
|
93
|
+
- **A join:** the joined event belongs to another event source, so the fold never reads it as an event of its own. The joined values are looked up only when one of the requested source's events sets the joined property, and only from the latest joined event appended before that event. A joined event appended after the last such event is not applied. The result therefore depends on append order: complete in one order, joined properties left at their defaults in the other, and a later change to the joined source does not show.
|
|
94
|
+
- **Events from other sources:** they are not read.
|
|
95
|
+
|
|
96
|
+
Materialise such a view instead. `[Passive]` alone does not make a type a projection; it needs at least one mapping attribute. `[Projection(eventSequence: ...)]` configures fluent projections only; a model-bound read model uses `[EventSequence]`. `[Passive]` together with `[Sink]` is an analyzer error, because a passive read model has no sink.
|
|
91
97
|
|
|
92
98
|
Chronicle has no synchronous projection: an append does not wait for a stored read model to be updated, so a read made right after it may still return the earlier state, and "immediate projection" means a passive read, computed from events at read time. To decide how a caller reads its own write, see `references/eventual-consistency.md` in `cratis-platform-deliver-slice`.
|
|
93
99
|
|
|
@@ -85,6 +85,8 @@ Cratis has no saga or process-manager building block. Build a multi-step process
|
|
|
85
85
|
| Waits for a person, another fact or a deadline | The same chain with a work-list item that stays open while the process waits. The wait is not code: the next step is a reactor for the fact that ends the wait, such as the approval, the answer or the recorded expiry. A reactor never waits itself. |
|
|
86
86
|
| One entity's lifecycle | A status on the entity's read model, built from its facts (`cratis-chronicle-project-view`). Commands decide from the entity's facts, not from that status. |
|
|
87
87
|
|
|
88
|
+
**Outcome after the effect.** When a step calls an external system, the reactor makes the call first and returns the outcome fact only after the call is confirmed. Never append the outcome fact before the call or from the command that requested it: nothing rolls it back when the call fails, and every reader then sees an outcome that did not happen. A failed or unconfirmed call fails the handler, so the step is redelivered; make the call idempotent with the delivery identity. Record a refusal the external system confirms as its own fact, not as a handler failure.
|
|
89
|
+
|
|
88
90
|
**No rollback across steps.** Each step commits on its own, and nothing spans a reactor's returned events and commands, several returned commands, or several steps. A failed step is redelivered, so first make each step safe to repeat and let a transient failure retry. Compensate only when the domain decides to reverse completed work: record that decision as a fact and issue a compensating command for each completed step it reverses. Chronicle does not prevent a duplicate compensation, so make each one safe to repeat. Keep the item on the work list until a completion or cancellation fact removes it. Never delete or redact events to undo a step.
|
|
89
91
|
|
|
90
92
|
**Order.** Each handler method sees its events in order within one event source. Two methods of the same reactor are not ordered relative to each other, even for the same event source: a batch method and a per-event method each keep only their own order. When two effects must happen in a set order, handle them in one method. Order does not hold across event sources or between observers: a reactor can handle a fact before a projection has stored it, and the reverse. When logic needs the facts of two entities in order, put them on one event source or carry the needed data on the later event. Limiting partition concurrency protects a downstream system; it does not create a global order. With several instances of a service connected, keep the kernel's default fan-out, which keeps each event source on one instance while the set of connected instances is unchanged. Scaling or a reconnect can move an event source to another instance, so do not hold per-source state in instance memory.
|
|
@@ -65,7 +65,7 @@ return [new ParcelIndexed(), { eventSourceId: sortingHub, event: new HubNotified
|
|
|
65
65
|
subject: context.eventSourceId, eventStreamId: shiftId, eventStreamType: 'Shift', eventSourceType: 'Hub' }];
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
-
Wrappers pass through rather than merging bare-event defaults. Return nothing for no append; unrecognized objects are ignored. Append failure fails processing. For an application contract configure `reactorResultHandler` in client options, e.g. `async (result, context) => { if (!(result instanceof IssueNotice)) return false; await issueNotice(result, context); return true; }`. It runs before event interpretation and claims the **whole** result; it can also receive reactor type, store and namespace. For command decisions use the integration in `cratis-arc-invoke-command` rather than treating commands as facts.
|
|
68
|
+
Wrappers pass through rather than merging bare-event defaults. Return nothing for no append; unrecognized objects are ignored. Append failure fails processing. For an application contract configure `reactorResultHandler` in client options, e.g. `async (result, context) => { if (!(result instanceof IssueNotice)) return false; await issueNotice(result, context); return true; }`. It runs before event interpretation and claims the **whole** result; it can also receive reactor type, store and namespace. For command decisions use the integration in `cratis-arc-invoke-command` rather than treating commands as facts. An Arc-owned connection (`withChronicle` with a connection string) executes returned Arc commands by itself. A client you construct yourself and pass to `withChronicle` does not: nothing fails, the returned commands are just never executed. Set `reactorResultHandler: reactorCommandResultHandler(() => app.server, '<event store>')` (from `@cratis/arc.chronicle`) in the options the client is created with, before it connects.
|
|
69
69
|
|
|
70
70
|
## Process a page and recover
|
|
71
71
|
|
|
@@ -34,6 +34,7 @@ Catch-up, retry and replay must compute the same result from the same history. U
|
|
|
34
34
|
- **Separate reducer:** keep transitions on a separate artifact for shared model contracts or when an instance is needed.
|
|
35
35
|
- **Registration:** use normal SDK discovery or typed registration; explicitly nominate artifacts in discovery-free hosts.
|
|
36
36
|
- **Observer ID:** specify a durable ID to preserve progress across a rename or move.
|
|
37
|
+
- **Changing between projection and reducer:** not a migration. Events, the model's shape and its queries can stay, but reusing the model's identity under the other kind neither converts nor reliably rebuilds the stored instances. Remove the previous producer so the model has one, stop the old writer before starting the new one, then request an explicit replay and verify it: the job completed, and stored state, query results and personal-data protection match the same history.
|
|
37
38
|
- **Sequence:** select a named event sequence when the input is not the event log.
|
|
38
39
|
- **Source store:** route a foreign store's subscribed events through its inbox; do not also select an unrelated sequence.
|
|
39
40
|
- **Active flag:** disable continuous maintenance when the client should register the definition but not keep a sink current.
|
|
@@ -44,6 +44,7 @@ in the findings that matter:
|
|
|
44
44
|
| A focused Chronicle, database, backend or frontend scalability analysis | `cratis-performance-review`; the performance items here are only those visible in passing, so do not duplicate its findings when both ran |
|
|
45
45
|
| Scheduling review passes, rounds and re-reviews | `cratis-engineering-review-rounds` |
|
|
46
46
|
| Reviewing the model itself | `cratis-modeling-review-event-model` |
|
|
47
|
+
| The change raises or pins Cratis packages, tools or images | Also read `cratis-platform-upgrade-application` for version pairing, pinning and upgrade order, and `cratis-components-theme-application` (`references/upgrade-from-previous-major.md`) when it crosses the Components major that left PrimeReact |
|
|
47
48
|
|
|
48
49
|
## How gates and review divide the work
|
|
49
50
|
|
|
@@ -96,7 +96,7 @@ Neutral guidance:
|
|
|
96
96
|
- **Tooltip** — wraps exactly one focusable element; shows non-interactive `content` on hover and keyboard focus. `position` (`top`, `right`, `bottom`, `left`), `disabled` (suppresses it), `className` (on the trigger element). Empty, `null` or boolean content also disables it.
|
|
97
97
|
- **ActionMenubar** — flat toolbar of page actions. `model` items (`label`, also the name; `icon`, `command`, `disabled`, `className`, `severity` as tone, `template` replaces rendering), `focusMode` `ToolbarFocusMode.Arrows` (default), `SingleTabStop`, `None` (native focus only), `aria-label` (no default), `className`, `pt` (applied to every action button). Ignored: `ptOptions`, `unstyled`.
|
|
98
98
|
- **Breadcrumbs** — route trail, outermost first. `items` (`label`, `href`; do not write the legacy `onNavigate`, which runs in addition to `href`), `separator` (decorative; slash by default), `aria-label` (name it when a page has several trails), `className`, `pt` (`root`, `item`, `link`, `separator`; class, style, title and data attributes only). The last item is the current page and never navigates; routing comes from the provider.
|
|
99
|
-
- **Page** — root of a routed view: full-height column
|
|
99
|
+
- **Page** — root of a routed view: full-height column whose `main` clips overflow; scroll in a child. `title` (required; an `h1` only with `showTitle`; set the browser tab title yourself), `showTitle`, `landmark` (on; off renders a `div`), `panel` (adds an unstyled `panel` class), `div` attributes.
|
|
100
100
|
- **Surface** — non-interactive semantic region. `as` (`div` default, `section`, `article`), HTML attributes, `pt`, element ref.
|
|
101
101
|
- **FormElement** — leading icon beside an input you own. `icon` and children required; holds no value, names nothing.
|
|
102
102
|
- **ErrorBoundary** — isolates render failures of a section. `fallback`: content, or a function of `reset` returning content (`null` renders nothing); `onError` (error and info; replaces console reporting), `onReset` (synchronous, before retry). Retry remounts the children, losing local state. Not caught: event handlers, async work, server rendering, its own fallback.
|
package/package/corpus/skills/cratis-components-choose-control/references/typescript-common.md
CHANGED
|
@@ -43,7 +43,7 @@ Import everything named here from `@cratis/components/Common` unless stated. "Na
|
|
|
43
43
|
|
|
44
44
|
## Structure and icons
|
|
45
45
|
|
|
46
|
-
- `Page`: native `div` attributes plus required `title: string`, `showTitle?`, `landmark?`, `panel?`; no ref.
|
|
46
|
+
- `Page`: native `div` attributes plus required `title: string`, `showTitle?`, `landmark?`, `panel?`; no ref. The root and the content region are flex columns with `height: 100%` and `flex: 1`, and the content region (`main`) has `overflow: hidden`. Content taller than the view is clipped, not scrolled, and the page itself never scrolls. Put the scrolling element inside: a child with `flex: 1`, `min-height: 0` and `overflow: auto`. The ancestors need a definite height for `Page` to fill; without one the page grows with its content and nothing is clipped. `className` is added to the root after the layout classes; `style` and the other attributes also land on the root, not on `main`.
|
|
47
47
|
- `Surface`: HTML attributes plus `as?: SurfaceElement` (`'div' | 'section' | 'article'`); ref `HTMLElement`.
|
|
48
48
|
- `FormElement`: required `icon: ReactNode` and `children: ReactNode`.
|
|
49
49
|
- `ErrorBoundary`: required `children`; `fallback?: ReactNode | ((reset: () => void) => ReactNode)`; `onError?: (error: unknown, errorInfo: ErrorInfo) => void`; `onReset?: () => void`.
|
|
@@ -116,7 +116,7 @@ Every form option, plus: `title` (required); `subtitle`; `okLabel`, `cancelLabel
|
|
|
116
116
|
|
|
117
117
|
- **Shared step options:** `linear` (default on), `orientation` (`horizontal` default or `vertical`), `headerPosition` (`top` default or `bottom`), `start`, `end`, `onChangeStep` (zero-based `index`), `pt`; plus `onBeforeExecute` and `confirmBeforeExecute`.
|
|
118
118
|
- **`StepperPanel`:** `header` and the step's fields.
|
|
119
|
-
- **`CommandStepper`:** every form option, plus `showNavigation`, `showSubmit` (both default on), `nextLabel`, `previousLabel`, `okLabel`, `isBusy` (
|
|
119
|
+
- **`CommandStepper`:** every form option, plus `showNavigation`, `showSubmit` (both default on), `nextLabel`, `previousLabel`, `okLabel`, `isBusy` (host work: disables Previous, Next and Submit only, not headers or fields), `onStepErrorsChange` (per-step error flags).
|
|
120
120
|
- **`StepperCommandDialog`:** every form option, plus `title` (required), `okLabel`, `nextLabel`, `previousLabel`, `showCancel`, `cancelLabel`, `onConfirm`, `onCancel`, `onClose`, `isValid`, `visible`, `width` (default 600px), `style`, `contentStyle`, `headerActions`, `hideGlobalHeaderActions`, `sliceLocation`, and `dialogClassName`, `dialogPt` to style the outer dialog.
|
|
121
121
|
|
|
122
122
|
### Fields
|
|
@@ -130,7 +130,7 @@ Seventeen fields, by bound type: text (`InputTextField`, `TextAreaField`, `Passw
|
|
|
130
130
|
- **`AutoCommandForm`:** every form option plus `exclude` and `footer` (put the submit button there). Strings get `InputTextField`, numbers `NumberField`, booleans `CheckboxField`, dates `CalendarField`; other types (nested objects, arrays) get no field. Titles come from property names (`dueDate` → "Due Date"). `exclude` hides only the editor: seed an excluded or unprovided non-optional property through `initialValues`.
|
|
131
131
|
- **`AutoCommandFields`:** generated fields inside an existing `CommandForm` or `CommandDialog`; `exclude`, `currentValues`. Not inside steppers.
|
|
132
132
|
- **`registerFieldTypeProvider`:** add a provider (`canHandle` over the property descriptor, `component`); newest wins, so it overrides a default. `GuidField` is opt-in this way. `resolveFieldTypeProvider` looks one up; `clearFieldTypeProviders` is for specs only.
|
|
133
|
-
- **`CommandForm.Column`:**
|
|
133
|
+
- **`CommandForm.Column`:** as direct children of the form, columns sit side by side only with PrimeFlex-style utility CSS loaded; anywhere else, place them in your own grid or flex container.
|
|
134
134
|
- **`ValidationSummary`, `ValidationMessage`:** render results no field claims, or one property's message, where you place them.
|
|
135
135
|
- **`useCommandInstance`, `useCommandFormContext`, `useIsCommandExecuting`, `useSetCommandResult`:** from a child, read the instance, state and busy flag, or publish a result. Context operations: `setCommandValues` writes the given keys without re-validating (drive `currentValues` when validity must follow); `setCustomFieldError` blocks submission until cleared with an empty value; `validation` reports per channel (client, server) whether a verdict is pending, `current`, `stale` or `unvalidated` and `valid`, `invalid` or `error`; trust `isValid` only from a current, non-pending verdict, and only as a preflight.
|
|
136
136
|
- **`asCommandFormField`:** turn a controlled component into a bound field (`defaultValue`, `extractValue`, `groupRole` for multi-input groups). `withCommandFormFieldBinding` (already applied by `asCommandFormField`) lets a hand-marked field bind behind an opaque component; `markAsCommandFormField`, `markAsCommandFormColumn`, `isCommandFormField`, `isCommandFormColumn` mark or recognize hand-rolled fields and columns.
|
package/package/corpus/skills/cratis-components-submit-form/references/typescript-commanddialog.md
CHANGED
|
@@ -105,7 +105,7 @@ Step rules:
|
|
|
105
105
|
- Next (or a header, with `linear` off) is refused while the current step shows field errors. These are displayed errors, not missing values: under blur validation an untouched blank field does not block it, unless `validateOnInit` is set.
|
|
106
106
|
- Moving back is always allowed. With `linear` (the default) headers are not clickable. `onChangeStep` reports an accepted move.
|
|
107
107
|
- `StepperCommandDialog` hides Submit until the last step and a valid form, and offers no footer Cancel unless `showCancel` is set.
|
|
108
|
-
- `CommandStepper` shows Submit on the last step, disabled while the form is invalid or busy, or while any step shows field errors. On `CommandStepper`, `showNavigation={false}` hides the whole built-in footer, Submit included, and `showSubmit={false}` hides only Submit; labels fall back to the provider's stepper messages.
|
|
108
|
+
- `CommandStepper` shows Submit on the last step, disabled while the form is invalid or busy, or while any step shows field errors. While `onBeforeExecute`, confirmation or the command is pending, Next and Submit are disabled and Submit shows a spinner; Previous stays enabled. `isBusy` is for work the page owns: it disables Previous, Next and Submit and sets `data-busy` on the stepper parts. It does not disable step headers (clickable with `linear={false}`) or the fields, and shows no spinner. To lock the fields during host work, disable them yourself, for example with a `<fieldset disabled>` around the fields inside each panel. On `CommandStepper`, `showNavigation={false}` hides the whole built-in footer, Submit included, and `showSubmit={false}` hides only Submit; labels fall back to the provider's stepper messages.
|
|
109
109
|
|
|
110
110
|
## Stepper layout and styling
|
|
111
111
|
|
|
@@ -152,7 +152,7 @@ Conditional rendering gives a fresh form per opening; keeping it mounted and tog
|
|
|
152
152
|
|
|
153
153
|
## Layout, footer and announcements
|
|
154
154
|
|
|
155
|
-
- **Columns:** wrap fields in `CommandDialog.Column`
|
|
155
|
+
- **Columns:** wrap fields in `CommandDialog.Column` inside your own grid or flex container. In a dialog a column is only a vertical stack of its fields; the form's automatic side-by-side row applies to direct children of `CommandForm` alone. Fields inside still bind.
|
|
156
156
|
- **Footer:** `buttons={DialogButtons.YesNo}` relabels the predefined footer; custom footer content does not run the command, and `buttons={null}` removes it. Both custom and no footer turn off X, Escape and backdrop dismissal unless you set `dismissable`.
|
|
157
157
|
- **Validation announcement (`CommandDialog` only; the steppers have no such option):** `validationAnnouncement={results => …}` receives the refused validation results and returns the text a screen reader announces when an execution is refused for validation; the built-in text is English.
|
|
158
158
|
- **Values from the caller:** use `initialValues` for seeds and `currentValues` for a reactive overlay; `AutoCommandFields` inside a `CommandDialog` follows the dialog's own `currentValues`.
|
package/package/corpus/skills/cratis-components-submit-form/references/typescript-commandform.md
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
## Contents
|
|
4
4
|
|
|
5
5
|
- Edit form on a page
|
|
6
|
+
- Columns
|
|
6
7
|
- Submit from outside the form
|
|
7
8
|
- The execute() result
|
|
8
9
|
- Inside the form
|
|
@@ -28,7 +29,16 @@ Populate from a **single-item** query whose properties match the command by name
|
|
|
28
29
|
</CommandForm>
|
|
29
30
|
```
|
|
30
31
|
|
|
31
|
-
`
|
|
32
|
+
`onBeforeExecute` is synchronous here: mutate and return the instance, never a spread copy.
|
|
33
|
+
|
|
34
|
+
## Columns
|
|
35
|
+
|
|
36
|
+
How `CommandForm.Column` is laid out depends on where it sits.
|
|
37
|
+
|
|
38
|
+
- **Direct child of the form.** As soon as one direct child is a column, the form wraps all its children in one row with the classes `flex flex-column md:flex-row gap-3`, gives each column `flex flex-column gap-3 flex-1`, and gives every other direct child a full-width row. Those are PrimeFlex utility classes. Neither Arc nor Components ships them and a PrimeReact theme does not include them, so load PrimeFlex or define equivalent rules in the application's CSS. Without them the columns stack and the gaps are missing; nothing fails. With them, columns stack below the `md` breakpoint and sit side by side above it.
|
|
39
|
+
- **Anywhere deeper**, for example inside your own `div` or inside `CommandDialog`: the column is only a full-width vertical stack of its fields. Position it with your own container. Fields in it still bind.
|
|
40
|
+
|
|
41
|
+
Without utility CSS, skip `CommandForm.Column` and put the fields in a CSS Grid container inside the form, for example `<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 16rem), 1fr))', gap: '1rem' }}>`. Fields bind at any depth, so the grid needs no column wrapper.
|
|
32
42
|
|
|
33
43
|
## Submit from outside the form
|
|
34
44
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-components-theme-application
|
|
3
|
-
description: Use when wiring Cratis Components CSS (tokens, structural styles, baseline theme, per-area sheets, Designsystemet bridge), branding or replacing the palette through `--cratis-*` tokens, switching light/dark or theming a subtree, styling component parts, configuring `CratisComponentsProvider` (locale, messages, icons, router, dialog header actions, toaster, overlay container) selecting a renderer adapter,
|
|
3
|
+
description: Use when wiring Cratis Components CSS (tokens, structural styles, baseline theme, per-area sheets, Designsystemet bridge), branding or replacing the palette through `--cratis-*` tokens, switching light/dark or theming a subtree, styling component parts, configuring `CratisComponentsProvider` (locale, messages, icons, router, dialog header actions, toaster, overlay container) selecting a renderer adapter, authoring one for another design system, or upgrading an application from the PrimeReact-based Components major (which codemods to run and in what order). Not for keyboard and ARIA semantics (`cratis-components-accessibility`), raising toasts or busy feedback (`cratis-components-coordinate-feedback`), or choosing which control to render (`cratis-components-choose-control`).
|
|
4
4
|
compatibility: Requires @cratis/components and a CSS bundler that resolves package imports.
|
|
5
5
|
---
|
|
6
6
|
|
package/package/corpus/skills/cratis-fundamentals-concept/references/csharp-serialization.md
CHANGED
|
@@ -27,11 +27,13 @@ var json = JsonSerializer.Serialize(order, Globals.JsonSerializerOptions);
|
|
|
27
27
|
var roundTrippedOrder = JsonSerializer.Deserialize<Order>(json, Globals.JsonSerializerOptions)!;
|
|
28
28
|
```
|
|
29
29
|
|
|
30
|
+
A call without an options argument, `JsonSerializer.Serialize(order)`, uses the `System.Text.Json` defaults and nothing from Cratis or Arc, in any host: property names keep their C# casing, `null` properties are written, a concept becomes an object holding `Value`, and no `_derivedTypeId` is written. Nothing fails; the JSON is just a different shape from the application's HTTP surface. Pass options on every call.
|
|
31
|
+
|
|
30
32
|
`Globals.JsonSerializerOptions` is built once, on first use, against the discovered application types. To build it against another type universe, call `Globals.Configure(derivedTypes)` before the first read; a later call changes nothing.
|
|
31
33
|
|
|
32
34
|
Alternatives:
|
|
33
35
|
|
|
34
|
-
1. Inside an Arc host, use the options Arc itself serializes with
|
|
36
|
+
1. Inside an Arc host, when the JSON must match the HTTP surface, use the options Arc itself serializes with: inject `IOptions<ArcOptions>` and read `Value.JsonSerializerOptions`. `Globals.JsonSerializerOptions` is a separate instance and carries none of the converters or resolvers the application added to Arc's options.
|
|
35
37
|
2. For options you own, add the converters you need from the table below, with the derived-type factory after the others, as the defaults do.
|
|
36
38
|
|
|
37
39
|
## Host without Arc or Chronicle
|
package/package/corpus/skills/cratis-fundamentals-concept/references/typescript-serialization.md
CHANGED
|
@@ -92,6 +92,7 @@ All travel as text. Each has a `toJSON()` that returns that text, so plain `JSON
|
|
|
92
92
|
|
|
93
93
|
Never compare these with `===`: two instances with the same value are different objects. Use `equals` on `Guid`, `DateOnly` and `TimeOnly`, `getTime()` on `Date` and `ticks` on `TimeSpan`.
|
|
94
94
|
|
|
95
|
+
- **`DateOnly.parse` validates, `DateOnly.from` does not.** `parse` throws on text that is not `yyyy-MM-dd` and on a date that does not exist (month 13, 30 February, 29 February outside a leap year). `from(year, month, day)` and `fromDate` store what they are given, so `DateOnly.from(2025, 2, 30)` succeeds and serializes as `2025-02-30`, which the backend then rejects. Build a `DateOnly` from typed or picked text with `parse` inside a `try`, from a picker's `Date` with `fromDate`, and reserve `from` for parts already known to be a real date. Declare a calendar date on a contract as `@field(DateOnly)`; it needs no concept wrapper to travel correctly.
|
|
95
96
|
- **`Guid.equals(other)`** compares canonical text: a `Guid` is used as-is, any other argument is converted with `toString()`, so GUID text matches and non-GUID text returns `false`. It throws on `null` or `undefined`, so guard nullable values first. The parameter is typed `object`, so turn text you hold into a `Guid` with `Guid.as(text)` (or declare a typed `@field(Guid)` member) before comparing. `Guid.as` and `Guid.parse` throw on non-GUID text, so check untrusted text with `Guid.isGuid` first.
|
|
96
97
|
- **`TimeSpan` components and totals:** `days`, `hours`, `minutes`, `seconds` (and `milliseconds`, `microseconds`, `nanoseconds`) are components: `hours` is 0 to 23 and whole days sit in `days`. Components other than `days` are unsigned, so read the sign from `ticks` or a total. `ticks`, `totalDays`, `totalHours`, `totalMinutes`, `totalSeconds` and the other totals are signed aggregates, so compare and threshold on them. `parse` rejects hours above 23 and minutes or seconds above 59, so a duration of a day or more is written with a day part (`1.02:30:00`).
|
|
97
98
|
- **`TimeSpan` fields are plain and writable:** assigning one recalculates nothing, and the text (`toString()`, `toJSON()`) is formatted from `ticks`. Build a changed duration by parsing new text, never by assigning a field.
|
|
@@ -238,5 +239,6 @@ pathOf<Invoice>(invoice => invoice.customer.name); // 'customer.name'
|
|
|
238
239
|
| A polymorphic member comes back as the base type | The subclass module was not imported, the identifier differs from the backend's, or `derivatives` omits it | Import it, align the identifier, or list it |
|
|
239
240
|
| `Derived type identifier '…' is already registered for '…'` | Two different classes use one identifier under the same base | Give each a unique identifier |
|
|
240
241
|
| `Not a Guid.`, `Invalid DateOnly format`, `Invalid TimeOnly format`, `Invalid TimeSpan format` | The text is not the wire format in the Value types table | Fix the payload or the declared type |
|
|
242
|
+
| `Invalid DateOnly: … is out of range` | The text has the right format but names a date that does not exist | Fix the value; validate input before parsing |
|
|
241
243
|
| A `ValueMap` lookup returns `undefined` for a key that exists, or another key's value | The lookup key's members are in a different order, a member differs from what reading gives it (`null` versus absent, or an array member unset instead of `[]`), a read `Date` key kept sub-millisecond digits, a stored key was changed after insertion, or the key class has no `@field` members | Decorate every key member with `@field`; create lookup keys with `new`, assign members in declared order, give each member the value the read key has (absent stays unassigned, an absent array is `[]`, `null` only where the stored key is `null`), or reuse a key from `entries()`; never change a stored key |
|
|
242
244
|
| A console warning at load about more than one copy of the package | The package was loaded twice: two installs (even of the same release), or one install reached as both ESM and CommonJS. Converters registered on one copy do not reach the other | Deduplicate the dependency and load it through one module format |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-platform-upgrade-application
|
|
3
|
-
description: Use when moving an existing Cratis application to newer Cratis packages, tools or images, or when a build or run breaks after such an update. Not for upgrading the Chronicle kernel itself (`cratis-chronicle-deploy-kernel`) or scaffolding a new application (`cratis-platform-start-application`).
|
|
3
|
+
description: Use when moving an existing Cratis application to newer Cratis packages, tools or images, pinning Cratis package and image versions before a first production deployment, planning or reviewing a Cratis dependency upgrade (which package versions pair, and the order of the steps), or when a build or run breaks after such an update. Not for the PrimeReact codemods and the renderer and CSS migration of a Components major (`cratis-components-theme-application`), upgrading the Chronicle kernel itself (`cratis-chronicle-deploy-kernel`) or scaffolding a new application (`cratis-platform-start-application`).
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Move an application to newer Cratis packages, tools and images
|
package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-events.md
CHANGED
|
@@ -41,10 +41,18 @@ result.ShouldHaveConstraintViolation("UniqueCarrierName");
|
|
|
41
41
|
| `Given.ForEventSource(id).Events(...)` | Seed history; awaited. A seeded event the log refuses throws `GivenEventAppendFailed` naming the violations, so a spec never runs against history it did not receive |
|
|
42
42
|
| `When.ForEventSource(id).Events(first, ...)` | The act; returns `AppendResult` |
|
|
43
43
|
| `EventLog` / `EventSequence` | The real client API over the in-memory store, for `Append`, `AppendMany`, `HasEventsFor` and the assertions below |
|
|
44
|
-
| `ReadModels` | Read models
|
|
44
|
+
| `ReadModels` | Read models folded from this scenario's own log: `GetInstanceById`, `GetInstances` and `Observe<T>()`. See the note below the table |
|
|
45
45
|
| `Time` | The scenario clock, a `ScenarioTime` |
|
|
46
46
|
| `Dispose()` | Release the scenario; use `using` or `Destroy` |
|
|
47
47
|
|
|
48
|
+
`scenario.ReadModels` is the surface to hand to code that depends on `IReadModels` and enumerates or observes. It reads only what was seeded or appended through this scenario (`Given`, `When`, `EventLog`).
|
|
49
|
+
|
|
50
|
+
- `await scenario.ReadModels.GetInstances<T>()` returns the collection folded from the log, and `GetInstanceById<T>(key)` one instance.
|
|
51
|
+
- `scenario.ReadModels.Observe<T>()` (import `System.Reactive.Linq` to subscribe) emits the collection on subscription and again after each successful append that changes it; an unchanged collection does not emit. Await a signal completed by the subscription, for example a `TaskCompletionSource` per expected emission, with a timeout. Never sleep before asserting. Dispose the subscription. Passive read models and event-target projections cannot be observed.
|
|
52
|
+
- To give an existing testing read-model surface this behaviour over a log you already hold, wrap it: `new ReadModelsForTesting(inner, eventLog)` (namespace `Cratis.Chronicle.Testing.ReadModels`). Take `inner` from the testing event store that owns that log, so its artifacts, explicit projections and services are kept.
|
|
53
|
+
|
|
54
|
+
This proves the fold and what the subscriber is handed. It does not prove kernel delivery or a sink's change notifications.
|
|
55
|
+
|
|
48
56
|
## Append-result assertions
|
|
49
57
|
|
|
50
58
|
| Assertion | Passes when |
|
|
@@ -43,6 +43,37 @@ Both `Perform` and `Observe` take optional `paging` (`Paging`) and `sorting` (`S
|
|
|
43
43
|
|
|
44
44
|
Events seeded through `Given.ForEventSource(id).Events(...)` run the application's own projection or reducer, including children and joins, so the query is proven against the model production would hold. After `Observe`, seed further events and await `observation.Next()` to prove the query pushes the changed model.
|
|
45
45
|
|
|
46
|
+
## Observe what a command appends
|
|
47
|
+
|
|
48
|
+
A query scenario and a command scenario created independently have separate logs, so the observation never sees the command's appends and `Next()` times out. Share the command scenario's services and context with the query scenario before seeding or first using either one:
|
|
49
|
+
|
|
50
|
+
```csharp
|
|
51
|
+
using Cratis.Arc.Chronicle.Testing.Commands;
|
|
52
|
+
using Cratis.Arc.Chronicle.Testing.Queries;
|
|
53
|
+
using Cratis.Arc.Testing.Commands;
|
|
54
|
+
using Cratis.Arc.Testing.Queries;
|
|
55
|
+
|
|
56
|
+
await using var commands = new CommandScenario<ChangeBalance>();
|
|
57
|
+
await using var queries = new QueryScenario<AccountBalance>();
|
|
58
|
+
|
|
59
|
+
foreach (var resource in queries.Context.Values.Distinct().OfType<IDisposable>()) resource.Dispose();
|
|
60
|
+
queries.Context.Clear();
|
|
61
|
+
queries.Services.Clear();
|
|
62
|
+
foreach (var service in commands.Services) queries.Services.Add(service);
|
|
63
|
+
foreach (var (key, value) in commands.Context) queries.Context[key] = value;
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Then seed with `queries.Given.ForEventSource(id).Events(...)`, open `await queries.Observe(...)`, run `await commands.Execute(...)` and assert the result of `await observation.Next()`.
|
|
67
|
+
|
|
68
|
+
State each prior event exactly once. After sharing, `queries.Given` and `commands.Given` write to the same seed store, and the observation also receives every successful append to the command's log, including events placed there with `commands.EventScenario.Given`. An event stated through two of those is folded twice, so counts and sums double.
|
|
69
|
+
|
|
70
|
+
| Mode | What the observation folds | Where a seed lands |
|
|
71
|
+
| --- | --- | --- |
|
|
72
|
+
| Default | The `Given` seeds plus the command log's successful appends | `Given` seeds feed injected read models and the observation, and never enter the command log |
|
|
73
|
+
| Decision | One log shared by seeds, commands and observation | `Given` seeds enter that log; `commands.EventScenario` throws |
|
|
74
|
+
|
|
75
|
+
`QueryScenario` has no decision-mode switch: the command scenario selects the mode and the shared query follows it.
|
|
76
|
+
|
|
46
77
|
An observed query merges a row pinned with `.ReadModel(instance)` by its identifier: `[Key]`, then `[Subject]`, then a property named `Id`. A pinned instance without a readable identifier, or with a null one, cannot be merged. `scenario.Observe` does not throw for it: the failure arrives as a failed query result carrying the `PinnedReadModelCannotBeObserved` message. Where it arrives depends on when the instance was pinned:
|
|
47
78
|
|
|
48
79
|
| Pinned | Failed result |
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
- Setup
|
|
6
6
|
- What to prove per slice type
|
|
7
|
+
- What a scenario does not prove
|
|
7
8
|
- Default path: refuse an invalid command
|
|
8
9
|
- Common mistakes
|
|
9
10
|
- Command scenario
|
|
@@ -68,6 +69,20 @@ Each row lists the proofs a slice of that type needs; follow the link for how to
|
|
|
68
69
|
|
|
69
70
|
A reactor that calls the command pipeline is not failed by an unsuccessful result unless its own code throws on it, so which results it throws on and which it tolerates is behaviour to prove.
|
|
70
71
|
|
|
72
|
+
## What a scenario does not prove
|
|
73
|
+
|
|
74
|
+
Every scenario here runs in process. None of them proves observer delivery, storage in a real sink, transport or HTTP: those need a running kernel or the HTTP host ([csharp-integration.md](csharp-integration.md)). Beyond that, each scenario has its own limit and one combination to avoid.
|
|
75
|
+
|
|
76
|
+
| Scenario | It does not prove | Do not combine |
|
|
77
|
+
| --- | --- | --- |
|
|
78
|
+
| `CommandScenario` | That a query or subscription sees what the command appended. That needs a query scenario sharing its services and context: [csharp-query-scenario.md](csharp-query-scenario.md). | Seeds in two places for one fact. In default mode `Given` supplies injected read-model state and `EventScenario.Given` supplies log history. |
|
|
79
|
+
| `QueryScenario` | Anything about a command scenario created independently: the two have separate state, so waiting for the next emission times out. | The same event seeded through both `commands.Given` and `queries.Given` once the scenarios are shared: they write to one seed store and the observation folds both copies. Seed each event once. |
|
|
80
|
+
| `EventScenario` | That a projection, reducer or reactor was delivered the event by an observer. `ReadModels` folds the scenario's own log on each read. | Appends through `Defaults.Instance.EventStore` or another store: that is a different log, which this scenario's `ReadModels` never reads. |
|
|
81
|
+
| `ReadModelScenario` | Collection reads and subscriptions. It collects its input instead of appending it to a log, so its `ReadModels` serves only `GetInstanceById` for seeded instances. | `ReadModels.GetInstances` or `ReadModels.Observe` expecting the scenario's output: `Observe` throws `ReadModelCannotBeObserved` and `GetInstances` needs a running Chronicle. Assert through `Instance`, `Instances` or `InstanceForEventSourceId`. Hand code that enumerates or observes through `IReadModels` the `ReadModels` of an `EventScenario` instead ([csharp-events.md](csharp-events.md)). |
|
|
82
|
+
| `ReactorScenario` | That anything was sent, appended or executed. The default recorder records what the reactor returned; it does not append events, execute commands or call a registered `IReactorSideEffectHandler`. | An assertion on a gateway or a substitute behind a side-effect handler after a default-recorder run: it was never called. Assert `Produced` or `ShouldHaveProduced<T>`, and prove the effect in a spec of the handler or against a running kernel. |
|
|
83
|
+
|
|
84
|
+
A reactor that returns a custom type still needs an `IReactorSideEffectHandler` claiming that type registered in `scenario.Services`; without one, the scenario throws `InvalidReactorHandlerReturnType`. The registration only makes the return type legal: the recorder keeps the value and the handler does not handle it.
|
|
85
|
+
|
|
71
86
|
## Default path: refuse an invalid command
|
|
72
87
|
|
|
73
88
|
Seed another registration so earlier history is distinguishable from this command’s work.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cratis-specifications-test-typescript-behavior
|
|
3
|
-
description: Use when writing or repairing an isolated TypeScript spec for a calculation, parser, serializer, view model, or command decision invoked directly in the package's runner. Not for the Arc Node command or query pipeline (use cratis-arc-testing-typescript), mounted UI (use cratis-specifications-test-application-ui), or C# specs (use cratis-specifications-isolate-behavior).
|
|
3
|
+
description: Use when writing or repairing an isolated TypeScript spec for a calculation, parser, serializer, view model, or command decision invoked directly in the package's runner, or the client-side validation of a generated command proxy without a backend. Not for the Arc Node command or query pipeline (use cratis-arc-testing-typescript), mounted UI (use cratis-specifications-test-application-ui), or C# specs (use cratis-specifications-isolate-behavior).
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Specify isolated behavior in the package's runner
|
|
@@ -27,6 +27,7 @@ Read `references/<language>.md` for the project's SDK (`.csproj` → csharp, Nod
|
|
|
27
27
|
| A calculation, parser, serializer, mapping or value rule | This skill: call the function directly |
|
|
28
28
|
| A view model's decisions without mounting the UI | This skill |
|
|
29
29
|
| The calculation or branch inside a command handler, given explicit inputs | This skill: call the handler on a command instance |
|
|
30
|
+
| What a generated command proxy rejects locally, with no backend | This skill: `validateClientSide()`; see the SDK reference |
|
|
30
31
|
| Validation, authorization, preparation, service binding, or result envelope in the Arc server pipeline | `cratis-arc-testing-typescript` |
|
|
31
32
|
| Which events a command appends, or which read model a projection produces | `cratis-specifications-exercise-backend` |
|
|
32
33
|
| A mounted screen that responds to input, navigates or survives a refusal | `cratis-specifications-test-application-ui` |
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
- Test doubles
|
|
12
12
|
- Fake time
|
|
13
13
|
- Arc command decision
|
|
14
|
+
- Generated command client validation
|
|
14
15
|
- Specs without globals
|
|
15
16
|
- Common mistakes and recovery
|
|
16
17
|
|
|
@@ -315,6 +316,43 @@ describe('when pricing an order directly', () => {
|
|
|
315
316
|
|
|
316
317
|
Await `handle()` when it returns a promise. Assert the in-memory `OrderTotal`, not its wire representation. A direct call skips validation, preparation, authorization, service resolution, and response encoding; use `cratis-arc-testing-typescript` to prove that wiring.
|
|
317
318
|
|
|
319
|
+
## Generated command client validation
|
|
320
|
+
|
|
321
|
+
A generated command proxy validates in two ways. Pick by whether the spec may reach a server.
|
|
322
|
+
|
|
323
|
+
| Call | What runs |
|
|
324
|
+
| --- | --- |
|
|
325
|
+
| `command.validateClientSide()` | Synchronous and never sends a request: the generated rules, then the required-property check. |
|
|
326
|
+
| `await command.validate()` | The same two local steps. A blocking local failure returns without a request. Otherwise it POSTs to the command's route with `/validate` appended. |
|
|
327
|
+
|
|
328
|
+
Use `validateClientSide()` in a spec that must run without a backend. `validate()` and `execute()` send a request for every draft the local rules accept, so they are not network-free.
|
|
329
|
+
|
|
330
|
+
```typescript
|
|
331
|
+
const command = new ReserveMeetingRoom();
|
|
332
|
+
command.room = 'Fjord';
|
|
333
|
+
command.attendees = 6;
|
|
334
|
+
expect(command.validateClientSide().isValid).toBe(true);
|
|
335
|
+
|
|
336
|
+
command.attendees = 13;
|
|
337
|
+
|
|
338
|
+
const result = command.validateClientSide();
|
|
339
|
+
|
|
340
|
+
expect(result.isValid).toBe(false);
|
|
341
|
+
expect(result.validationResults.flatMap(_ => _.members)).toContain('attendees');
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
Start from a draft the rules accept, prove it passes, then change exactly one field. Assert the failing member, not only `isValid`: with two fields invalid at once, one rule can pass for another.
|
|
345
|
+
|
|
346
|
+
What the local result covers:
|
|
347
|
+
|
|
348
|
+
- **Mirrored rules.** With the default generation setting the proxy carries the backend validator's translatable rules, for example `NotEmpty()` as `notEmpty()` and `LessThanOrEqualTo(12)` as `lessThanOrEqual(12)`. `notEmpty()` rejects `null`, `undefined`, a blank string and an empty array.
|
|
349
|
+
- **Required properties.** A non-optional property fails only when it is `null` or `undefined`. An empty string `''` passes this check but can fail a mirrored rule such as `notEmpty()` or `minLength(1)`.
|
|
350
|
+
- **Not translated.** `Must`, `MustAsync`, custom validators, conditional rules (`When`, `Unless`) and any rule that needs a dependency exist only on the server. A project generated with client validation set to `server` carries no generated rules at all.
|
|
351
|
+
|
|
352
|
+
A passing local result is therefore not proof that the server accepts the command. Prove each server-only rule in a backend spec through the command pipeline (see `cratis-specifications-exercise-backend`). Do not stub `fetch` with a canned failure and call that proof of the rule: it proves only how the caller handles a refusal.
|
|
353
|
+
|
|
354
|
+
To see which rules a proxy carries, read the generated file; never edit it. How a screen uses the two calls is in `cratis-arc-react-bind-slice`.
|
|
355
|
+
|
|
318
356
|
## Specs without globals
|
|
319
357
|
|
|
320
358
|
When the package does not expose global suite functions, import them from the runner. The example uses Vitest matchers; keep the package's assertion style and naming regardless of how the suite functions are bound:
|