@shivaedev/contract 0.49.0 → 0.51.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/CHANGELOG.md +22 -0
- package/README.md +160 -123
- package/dist/bind.d.ts +7 -0
- package/dist/bind.d.ts.map +1 -1
- package/dist/bind.js +2 -1
- package/dist/bind.js.map +1 -1
- package/dist/clientOperations.d.ts +5 -1
- package/dist/clientOperations.d.ts.map +1 -1
- package/dist/clientOperations.js +4 -0
- package/dist/clientOperations.js.map +1 -1
- package/dist/commandSignal.d.ts.map +1 -1
- package/dist/commandSignal.js +17 -13
- package/dist/commandSignal.js.map +1 -1
- package/dist/connectionReadiness.js +1 -1
- package/dist/connectionReadiness.js.map +1 -1
- package/dist/defineModule.d.ts +5 -7
- package/dist/defineModule.d.ts.map +1 -1
- package/dist/defineModule.js.map +1 -1
- package/dist/failureKind.d.ts +10 -0
- package/dist/failureKind.d.ts.map +1 -0
- package/dist/failureKind.js +20 -0
- package/dist/failureKind.js.map +1 -0
- package/dist/live.d.ts.map +1 -1
- package/dist/live.js +16 -6
- package/dist/live.js.map +1 -1
- package/dist/liveHintQueue.d.ts.map +1 -1
- package/dist/liveHintQueue.js +19 -14
- package/dist/liveHintQueue.js.map +1 -1
- package/dist/moduleHandlers.d.ts +3 -3
- package/dist/moduleHandlers.d.ts.map +1 -1
- package/dist/moduleHandlers.js.map +1 -1
- package/dist/moduleProof.d.ts +10 -12
- package/dist/moduleProof.d.ts.map +1 -1
- package/dist/querySubscription.js +5 -1
- package/dist/querySubscription.js.map +1 -1
- package/dist/reflection.d.ts.map +1 -1
- package/dist/reflection.js +3 -3
- package/dist/reflection.js.map +1 -1
- package/dist/runProof.d.ts +2 -1
- package/dist/runProof.d.ts.map +1 -1
- package/dist/servedOperation.d.ts.map +1 -1
- package/dist/servedOperation.js +2 -1
- package/dist/servedOperation.js.map +1 -1
- package/dist/socketProtocol.js +1 -1
- package/dist/socketProtocol.js.map +1 -1
- package/dist/staleWrite.d.ts +10 -0
- package/dist/staleWrite.d.ts.map +1 -0
- package/dist/staleWrite.js +14 -0
- package/dist/staleWrite.js.map +1 -0
- package/package.json +9 -9
- package/src/bind.ts +9 -9
- package/src/clientOperations.ts +4 -0
- package/src/commandSignal.ts +16 -12
- package/src/connectionReadiness.ts +1 -1
- package/src/defineModule.ts +13 -10
- package/src/failureKind.ts +33 -0
- package/src/live.ts +19 -6
- package/src/liveHintQueue.ts +20 -14
- package/src/moduleHandlers.ts +3 -3
- package/src/moduleProof.ts +15 -23
- package/src/querySubscription.ts +7 -1
- package/src/reflection.ts +88 -86
- package/src/runProof.ts +3 -1
- package/src/servedOperation.ts +2 -1
- package/src/socketProtocol.ts +1 -1
- package/src/staleWrite.ts +23 -0
package/README.md
CHANGED
|
@@ -30,7 +30,7 @@ const Rename = command("rename", {
|
|
|
30
30
|
},
|
|
31
31
|
});
|
|
32
32
|
|
|
33
|
-
export const Notes = defineModule({ name: "notes", operations: [List, Rename],
|
|
33
|
+
export const Notes = defineModule({ name: "notes", operations: [List, Rename], wire: notesWire });
|
|
34
34
|
```
|
|
35
35
|
|
|
36
36
|
`Notes` is a native RPC group with `notes.list` and `notes.rename`, served by the operations themselves. Nothing restates what `list` returns or how `rename` fails: [`@shivaedev/build`](https://github.com/ShivaeDev/platform/tree/main/packages/build) writes those schemas from `run`'s types into `notesWire`, and the compiler checks them against `run` on every type check. When a bound rename succeeds, the note's key refreshes its readers and the list; an item query for another note keeps its result. Handlers, middleware and transport use Effect's own APIs.
|
|
@@ -41,7 +41,7 @@ export const Notes = defineModule({ name: "notes", operations: [List, Rename], r
|
|
|
41
41
|
|
|
42
42
|
An **operation** is a query or a command written as its `payload` schema and a generator `*run`. Everything else about its boundary is derived from `run`: what it returns, the tagged failures it raises, and the services it needs. A **query** listens on the keys its repository reads name, or on the keys it declares in `reads`; a **command** announces the keys its repository writes name, plus any it declares in `invalidates`. A **rejection** is an expected typed failure that `run` raises, such as a missing note or an invalid title. Middleware failures and RPC client failures remain separate parts of the native client's error type.
|
|
43
43
|
|
|
44
|
-
A **module** lists its operations
|
|
44
|
+
A **module** lists its operations and serves them without hand-written handlers; its type carries the services they yield. Types are erased, so the schemas the server encodes with and the browser decodes with must exist as values: the module's **wire** holds them, generated from `run`'s types, and the browser imports a **browser contract** generated beside it, which carries no `run`. A module is a native `RpcGroup`. Its RPC tags are the module name and operation name joined by a dot. A **binding** connects a module or contract to an existing `AtomRpc.Service`: queries get native query atoms and call Effects, while commands get call Effects that invalidate after success.
|
|
45
45
|
|
|
46
46
|
A **collection key** names a dependency. Its item key identifies one item; its list key identifies a list in that collection. Keys do not hold data. Native query atoms hold results, and native Reactivity asks matching queries to run again. Live subscriptions use those same keys to rerun each subscriber’s authorized query on the server and push its changed result.
|
|
47
47
|
|
|
@@ -89,15 +89,17 @@ Here `NotesRepository` is a `@shivaedev/sql` repository whose model marks `userI
|
|
|
89
89
|
|
|
90
90
|
A command without `invalidates` announces no keys of its own. Its `invalidates` takes the decoded payload and returns keys; object keys are sorted, so `invalidates` is checked before `run` and cannot see `run`'s result. A command that must announce keys computed from what it did, such as the note it found by title or the people a move affected, contributes them from inside `run` with [`commandResult`](#server-only-command-keys).
|
|
91
91
|
|
|
92
|
-
An operation written this way states no `success` or `rejections`: its module's wire supplies both. On its own, outside a module, it is served with `Schema.Void` and only `InternalServerError` and `ServiceUnavailable`. Every operation written this way carries those two in its type and its rejection set. Nothing adds `Conflict`: an operation that answers a constraint violation as a domain failure maps it by constraint name in `run`, and inference carries the result. A failure that states `isRetryable` (such as `SqlError`), `SchemaError` and `QueryReadDenied` are never rejections. Rejections are exported classes keyed by their `_tag`.
|
|
92
|
+
An operation written this way states no `success` or `rejections`: its module's wire supplies both. On its own, outside a module, it is served with `Schema.Void` and only `InternalServerError` and `ServiceUnavailable`. Every operation written this way carries those two in its type and its rejection set. A stale versioned write is the one failure `run` answers for the operation: an `OptimisticConcurrencyError` from an `@shivaedev/sql` repository that reaches the end of `run` becomes the shared `Conflict`, with a message telling the person to refresh, so the operation's type, its generated wire and its client list `Conflict`. An operation that wants another answer catches `OptimisticConcurrencyError` itself, and inference carries what it raises instead. Nothing else adds `Conflict`: an operation that answers a constraint violation as a domain failure maps it by constraint name in `run`, and inference carries the result. A failure that states `isRetryable` (such as `SqlError`), `SchemaError` and `QueryReadDenied` are never rejections. Rejections are exported classes keyed by their `_tag`.
|
|
93
93
|
|
|
94
94
|
`run` must not return `any`, such as the result of `JSON.parse`, which would otherwise pass every check: such an operation is a compile error that names it and `RunReturnsAny` (decode the value with a schema, or type it). While the declaration form is still accepted, that error starts with "No overload matches this call" and its last line names the problem. Biome's `useYield` refuses a `*run` that yields nothing, so a `run` that needs no service still yields an Effect.
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
`failureKind(error)` from `@shivaedev/contract/failureKind.ts` sorts an operation's failure for its client: `"request"` for a shared request rejection (the `RequestRejection` type in `@shivaedev/errors/taxonomy.ts`), `"framework"` for a `ServerFailure`, an `RpcClientError` or the contract's own `MissingReadPolicy`, `MissingReadPolicies`, `QueryReadDenied` and `WebSocketRequired`, `"framework"` also for a failure without a string `_tag`, and `"app"` for any other tagged failure, which is a rejection the feature declared for itself. `AppRejection<E>` and `FrameworkFailure` are the matching types; `@shivaedev/react` requires a handler only for an `AppRejection`.
|
|
97
|
+
|
|
98
|
+
A field failure is an exported tagged class built from the payload's fields with `fieldRejection`, as `TitleTaken` above. `run` raises it with `yield* new TitleTaken({ field, message })`; `useCreate` and `useEditor` in `@shivaedev/react` place its message on that field, as `@shivaedev/form`'s `rejecting` does for a form used directly.
|
|
97
99
|
|
|
98
100
|
#### A module defined from its operations
|
|
99
101
|
|
|
100
|
-
A module lists its operations once
|
|
102
|
+
A module lists its operations once and serves them without hand-written handlers:
|
|
101
103
|
|
|
102
104
|
```ts
|
|
103
105
|
import { Effect, Option, Schema } from "effect";
|
|
@@ -107,7 +109,7 @@ import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
|
107
109
|
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
108
110
|
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
109
111
|
import { fieldRejection } from "@shivaedev/contract/rejection.ts";
|
|
110
|
-
import { notesWire } from "#generated/modules/notes/
|
|
112
|
+
import { notesWire } from "#generated/modules/notes/Notes.ts";
|
|
111
113
|
import { Caller, NotesStore, type StoredNote } from "./services.ts";
|
|
112
114
|
|
|
113
115
|
const notes = collection("notes", Schema.Number);
|
|
@@ -171,28 +173,29 @@ export const Notes = defineModule({
|
|
|
171
173
|
middleware: Caller,
|
|
172
174
|
name: "notes",
|
|
173
175
|
operations: [List, Get, Create],
|
|
174
|
-
requires: [NotesStore],
|
|
175
176
|
wire: notesWire,
|
|
176
177
|
});
|
|
177
178
|
```
|
|
178
179
|
|
|
179
|
-
Here `NotesStore` is an ordinary service, `StoredNote` the row it returns, and `Caller` an RPC middleware that sets the viewer. `defineModule` takes the operations written as payload and run,
|
|
180
|
+
Here `NotesStore` is an ordinary service, `StoredNote` the row it returns, and `Caller` an RPC middleware that sets the viewer. `defineModule` takes the operations written as payload and run, its `wire` (below), and optionally `middleware`, `subject` and `keyScope` as `contract` does. It returns the module's contract, so `bind`, `makeClient` and a host accept it as they accept any contract. Each of its RPCs carries the `DefinedModule` annotation from the same file with the module's name, so a host can tell a module's queries from a contract's. The module lists no services: its type carries, for each operation, the services that operation's `run` and read policy yield, less what its middleware and subject provide per call, and nothing reads them at run time. An operation that starts to yield another service changes only that operation. A definition without `wire` is a compile error that says the property is missing. Its generics check the definition on the `name` line, so the first line of the compiler's message names the operation and its problem, such as `OperationNameRepeated` when two operations share a name:
|
|
180
181
|
|
|
181
182
|
```
|
|
182
|
-
src/test-support/fixtures/invalid/
|
|
183
|
+
src/test-support/fixtures/invalid/moduleRepeatedName.ts(15,2): error TS2322: Type '"lists"' is not assignable to type '"lists" & NoInfer<OperationNameRepeated<"list">>'.
|
|
183
184
|
```
|
|
184
185
|
|
|
185
|
-
`moduleHandlers(Notes)` builds the module's handler Layer from its operations, and the Layer requires exactly the services
|
|
186
|
+
`moduleHandlers(Notes)` builds the module's handler Layer from its operations, and the Layer requires exactly the services the operations yield beyond the middleware and subject, here `NotesStore`, so serving it provides that service on the Layer:
|
|
186
187
|
|
|
187
188
|
```ts
|
|
188
189
|
import { Layer } from "effect";
|
|
189
190
|
import { moduleHandlers } from "@shivaedev/contract/moduleHandlers.ts";
|
|
190
|
-
import { Notes } from "./
|
|
191
|
+
import { Notes } from "./Notes.ts";
|
|
191
192
|
import { NotesStoreLive } from "./store.ts";
|
|
192
193
|
|
|
193
194
|
export const NotesHandlers = moduleHandlers(Notes).pipe(Layer.provide(NotesStoreLive));
|
|
194
195
|
```
|
|
195
196
|
|
|
197
|
+
An application registers the module with the server instead, and the [server's `appModules`](https://github.com/ShivaeDev/platform/tree/main/packages/server#host-the-application) refuses a registration list that leaves a service unprovided, naming the module, the operation and the service.
|
|
198
|
+
|
|
196
199
|
Each operation runs in a span named after the module and the operation, such as `Notes.create`. A query's read policy is checked inside its handler before `run`, with the module's services, so a policy reads a repository directly, as `Get` does above; a live subscription to the query checks the same policy. Failures pass the RPC boundary from `@shivaedev/errors`: a rejection the wire lists reaches the client as itself, an unlisted failure that states `isRetryable` answers `ServiceUnavailable`, and anything else answers `InternalServerError`, for the policy of a live subscription too. A command without `invalidates` publishes only the keys its writes announce.
|
|
197
200
|
|
|
198
201
|
#### The wire and the browser's contract
|
|
@@ -206,7 +209,7 @@ import { Schema } from "effect";
|
|
|
206
209
|
import { Unauthorized } from "@shivaedev/errors/taxonomy.ts";
|
|
207
210
|
import { clientContract } from "@shivaedev/contract/clientContract.ts";
|
|
208
211
|
import type { ClientMatchesModule } from "@shivaedev/contract/clientMatchesModule.ts";
|
|
209
|
-
import type { Notes as NotesModule } from "#modules/notes/
|
|
212
|
+
import type { Notes as NotesModule } from "#modules/notes/Notes.ts";
|
|
210
213
|
import { Caller, NoteFields, notes, TitleTaken } from "#modules/notes/model.ts";
|
|
211
214
|
|
|
212
215
|
const Note = Schema.Struct({ createdAt: Schema.Date, id: Schema.Number, title: Schema.String });
|
|
@@ -300,22 +303,31 @@ The native RPC mapping types `OperationRpc` and `Tag` are exported from `@shivae
|
|
|
300
303
|
|
|
301
304
|
### Whose account a request acts on
|
|
302
305
|
|
|
303
|
-
Set `subject` on a contract to a browser-safe declaration from `@shivaedev/identity/subject.ts`: `selfSubject` selects the session account; `accountSubject({ permission, refusal, deny })` permits another account only with the permission's `any` grant. `delegatedSubject({ service, refusal, deny })` asks the application's rule per call, with a `kind` of `read` for queries and streams or `write` for commands. A contract's `declaration.subject` records the declaration it names. The declaration applies to the application RPCs and their changes stream. Native middleware carries its typed failures and supplies the branded `Subject` service to
|
|
306
|
+
Set `subject` on a module or contract to a browser-safe declaration from `@shivaedev/identity/subject.ts`: `selfSubject` selects the session account; `accountSubject({ permission, refusal, deny })` permits another account only with the permission's `any` grant. `delegatedSubject({ service, refusal, deny })` asks the application's rule per call, with a `kind` of `read` for queries and streams or `write` for commands. A contract's `declaration.subject` records the declaration it names. The declaration applies to the application RPCs and their changes stream. Native middleware carries its typed failures and supplies the branded `Subject` service to each operation's `run` and the application services it calls. Business payloads need no owner id.
|
|
304
307
|
|
|
305
308
|
```ts
|
|
306
|
-
import {
|
|
309
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
307
310
|
import { command } from "@shivaedev/contract/operation.ts";
|
|
308
|
-
import { selfSubject } from "@shivaedev/identity/subject.ts";
|
|
311
|
+
import { selfSubject, Subject } from "@shivaedev/identity/subject.ts";
|
|
312
|
+
import { accountWire } from "#generated/modules/account/Account.ts";
|
|
313
|
+
import { PreferenceFields } from "#modules/account/model.ts";
|
|
314
|
+
import { Profiles } from "./services.ts";
|
|
309
315
|
|
|
310
|
-
const Save = command("save", {
|
|
311
|
-
|
|
316
|
+
const Save = command("save", {
|
|
317
|
+
payload: PreferenceFields,
|
|
318
|
+
*run({ title }) {
|
|
319
|
+
const { id } = yield* Subject;
|
|
320
|
+
yield* (yield* Profiles).rename(id, title);
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
export const Account = defineModule({ name: "account", operations: [Save], subject: selfSubject, wire: accountWire });
|
|
312
324
|
```
|
|
313
325
|
|
|
314
|
-
Contracts with declared subjects can be exported from published packages with TypeScript declaration output. The client calls `account.save`
|
|
326
|
+
`PreferenceFields` is `Schema.Struct({ title: Schema.String })` and `Profiles` an application service whose `rename` takes the account's `SubjectId`. Contracts with declared subjects can be exported from published packages with TypeScript declaration output. The client calls `account.save` with only its title. For a delegated subject, the client names the account per call: a bound query takes `subject` in its options and a query's, command's or stream's `run` takes `{ subject }` as its second argument, as in `api.title.query(undefined, { subject: "bob" })` and `api.rename.run({ title }, { subject: "bob" })`. The option sets the call's `x-platform-subject` message header, so one client and its one socket serve the actor's own data and any number of subjects, each live query keeping its own subject on its changes stream. Queries with different subjects are different atoms, keep separate retained results, and serialize under separate keys when they share a `serializationKey`. The session host installs the resolver; operations read `Subject` from the request environment. See [identity's subject guide](https://github.com/ShivaeDev/platform/tree/main/packages/identity#declared-request-subjects) for delegated selection and refusal declarations.
|
|
315
327
|
|
|
316
328
|
### Expected failures
|
|
317
329
|
|
|
318
|
-
Import the shared expected failures from `@shivaedev/errors/taxonomy.ts`: `NotFound`, `Unauthorized`, `Forbidden`, `BadRequest`, `Conflict`, `PreconditionFailed`, `TooManyRequests`, `AuthUnavailable`, `InternalServerError` and `ServiceUnavailable`. Each class is a tagged error schema with a string `message`; `BadRequest` and `Conflict` also accept an optional string `field`. Declare only the failures an operation can return:
|
|
330
|
+
Import the shared expected failures from `@shivaedev/errors/taxonomy.ts`: `NotFound`, `Unauthorized`, `Forbidden`, `BadRequest`, `Conflict`, `PreconditionFailed`, `TooManyRequests`, `AuthUnavailable`, `InternalServerError` and `ServiceUnavailable`. Each class is a tagged error schema with a string `message`; `BadRequest` and `Conflict` also accept an optional string `field`. An operation written with `run` raises them and its wire lists them; the rest of this section is about RPCs that state their failures by hand, as native `Rpc` definitions and operations declared without run do. Declare only the failures an operation can return:
|
|
319
331
|
|
|
320
332
|
```ts
|
|
321
333
|
import { Effect, Schema } from "effect";
|
|
@@ -347,7 +359,7 @@ const missing = Get.reject.NoteMissing({ id: 9 });
|
|
|
347
359
|
|
|
348
360
|
### 2. Once per host: native handlers and transport
|
|
349
361
|
|
|
350
|
-
|
|
362
|
+
An application registers its defined modules with the [server's host](https://github.com/ShivaeDev/platform/tree/main/packages/server#host-the-application), which builds their handlers with `moduleHandlers`, and writes no handlers. A boundary of operations declared without run is implemented with native `of` and `toLayer`:
|
|
351
363
|
|
|
352
364
|
```ts
|
|
353
365
|
import { Effect, Ref, Stream } from "effect";
|
|
@@ -435,7 +447,7 @@ export class NotesClient extends AtomRpc.Service<NotesClient>()("app/NotesClient
|
|
|
435
447
|
export const api = bind(Notes, NotesClient, { live: false });
|
|
436
448
|
```
|
|
437
449
|
|
|
438
|
-
Save the client module as `client.ts`. The [native RPC guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/native-rpc.md) covers hosting; the [
|
|
450
|
+
Save the client module as `client.ts`. The [native RPC guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/native-rpc.md) covers hosting; the [feature guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/add-a-feature.md) composes a defined module, request identity, SQL and a rendered client in the starter.
|
|
439
451
|
|
|
440
452
|
### Build a shared WebSocket client
|
|
441
453
|
|
|
@@ -471,7 +483,7 @@ const readOnce = api.get.run({ id: 1 });
|
|
|
471
483
|
const rename = api.rename.run({ id: 1, title: "Uno" });
|
|
472
484
|
```
|
|
473
485
|
|
|
474
|
-
`one` and `list` are native query atoms. `readOnce` and `rename` are Effects for individual calls. A query's Effect requires `NotesClient`; a command's Effect also requires native `Reactivity`. Commands expose `run`, and have no `query` member.
|
|
486
|
+
`one` and `list` are native query atoms. `readOnce` and `rename` are Effects for individual calls. A query's Effect requires `NotesClient`; a command's Effect also requires native `Reactivity`. Commands expose `run`, the atom `runtime` that provides those services and their declared `payload` schema, and have no `query` member; queries and streams also carry `runtime`. React's action and form hooks take a bound command as it is, as in `useAction(api.rename)`, and a form derives its fields from `payload`.
|
|
475
487
|
|
|
476
488
|
Mount the atoms and run commands through the service's atom runtime in the same registry:
|
|
477
489
|
|
|
@@ -540,7 +552,7 @@ const move = ({ id, household }) =>
|
|
|
540
552
|
result: pot,
|
|
541
553
|
invalidates: [...before, ...after].map((viewerId) => pots.bucket.viewerId(viewerId)),
|
|
542
554
|
});
|
|
543
|
-
}).pipe(transact(
|
|
555
|
+
}).pipe(transact());
|
|
544
556
|
```
|
|
545
557
|
|
|
546
558
|
Here `audienceFor` reads household members and people who ate from the pot from the application's database, `movePot` performs the write, and `pots` declares a `viewerId` bucket. Read the audience after the write to include new readers, and retain the old audience when the write removes access. Each viewer's list reads its own bucket. Keep these reads and the write in the same transaction when they must describe one change.
|
|
@@ -609,45 +621,57 @@ Mount the query to start it. Wait on `completions` for `completed > before` afte
|
|
|
609
621
|
|
|
610
622
|
### Session-owned keys
|
|
611
623
|
|
|
612
|
-
A self-only feature, such as a user's preferences, reads and changes only the signed-in account's records.
|
|
624
|
+
A self-only feature, such as a user's preferences, reads and changes only the signed-in account's records. Define its module with `keyScope: "session"` and let its operations read the account from request-local `Identity`, so payloads carry no owner field, and reads and invalidations name a logical item key for the record:
|
|
613
625
|
|
|
614
626
|
```ts
|
|
615
|
-
|
|
616
|
-
|
|
627
|
+
import { collection } from "@shivaedev/changes/keys.ts";
|
|
628
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
629
|
+
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
630
|
+
import { Identity } from "@shivaedev/identity/identity.ts";
|
|
631
|
+
import { Authenticated } from "@shivaedev/identity/middleware.ts";
|
|
632
|
+
import { preferencesWire } from "#generated/modules/preferences/Preferences.ts";
|
|
633
|
+
import { PreferenceFields, preferences } from "#modules/preferences/model.ts";
|
|
634
|
+
import { PreferencesStore } from "./services.ts";
|
|
635
|
+
|
|
636
|
+
const Self = query("self", {
|
|
637
|
+
reads: () => [preferences.item("self")],
|
|
638
|
+
*run() {
|
|
639
|
+
const { id } = yield* Identity;
|
|
640
|
+
return yield* (yield* PreferencesStore).read(id);
|
|
641
|
+
},
|
|
642
|
+
});
|
|
643
|
+
const Save = command("save", {
|
|
644
|
+
invalidates: () => [preferences.item("self")],
|
|
645
|
+
payload: PreferenceFields,
|
|
646
|
+
*run({ title }) {
|
|
647
|
+
const { id } = yield* Identity;
|
|
648
|
+
return yield* (yield* PreferencesStore).save(id, title);
|
|
649
|
+
},
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
export const Preferences = defineModule({
|
|
617
653
|
keyScope: "session",
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
}),
|
|
631
|
-
],
|
|
632
|
-
}).middleware(Authenticated);
|
|
654
|
+
middleware: Authenticated,
|
|
655
|
+
name: "preferences",
|
|
656
|
+
operations: [Self, Save],
|
|
657
|
+
wire: preferencesWire,
|
|
658
|
+
});
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
`model.ts` declares `preferences` as `collection("preferences", Schema.String)` and `PreferenceFields` as `Schema.Struct({ title: Schema.String })`, and `PreferencesStore` is the application's persistence service. The browser binds the generated contract with the session's registry:
|
|
662
|
+
|
|
663
|
+
```ts
|
|
664
|
+
import { bind } from "@shivaedev/contract/bind.ts";
|
|
665
|
+
import { Preferences } from "#generated/modules/preferences/Preferences.ts";
|
|
633
666
|
|
|
634
667
|
const api = bind(Preferences, Client, { registry });
|
|
635
668
|
const self = api.self.query(undefined);
|
|
636
669
|
const save = api.save.run({ title: "My preferences" });
|
|
637
670
|
```
|
|
638
671
|
|
|
639
|
-
|
|
672
|
+
`Client` is the application's native AtomRpc service, and `registry` is the atom registry that owns the session's queries. In React, `SessionBoundary` supplies that registry to `connect`, as [react's session-scoped bindings](https://github.com/ShivaeDev/platform/blob/main/packages/react/README.md#session-scoped-bindings) show.
|
|
640
673
|
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
```ts
|
|
644
|
-
Preferences.application.toLayer({
|
|
645
|
-
"preferences.self": () => Effect.flatMap(Identity, ({ id }) => store.read(id)),
|
|
646
|
-
"preferences.save": ({ title }) => Effect.flatMap(Identity, ({ id }) => store.save(id, title)),
|
|
647
|
-
});
|
|
648
|
-
```
|
|
649
|
-
|
|
650
|
-
`store` is the application's persistence service. No owner or client key scope is accepted from a request. The database app host uses plain repository keys for every subscriber and rechecks each subscriber’s read policy before delivery.
|
|
674
|
+
No owner or client key scope is accepted from a request. The database app host uses plain repository keys for every subscriber and rechecks each subscriber’s read policy before delivery.
|
|
651
675
|
|
|
652
676
|
The registry is required for session-scoped bindings. Query atoms and live connections belong in it; command and one-off query Effects execute through it. Explicit streams also run through its client, preserving the session transport and headers; disposing the registry ends those streams. Streams on ordinary contracts use the caller's client. A successful command invalidates its registry's prefixed keys, while a rejected command declares no invalidation. Ordinary contracts keep unscoped keys and the two-argument `bind` call.
|
|
653
677
|
|
|
@@ -705,21 +729,22 @@ Server adapters import `LiveServer` from `@shivaedev/contract/live-server/servic
|
|
|
705
729
|
|
|
706
730
|
Contract groups carry their read-policy guard into native `RpcServer` hosts and Platform’s application host. An ordinary query evaluates its policy once per request, after identity middleware supplies `CurrentViewer` from its validated session. A false policy returns `QueryReadDenied` without running the handler. Native hosts need no policy middleware or guard Layer. Real HTTP stories exercise both hosts with allowed and denied counted policies; they prove this RPC boundary, not an application’s session or deployment policy. Platform’s application host refuses HTTP `$changes` calls with `WebSocketRequired`; subscriptions use its WebSocket protocol. Subscription delivery and pushed reruns continue to check current access.
|
|
707
731
|
|
|
708
|
-
A query
|
|
732
|
+
A query's `readPolicy(payload, viewer)` returns an Effect boolean, and a query declares `reads` only when its reads do not name its keys, as described below. `viewer` is the session's `Option<{ id: string }>`; the browser does not send the identity. `signedIn` from `readPolicy.ts` allows any signed-in viewer and refuses a signed-out viewer, and a query written with `run` that states no policy gets it. `QueryReadPolicy<Payload, E, R>` preserves typed failures and required services. A policy's typed failures join the query's rejections, so a failing access check reaches the client as that failure, including during live reads. Only a successful `false` denies access. [Policy services](#policy-services) explains richer session requirements and where to provide implementations.
|
|
709
733
|
|
|
710
734
|
```ts
|
|
711
|
-
import { Schema } from "effect";
|
|
712
735
|
import { query } from "@shivaedev/contract/operation.ts";
|
|
713
|
-
import {
|
|
736
|
+
import { NotesRepository, SessionUser } from "./services.ts";
|
|
714
737
|
|
|
715
738
|
const Mine = query("mine", {
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
739
|
+
*run() {
|
|
740
|
+
const repository = yield* NotesRepository;
|
|
741
|
+
const { id: userId } = yield* SessionUser;
|
|
742
|
+
return yield* repository.findMany({ select: ["title"], where: { userId } });
|
|
743
|
+
},
|
|
719
744
|
});
|
|
720
745
|
```
|
|
721
746
|
|
|
722
|
-
`Mine` declares no `reads`. Its
|
|
747
|
+
`Mine` declares no policy and no `reads`. Its `run` reads `findMany({ where: { userId } })` through a `@shivaedev/sql` repository, which names the viewer's `userId` bucket, so the live query listens on that bucket. On a repository model, annotate tenant fields with `bucket()` from `@shivaedev/changes/buckets.ts` so writes announce the affected buckets. For an admin page spanning every tenant, declare `readsCollections` beside a permission read policy:
|
|
723
748
|
|
|
724
749
|
```ts
|
|
725
750
|
import { Effect, Schema } from "effect";
|
|
@@ -729,14 +754,16 @@ import { query } from "@shivaedev/contract/operation.ts";
|
|
|
729
754
|
import { permissionReadPolicy } from "@shivaedev/contract/permissionReadPolicy.ts";
|
|
730
755
|
import { SessionUser } from "@shivaedev/identity/identity.ts";
|
|
731
756
|
import { hasPermission } from "@shivaedev/identity/permission.ts";
|
|
757
|
+
import { NotesRepository } from "./services.ts";
|
|
732
758
|
|
|
733
759
|
const notes = collection("notes", Schema.Number);
|
|
734
760
|
const ManageNotes = permission("notes.manage").any;
|
|
735
761
|
const AllNotes = query("allNotes", {
|
|
736
|
-
success: Schema.Array(Schema.String),
|
|
737
762
|
readPolicy: permissionReadPolicy(ManageNotes, (required) => Effect.map(SessionUser, (user) => hasPermission(user, required))),
|
|
738
|
-
reads: () => [],
|
|
739
763
|
readsCollections: [notes],
|
|
764
|
+
*run() {
|
|
765
|
+
return yield* (yield* NotesRepository).findMany({ select: ["title"] });
|
|
766
|
+
},
|
|
740
767
|
});
|
|
741
768
|
```
|
|
742
769
|
|
|
@@ -750,25 +777,26 @@ For dependencies that need server data, add `serverReads(payload, viewer)`, an E
|
|
|
750
777
|
import { Context, Effect, Schema } from "effect";
|
|
751
778
|
import type { Key } from "@shivaedev/changes/keys.ts";
|
|
752
779
|
import { query } from "@shivaedev/contract/operation.ts";
|
|
753
|
-
import { signedIn } from "@shivaedev/contract/readPolicy.ts";
|
|
754
780
|
|
|
755
781
|
class TimelineData extends Context.Service<
|
|
756
782
|
TimelineData,
|
|
757
783
|
{
|
|
784
|
+
readonly entries: (workspaceId: string) => Effect.Effect<readonly string[]>;
|
|
758
785
|
readonly readKeys: (workspaceId: string) => Effect.Effect<readonly Key[]>;
|
|
759
786
|
}
|
|
760
787
|
>()("app/TimelineData") {}
|
|
761
788
|
|
|
762
789
|
const Timeline = query("timeline", {
|
|
763
790
|
payload: { workspaceId: Schema.String },
|
|
764
|
-
success: Schema.Array(Schema.String),
|
|
765
|
-
readPolicy: signedIn,
|
|
766
791
|
reads: () => [],
|
|
767
792
|
serverReads: ({ workspaceId }) => Effect.flatMap(TimelineData, (data) => data.readKeys(workspaceId)),
|
|
793
|
+
*run({ workspaceId }) {
|
|
794
|
+
return yield* (yield* TimelineData).entries(workspaceId);
|
|
795
|
+
},
|
|
768
796
|
});
|
|
769
797
|
```
|
|
770
798
|
|
|
771
|
-
Provide `TimelineData` on the server to
|
|
799
|
+
Provide `TimelineData` on the server to read the workspace's entries, and to load its lists and return their keys. Use an application policy that checks workspace access; derived keys are refresh dependencies and grant no read access. Each write must publish the same keys. After every rerun the server evaluates `reads` and `serverReads` again and replaces the subscription's registrations, so the keys follow the workspace while the subscription stays open. A list that joins is watched once a rerun has seen it, so the write that adds a list must publish a key the query already reads, such as a workspace bucket that `serverReads` also returns. Once a rerun has seen a list leave, that list's writes no longer rerun the query. The browser never runs `serverReads`; matching changes rerun the affected query on the server.
|
|
772
800
|
|
|
773
801
|
A handler can also name keys while it runs, with `recordRead(keys)` from `@shivaedev/changes/readRecorder.ts`, before the statement that reads by them. The live subscription registers each recorded key with the host the moment it is recorded, before that statement is sent, and matches it alongside the keys from `reads`, `serverReads` and `readsCollections`. A key recorded on a rerun is therefore watched before its read, where a `serverReads` key is watched only once the rerun has finished. A key that is already registered is not registered again, so a handler that reads the same row many times registers its key once. Nothing the query's read policy records counts, whether through repository reads or its own `recordRead` calls: permission changes refresh nothing live, so a write to a row only the policy reads does not rerun the query.
|
|
774
802
|
|
|
@@ -783,7 +811,13 @@ import { Context, Effect, Option, Schema } from "effect";
|
|
|
783
811
|
import { query } from "@shivaedev/contract/operation.ts";
|
|
784
812
|
import { NotFound } from "@shivaedev/errors/taxonomy.ts";
|
|
785
813
|
|
|
786
|
-
class
|
|
814
|
+
class PrivateNotes extends Context.Service<
|
|
815
|
+
PrivateNotes,
|
|
816
|
+
{
|
|
817
|
+
readonly owner: (id: number) => Effect.Effect<Option.Option<string>>;
|
|
818
|
+
readonly title: (id: number) => Effect.Effect<string>;
|
|
819
|
+
}
|
|
820
|
+
>()("app/PrivateNotes") {}
|
|
787
821
|
const PrivateNote = query("privateNote", {
|
|
788
822
|
payload: { id: Schema.Number },
|
|
789
823
|
readPolicy: ({ id }, viewer) =>
|
|
@@ -791,40 +825,41 @@ const PrivateNote = query("privateNote", {
|
|
|
791
825
|
if (Option.isNone(viewer)) {
|
|
792
826
|
return false;
|
|
793
827
|
}
|
|
794
|
-
const owner = yield* (yield*
|
|
828
|
+
const owner = yield* (yield* PrivateNotes).owner(id);
|
|
795
829
|
if (Option.isNone(owner) || owner.value !== viewer.value.id) {
|
|
796
830
|
return yield* new NotFound({ message: "Note not found" });
|
|
797
831
|
}
|
|
798
832
|
return true;
|
|
799
833
|
}),
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
834
|
+
*run({ id }) {
|
|
835
|
+
return yield* (yield* PrivateNotes).title(id);
|
|
836
|
+
},
|
|
803
837
|
});
|
|
804
838
|
```
|
|
805
839
|
|
|
806
|
-
The
|
|
840
|
+
The module's registration provides `PrivateNotes`; the browser's generated contract carries no read policy. The generator lists the policy's `NotFound` among the query's rejections, and the same typed rejection reaches ordinary reads and live subscriptions.
|
|
807
841
|
|
|
808
842
|
A record key, `notes.item(id)`, names one record. A bucket, `notes.bucket.userId(id)`, names every row with that field value. Declare bucket fields on the collection model with their schemas. A list may add title, state or other filters to its input and handler, but those filters never narrow its bucket. It reruns whenever any row in that bucket changes, including a row excluded by the filter. Writers explicitly announce the record and affected buckets with the same constructors from `@shivaedev/changes/keys.ts`.
|
|
809
843
|
|
|
810
|
-
The same query policy guards running the query and subscribing to it. A subscription is meant to carry one query. It names query references, never arbitrary record or bucket keys. If a subscription mixes queries the viewer may and may not read, the entire subscription is refused with `QueryReadDenied`; it delivers no partial results. Every query
|
|
844
|
+
The same query policy guards running the query and subscribing to it. A subscription is meant to carry one query. It names query references, never arbitrary record or bucket keys. If a subscription mixes queries the viewer may and may not read, the entire subscription is refused with `QueryReadDenied`; it delivers no partial results. Every query has a policy: one written with `run` gets `signedIn` when it states none, and one declared without run requires `readPolicy`, including queries used only through one-off `run` calls, so TypeScript rejects a policy-less declaration before handlers or a live server can be built. Platform’s application host validates the complete RPC group while building its Layer, before listening; untyped declarations missing policies fail with `MissingReadPolicies`, whose `queries` and `message` name every affected RPC. Native hosts enforce read policies automatically at request time. `MissingReadPolicy` remains a request-time refusal for untyped declarations served through native servers that bypass that boot check, on plain calls and subscriptions alike. Reads outside a declared query acquire no automatic subscription.
|
|
811
845
|
|
|
812
846
|
Session middleware supplies `CurrentViewer` after validating the session. Each rerun uses a freshly loaded session and the same authorized handler as an ordinary read. A removed session ends the subscription with `Unauthorized`; a current session denied by the read policy receives `QueryReadDenied`, with no query SQL and its stored hash cleared. The established subscription stays open for later authorized changes. Raw consumers handle `Result`, `Unchanged` and `QueryReadDenied`.
|
|
813
847
|
|
|
814
848
|
### Policy services
|
|
815
849
|
|
|
816
|
-
Use the policy's `viewer` argument for the viewer ID. Read richer session context from Effect requirements. For example, a policy service can require `SessionUserWithProviderAccounts` from `@shivaedev/identity/identity.ts` and yield its `providerAccounts` Effect. Apply `AuthenticatedUserWithProviderAccounts` middleware to the
|
|
850
|
+
Use the policy's `viewer` argument for the viewer ID. Read richer session context from Effect requirements. For example, a policy service can require `SessionUserWithProviderAccounts` from `@shivaedev/identity/identity.ts` and yield its `providerAccounts` Effect. Apply `AuthenticatedUserWithProviderAccounts` middleware to the module and merge `authenticatedUserWithProviderAccountsLayer()` from `@shivaedev/identity/server/session.ts` into the handlers the host serves, with the shared `SessionPolicy` Layer provided once by the application host. The middleware provides this request-local context for both RPC calls and live reruns, including each policy recheck before a result is delivered. Session-backed hosts reload that context before each rerun, and use the same snapshot for its policy and query rerun.
|
|
817
851
|
|
|
818
|
-
Keep the policy service tag
|
|
852
|
+
Keep the policy service's tag beside the query and its implementation in server code. Its method retains the session service in its requirements so the session is read when the policy runs:
|
|
819
853
|
|
|
820
854
|
```ts
|
|
821
855
|
import { Context, Effect, Option, Schema } from "effect";
|
|
822
|
-
import {
|
|
856
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
823
857
|
import { query } from "@shivaedev/contract/operation.ts";
|
|
824
858
|
import type { Viewer } from "@shivaedev/contract/readPolicy.ts";
|
|
825
859
|
import { AuthUnavailable, Unauthorized } from "@shivaedev/errors/taxonomy.ts";
|
|
826
860
|
import { SessionUserWithProviderAccounts } from "@shivaedev/identity/identity.ts";
|
|
827
861
|
import { AuthenticatedUserWithProviderAccounts } from "@shivaedev/identity/middleware.ts";
|
|
862
|
+
import { documentsWire } from "#generated/modules/documents/Documents.ts";
|
|
828
863
|
|
|
829
864
|
class ReadAccess extends Context.Service<
|
|
830
865
|
ReadAccess,
|
|
@@ -839,17 +874,23 @@ class ReadAccess extends Context.Service<
|
|
|
839
874
|
const Get = query("get", {
|
|
840
875
|
payload: { accountId: Schema.String },
|
|
841
876
|
readPolicy: ({ accountId }, viewer) => Effect.flatMap(ReadAccess, (access) => access.allows(accountId, viewer)),
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
877
|
+
*run({ accountId }) {
|
|
878
|
+
return yield* Effect.succeed(`Document for ${accountId}`);
|
|
879
|
+
},
|
|
880
|
+
});
|
|
881
|
+
export const Documents = defineModule({
|
|
882
|
+
middleware: AuthenticatedUserWithProviderAccounts,
|
|
883
|
+
name: "documents",
|
|
884
|
+
operations: [Get],
|
|
885
|
+
wire: documentsWire,
|
|
845
886
|
});
|
|
846
|
-
const Documents = contract("documents", { queries: [Get] }).middleware(AuthenticatedUserWithProviderAccounts);
|
|
847
887
|
```
|
|
848
888
|
|
|
849
|
-
|
|
889
|
+
The generator lists the policy's `AuthUnavailable` and `Unauthorized` among the query's rejections. Provide the implementation from the module's registration:
|
|
850
890
|
|
|
851
891
|
```ts
|
|
852
892
|
import { Effect, Layer, Option } from "effect";
|
|
893
|
+
import type { AppModule } from "@shivaedev/server/AppModule.ts";
|
|
853
894
|
|
|
854
895
|
const ReadAccessLive = Layer.succeed(ReadAccess, {
|
|
855
896
|
allows: (accountId, viewer) =>
|
|
@@ -863,14 +904,10 @@ const ReadAccessLive = Layer.succeed(ReadAccess, {
|
|
|
863
904
|
);
|
|
864
905
|
}),
|
|
865
906
|
});
|
|
866
|
-
const
|
|
867
|
-
.toLayer({
|
|
868
|
-
"documents.get": ({ accountId }) => Effect.succeed(`Document for ${accountId}`),
|
|
869
|
-
})
|
|
870
|
-
.pipe(Layer.provide(ReadAccessLive));
|
|
907
|
+
export const documents = { module: Documents, services: ReadAccessLive } satisfies AppModule;
|
|
871
908
|
```
|
|
872
909
|
|
|
873
|
-
The
|
|
910
|
+
The module's handlers check the policy with the services the registration provides, for RPC calls and subscriptions alike. Request-local services take precedence over those services; a session value installed while building the handlers cannot replace the current viewer's session. The policy runs again for live reruns; its allow or deny result is not cached.
|
|
874
911
|
|
|
875
912
|
### In-memory clients in story kits
|
|
876
913
|
|
|
@@ -913,43 +950,43 @@ Observe raw result streams with `watchHints` from `@shivaedev/test-kits/contract
|
|
|
913
950
|
|
|
914
951
|
Import the module that defines the name; the package has no root entry.
|
|
915
952
|
|
|
916
|
-
| Module | Functions and schemas
|
|
917
|
-
| -------------------------- |
|
|
918
|
-
| `operation.ts` | `query(name, { payload?, *run, readPolicy?, reads?, serverReads?, readsCollections? })` and `command(name, { payload?, *run, invalidates?(payload, viewer?) })` with an Effect-returning `run`; declared without run: `query(name, { payload?, success?, rejections?, readPolicy, reads?, serverReads? })`, `command(name, { payload?, success?, rejections?, invalidates(payload, result, viewer?) })` and `stream(name, { payload?, success, rejections?, reads })`.
|
|
919
|
-
| `contract.ts` | `contract(name, { queries?, commands?, streams?, keyScope? })`, returning a native RPC group with `declaration: { name, queries, commands, streams, keyScope }`.
|
|
920
|
-
| `defineModule.ts` | `defineModule({ name, operations,
|
|
921
|
-
| `moduleHandlers.ts` | `moduleHandlers(module)`, the module's handler Layer, requiring exactly its
|
|
922
|
-
| `clientContract.ts` | `clientContract({ name, wire, payloads?, queries?, commands?, middleware?, subject?, keyScope? })`, the browser's contract of a module that generated files build.
|
|
923
|
-
| `clientMatchesModule.ts` | `ClientMatchesModule<Client, Module>`, `true` when the browser's contract and the server module have the same RPCs, else `ClientDiffersFromModule`.
|
|
924
|
-
| `rejection.ts` | `fieldRejection(struct, fields?)`; lower-level `rejectionSet(specs)`, which constructs the rejection classes, union schema and failure helpers used by operations.
|
|
925
|
-
| `bind.ts` | `bind(contract, atomRpcService, { registry?, live?, resume?, resumeWindow? }?)`, requiring the registry for session-scoped contracts and exposing `{ query, run }` for queries, `{ run }`
|
|
926
|
-
| `clientKeys.ts` | `KeyContext`, `clientReadKeys`, `clientInvalidationKeys`: registry-local cache keys for custom clients.
|
|
927
|
-
| `live.ts` | `LiveHint` schema; `live(runtime, { stream, keyContext?, resume?, retryDelay?, retryKeys? })`, exposing `connection`, `paused` and `status`; `isLiveConnection(atom)` tells whether an atom is such a `connection`, which waits for as long as its subscription runs.
|
|
928
|
-
| `querySubscription.ts` | `querySubscription(rpc, references, viewer)` checks each referenced query, resolves its payload and server-derived keys, and captures its scopes and ongoing authorization.
|
|
929
|
-
| `live-server/service.ts` | `LiveServer`, the shared live server service.
|
|
930
|
-
| `live-server/layer.ts` | `liveServerLayer`, providing `LiveServer` and its dispatcher dependency, requiring `Reactivity`.
|
|
931
|
-
| `live-server/subscribe.ts` | `subscribe(subscription, read?)`, an Effect requiring `LiveServer` that returns an authorized subscription Stream with its policy and query-runner requirements.
|
|
932
|
-
| `makeLiveServer.ts` | `makeLiveServer`, an Effect requiring `Reactivity` that creates scoped server hint streams, a `resync` Effect and `synced(token)`.
|
|
933
|
-
| `readPolicy.ts` | `QueryReadPolicy`, `Viewer`, `signedIn`, `CurrentViewer`; `authorizeReads(effect, request, viewer)` for direct handler reruns outside RPC middleware.
|
|
934
|
-
| `ReadPolicyGuard.ts` | `ReadPolicyGuard`, the defaulted middleware reference attached to contract queries; `readPolicyGuardLayer({ websocket? })`, an optional override that refuses HTTP `$changes` calls by default.
|
|
935
|
-
| `validateReadPolicies.ts` | `validateReadPolicies(group)`, an Effect that fails with `MissingReadPolicies` when any served or subscribable query omits its policy.
|
|
936
|
-
| `readPolicyErrors.ts` | `MissingReadPolicies` (boot), `MissingReadPolicy` (native-server request fallback) and `QueryReadDenied`.
|
|
937
|
-
| `CommandGuard.ts` | `guardCommands(group)` places command publication inside viewer-providing middleware; `commandGuardLayer(boundary)` evaluates declared invalidations for that viewer and delegates publication to the host boundary.
|
|
938
|
-
| `commandResult.ts` | `commandResult({ result, invalidates })` contributes server-only keys from a guarded command's `run` or handler and returns only its success value.
|
|
939
|
-
| `serverMetadata.ts` | `QueryDefinition.definition`, `CommandInvalidation.invalidates`, `ChangesQueries.queries`, `ChangesQueries.resolve(references)` and `changesRpc(name, queries)` for server adapters.
|
|
940
|
-
| `queryKeys.ts` | `queryKeys(queries, references, viewer?)` authorizes references and resolves payload and server-derived keys using the provided services.
|
|
941
|
-
| `QueryServerReads.ts` | `QueryServerReads<Payload, E, R>`, the server-only resolver type.
|
|
942
|
-
| `resume.ts` | `resumeSignal({ window?, native? })`, returning a native numeric signal atom.
|
|
943
|
-
| `querySignals.ts` | `querySignals(query)` exposes completion counts and subscription status as a native atom.
|
|
944
|
-
| `retainQuery.ts` | `queryRuntime(query)` returns the atom runtime a bound query runs on, so a reader can schedule work on the same Effect `Clock`.
|
|
945
|
-
| `clientActivity.ts` | `clientActivity(client)` exposes a native activity Stream with a `current` Effect; `isClientSettled(state)` checks commands, commands not yet reflected and first query results; `isClientIdle(state)` checks all finite work; `activityScreenSignal(activity, settled?)` projects pending work for screen waits.
|
|
946
|
-
| `commandSignal.ts` | `untilReflected(command)` completes a command's Effect when it is reflected; `CommandSignal` receives each `CommandState`.
|
|
947
|
-
| `LiveSync.ts` | `LiveSync`, the host's contract of the `platform.liveSync.request` command that carries a sync token and writes nothing. Browser code takes the same command from `liveSyncRpc.ts`.
|
|
948
|
-
| `liveSyncRpc.ts` | `liveSyncRpc`, the RPC group a client declares for that command without importing its operation file, and `LIVE_SYNC`, its tag.
|
|
949
|
-
| `syncHeader.ts` | `syncClient(headers)` and `syncToken(headers)` read the client name and the sync token a request carries.
|
|
950
|
-
| `operationKind.ts` | `operationKind(rpc)`: `"read"` for a query, a changes stream or a stream, `"write"` for a command or an RPC no contract marked.
|
|
951
|
-
| `subjectHeader.ts` | `subjectHeader(headers)` reads the account a call names; `withSubject(headers, subject)` and `subjectSerializationKey(key, headers)` are what bound operations use to send it and to keep serialized results apart.
|
|
952
|
-
| `screenSync.ts` | `screenSync(client, registry)` runs a client's `sync` through a registry, for a screen driver's `sync` option.
|
|
953
|
+
| Module | Functions and schemas |
|
|
954
|
+
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
955
|
+
| `operation.ts` | `query(name, { payload?, *run, readPolicy?, reads?, serverReads?, readsCollections? })` and `command(name, { payload?, *run, invalidates?(payload, viewer?) })` with an Effect-returning `run`; declared without run: `query(name, { payload?, success?, rejections?, readPolicy, reads?, serverReads? })`, `command(name, { payload?, success?, rejections?, invalidates(payload, result, viewer?) })` and `stream(name, { payload?, success, rejections?, reads })`. |
|
|
956
|
+
| `contract.ts` | `contract(name, { queries?, commands?, streams?, keyScope? })`, returning a native RPC group with `declaration: { name, queries, commands, streams, keyScope }`. |
|
|
957
|
+
| `defineModule.ts` | `defineModule({ name, operations, wire, middleware?, subject?, keyScope? })`, returning the module's contract, whose type carries the services each operation yields. |
|
|
958
|
+
| `moduleHandlers.ts` | `moduleHandlers(module)`, the module's handler Layer, requiring exactly the services its operations yield beyond its middleware and subject. |
|
|
959
|
+
| `clientContract.ts` | `clientContract({ name, wire, payloads?, queries?, commands?, middleware?, subject?, keyScope? })`, the browser's contract of a module that generated files build. |
|
|
960
|
+
| `clientMatchesModule.ts` | `ClientMatchesModule<Client, Module>`, `true` when the browser's contract and the server module have the same RPCs, else `ClientDiffersFromModule`. |
|
|
961
|
+
| `rejection.ts` | `fieldRejection(struct, fields?)`; lower-level `rejectionSet(specs)`, which constructs the rejection classes, union schema and failure helpers used by operations. |
|
|
962
|
+
| `bind.ts` | `bind(contract, atomRpcService, { registry?, live?, resume?, resumeWindow? }?)`, requiring the registry for session-scoped contracts and exposing `{ query, run, runtime }` for queries, `{ run, payload, runtime }` for commands and `{ run, runtime }` with native Streams for streams; `makeClient(contract, { url, protocol?, headers?, webSocketConstructor?, group?, registry?, live?, resume?, resumeWindow? })`, which builds the shared WebSocket client and binds it, with `sync` beside `api`. |
|
|
963
|
+
| `clientKeys.ts` | `KeyContext`, `clientReadKeys`, `clientInvalidationKeys`: registry-local cache keys for custom clients. |
|
|
964
|
+
| `live.ts` | `LiveHint` schema; `live(runtime, { stream, keyContext?, resume?, retryDelay?, retryKeys? })`, exposing `connection`, `paused` and `status`; `isLiveConnection(atom)` tells whether an atom is such a `connection`, which waits for as long as its subscription runs. |
|
|
965
|
+
| `querySubscription.ts` | `querySubscription(rpc, references, viewer)` checks each referenced query, resolves its payload and server-derived keys, and captures its scopes and ongoing authorization. |
|
|
966
|
+
| `live-server/service.ts` | `LiveServer`, the shared live server service. |
|
|
967
|
+
| `live-server/layer.ts` | `liveServerLayer`, providing `LiveServer` and its dispatcher dependency, requiring `Reactivity`. |
|
|
968
|
+
| `live-server/subscribe.ts` | `subscribe(subscription, read?)`, an Effect requiring `LiveServer` that returns an authorized subscription Stream with its policy and query-runner requirements. |
|
|
969
|
+
| `makeLiveServer.ts` | `makeLiveServer`, an Effect requiring `Reactivity` that creates scoped server hint streams, a `resync` Effect and `synced(token)`. |
|
|
970
|
+
| `readPolicy.ts` | `QueryReadPolicy`, `Viewer`, `signedIn`, `CurrentViewer`; `authorizeReads(effect, request, viewer)` for direct handler reruns outside RPC middleware. |
|
|
971
|
+
| `ReadPolicyGuard.ts` | `ReadPolicyGuard`, the defaulted middleware reference attached to contract queries; `readPolicyGuardLayer({ websocket? })`, an optional override that refuses HTTP `$changes` calls by default. |
|
|
972
|
+
| `validateReadPolicies.ts` | `validateReadPolicies(group)`, an Effect that fails with `MissingReadPolicies` when any served or subscribable query omits its policy. |
|
|
973
|
+
| `readPolicyErrors.ts` | `MissingReadPolicies` (boot), `MissingReadPolicy` (native-server request fallback) and `QueryReadDenied`. |
|
|
974
|
+
| `CommandGuard.ts` | `guardCommands(group)` places command publication inside viewer-providing middleware; `commandGuardLayer(boundary)` evaluates declared invalidations for that viewer and delegates publication to the host boundary. |
|
|
975
|
+
| `commandResult.ts` | `commandResult({ result, invalidates })` contributes server-only keys from a guarded command's `run` or handler and returns only its success value. |
|
|
976
|
+
| `serverMetadata.ts` | `QueryDefinition.definition`, `CommandInvalidation.invalidates`, `ChangesQueries.queries`, `ChangesQueries.resolve(references)` and `changesRpc(name, queries)` for server adapters. |
|
|
977
|
+
| `queryKeys.ts` | `queryKeys(queries, references, viewer?)` authorizes references and resolves payload and server-derived keys using the provided services. |
|
|
978
|
+
| `QueryServerReads.ts` | `QueryServerReads<Payload, E, R>`, the server-only resolver type. |
|
|
979
|
+
| `resume.ts` | `resumeSignal({ window?, native? })`, returning a native numeric signal atom. |
|
|
980
|
+
| `querySignals.ts` | `querySignals(query)` exposes completion counts and subscription status as a native atom. |
|
|
981
|
+
| `retainQuery.ts` | `queryRuntime(query)` returns the atom runtime a bound query runs on, so a reader can schedule work on the same Effect `Clock`. |
|
|
982
|
+
| `clientActivity.ts` | `clientActivity(client)` exposes a native activity Stream with a `current` Effect; `isClientSettled(state)` checks commands, commands not yet reflected and first query results; `isClientIdle(state)` checks all finite work; `activityScreenSignal(activity, settled?)` projects pending work for screen waits. |
|
|
983
|
+
| `commandSignal.ts` | `untilReflected(command)` completes a command's Effect when it is reflected; `CommandSignal` receives each `CommandState`. |
|
|
984
|
+
| `LiveSync.ts` | `LiveSync`, the host's contract of the `platform.liveSync.request` command that carries a sync token and writes nothing. Browser code takes the same command from `liveSyncRpc.ts`. |
|
|
985
|
+
| `liveSyncRpc.ts` | `liveSyncRpc`, the RPC group a client declares for that command without importing its operation file, and `LIVE_SYNC`, its tag. |
|
|
986
|
+
| `syncHeader.ts` | `syncClient(headers)` and `syncToken(headers)` read the client name and the sync token a request carries. |
|
|
987
|
+
| `operationKind.ts` | `operationKind(rpc)`: `"read"` for a query, a changes stream or a stream, `"write"` for a command or an RPC no contract marked. |
|
|
988
|
+
| `subjectHeader.ts` | `subjectHeader(headers)` reads the account a call names; `withSubject(headers, subject)` and `subjectSerializationKey(key, headers)` are what bound operations use to send it and to keep serialized results apart. |
|
|
989
|
+
| `screenSync.ts` | `screenSync(client, registry)` runs a client's `sync` through a registry, for a screen driver's `sync` option. |
|
|
953
990
|
|
|
954
991
|
A bound query’s optional second argument accepts `headers`, `subject` and `serializationKey`. Successful results remain in their owning registry for five minutes after the last reader leaves, up to 100 idle queries, evicting the least recently left first. Reopening a query immediately returns the retained success with native `waiting: true` while a new subscription or read supplies fresh data. Execution stops between readers. Configure the registry’s `queryRetention` atom from `@shivaedev/contract/queryRetention.ts` with `{ timeToLive: "1 minute", capacity: 50 }`, or set React’s `SessionBoundary` prop of the same name. Zero for either disables idle retention. Expiry runs on the query runtime’s Effect Clock. Registry disposal clears all retained results; applications outside `SessionBoundary` own that disposal when their session changes. A native resume source receives a callback and returns a cleanup function.
|
|
955
992
|
|