@shivaedev/contract 0.54.0 → 0.55.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.
Files changed (72) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +93 -87
  3. package/dist/ClientOptions.d.ts +18 -0
  4. package/dist/ClientOptions.d.ts.map +1 -0
  5. package/dist/ClientOptions.js +2 -0
  6. package/dist/ClientOptions.js.map +1 -0
  7. package/dist/adapters/bindingOwner.d.ts +0 -2
  8. package/dist/adapters/bindingOwner.d.ts.map +1 -1
  9. package/dist/adapters/bindingOwner.js +1 -8
  10. package/dist/adapters/bindingOwner.js.map +1 -1
  11. package/dist/automaticLive.d.ts +2 -3
  12. package/dist/automaticLive.d.ts.map +1 -1
  13. package/dist/automaticLive.js +2 -8
  14. package/dist/automaticLive.js.map +1 -1
  15. package/dist/automaticQuery.d.ts.map +1 -1
  16. package/dist/automaticQuery.js +8 -0
  17. package/dist/automaticQuery.js.map +1 -1
  18. package/dist/bind.d.ts +1 -10
  19. package/dist/bind.d.ts.map +1 -1
  20. package/dist/bind.js +1 -12
  21. package/dist/bind.js.map +1 -1
  22. package/dist/clientOperations.d.ts.map +1 -1
  23. package/dist/clientOperations.js +17 -16
  24. package/dist/clientOperations.js.map +1 -1
  25. package/dist/commandReflected.d.ts +2 -0
  26. package/dist/commandReflected.d.ts.map +1 -0
  27. package/dist/commandReflected.js +3 -0
  28. package/dist/commandReflected.js.map +1 -0
  29. package/dist/live.d.ts +0 -4
  30. package/dist/live.d.ts.map +1 -1
  31. package/dist/live.js +6 -2
  32. package/dist/live.js.map +1 -1
  33. package/dist/makeClient.d.ts +41 -0
  34. package/dist/makeClient.d.ts.map +1 -0
  35. package/dist/makeClient.js +25 -0
  36. package/dist/makeClient.js.map +1 -0
  37. package/dist/queryProgress.d.ts +1 -3
  38. package/dist/queryProgress.d.ts.map +1 -1
  39. package/dist/queryProgress.js +0 -22
  40. package/dist/queryProgress.js.map +1 -1
  41. package/dist/retryOnChange.d.ts.map +1 -1
  42. package/dist/retryOnChange.js +4 -0
  43. package/dist/retryOnChange.js.map +1 -1
  44. package/dist/rpcClient.d.ts +1 -1
  45. package/dist/rpcClient.d.ts.map +1 -1
  46. package/dist/rpcClient.js +4 -1
  47. package/dist/rpcClient.js.map +1 -1
  48. package/dist/socketProtocol.d.ts +1 -1
  49. package/package.json +6 -6
  50. package/src/ClientOptions.ts +18 -0
  51. package/src/adapters/bindingOwner.ts +1 -11
  52. package/src/automaticLive.ts +0 -10
  53. package/src/automaticQuery.ts +8 -0
  54. package/src/bind.ts +3 -39
  55. package/src/clientOperations.ts +17 -22
  56. package/src/commandReflected.ts +2 -0
  57. package/src/live.ts +6 -4
  58. package/src/makeClient.ts +78 -0
  59. package/src/queryProgress.ts +1 -24
  60. package/src/retryOnChange.ts +4 -0
  61. package/src/rpcClient.ts +7 -2
  62. package/src/socketProtocol.ts +1 -1
  63. package/dist/clientKeys.d.ts +0 -7
  64. package/dist/clientKeys.d.ts.map +0 -1
  65. package/dist/clientKeys.js +0 -11
  66. package/dist/clientKeys.js.map +0 -1
  67. package/dist/clientOptions.d.ts +0 -31
  68. package/dist/clientOptions.d.ts.map +0 -1
  69. package/dist/clientOptions.js +0 -2
  70. package/dist/clientOptions.js.map +0 -1
  71. package/src/clientKeys.ts +0 -17
  72. package/src/clientOptions.ts +0 -44
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.55.0 - 2026-11-21
4
+
5
+ ### Changed
6
+
7
+ - a live subscription that failed with something other than `QueryReadDenied` reopens after the client's next reflected command, whatever keys that command declares. It used to reopen on a matching key the browser invalidated.
8
+
9
+ ### Breaking
10
+
11
+ - every bound query subscribes to the server's changes. `bind` and `makeClient` no longer take `live`; delete `live: false` from their options. Over HTTP a bound operation's `run` still makes one call, and a bound query's atom fails with `WebSocketRequired`, so serve a screen's queries over the WebSocket client from `makeClient`.
12
+ - the browser no longer refreshes queries itself. A successful command no longer invalidates its declared keys or its contract's key in the client's `Reactivity`, so an atom that listened there for a command's keys no longer reruns; read the query through a binding, whose subscription receives the server's new result.
13
+ - `@shivaedev/contract/clientKeys.ts` is removed, with `clientReadKeys`, `clientInvalidationKeys` and `KeyContext`. Delete their imports; the server's keys from `@shivaedev/changes/keys.ts` are the only keys.
14
+ - `queryProgress()` from `@shivaedev/contract/queryProgress.ts`, the `keyContext` and `retryKeys` options of `live()` from `@shivaedev/contract/live.ts`, and the positional `enabled` parameter of `automaticLive` from `@shivaedev/contract/automaticLive.ts` are removed. Delete them where you pass or call them; nothing replaces them.
15
+
16
+ ## 0.54.1 - 2026-11-21
17
+
18
+ ### Fixed
19
+
20
+ - a live query that failed and is refreshed or retried shows its failure as waiting while its subscription reopens, instead of a settled failure.
21
+
3
22
  ## 0.54.0 - 2026-11-21
4
23
 
5
24
  ### Added
package/README.md CHANGED
@@ -41,7 +41,7 @@ export const Notes = defineModule({ name: "notes", operations: [List, Rename], w
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 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.
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 **client** is one native AtomRpc client made from a record of contracts, and each contract in the record gets a **binding**: queries get native query atoms that subscribe to the server's changes, and call Effects; commands get call Effects whose changes the server pushes to the queries they affect.
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
 
@@ -177,7 +177,7 @@ export const Notes = defineModule({
177
177
  });
178
178
  ```
179
179
 
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
+ 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 `makeClient`, `bind` 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:
181
181
 
182
182
  ```
183
183
  src/test-support/fixtures/invalid/moduleRepeatedName.ts(15,2): error TS2322: Type '"lists"' is not assignable to type '"lists" & NoInfer<OperationNameRepeated<"list">>'.
@@ -231,7 +231,7 @@ export const Notes = clientContract({
231
231
  export const notesMatchModule: ClientMatchesModule<typeof Notes, typeof NotesModule> = true;
232
232
  ```
233
233
 
234
- `clientContract` requires a wire entry for every query and command it declares. The browser imports `Notes` from that file and binds it like any contract; it carries no `run`, read policy or service, and its import graph reaches no server code. A command's `invalidates` and a query's `reads` work in the browser exactly as on the server. Over RPC's JSON serialization, a `Schema.Date` field arrives as a `Date` equal to the one `run` returned, and a rejection the wire lists arrives as its class. Neither the browser's contract nor an operation without a read policy can be served: `contract()` requires one on every query, and a host refuses a query without one at start-up.
234
+ `clientContract` requires a wire entry for every query and command it declares. The browser imports `Notes` from that file and binds it like any contract; it carries no `run`, read policy or service, and its import graph reaches no server code. Over RPC's JSON serialization, a `Schema.Date` field arrives as a `Date` equal to the one `run` returned, and a rejection the wire lists arrives as its class. Neither the browser's contract nor an operation without a read policy can be served: `contract()` requires one on every query, and a host refuses a query without one at start-up.
235
235
 
236
236
  The compiler compares the wire with `run` on every type check, and a stale file is an error on the module's `name` line that names the operation, one problem per operation: `WireSuccessStale` when the entry's success differs from what `run` returns, `WireRejectionsStale` when its rejection tags or classes differ from what `run` and a query's read policy raise, other than infrastructure failures, and `OperationMissingFromWire` when an operation has no entry and its `run` returns a value or raises a rejection. A success differs when its type and `run`'s return type are not mutually assignable; when they differ only in array mutability, because `Schema.Array` decodes a readonly array; when an object that `run` returns and a `Schema.Struct` that the success holds in the same position, at the top or in an array, struct field, tuple, record, union or `Option`, have different keys, such as an optional property only one of them has, which the `Struct` would drop or never send; and when the success holds a `Schema.Class` in such a position and `run` returns something other than that class there, such as an object literal of its fields, which fails to encode. Rejections differ when `run` raises a tag the entry does not list, the entry lists a tag nothing raises or one of the automatic two, or a listed class and the class `run` raises under the same tag differ in shape, such as a local `NotFound` with other fields than the shared one.
237
237
 
@@ -293,7 +293,7 @@ export const Create = command("create", {
293
293
  export const Notes = contract("notes", { queries: [Get, List], commands: [Rename, Create] });
294
294
  ```
295
295
 
296
- Save this module as `notes.ts`. The payload can be struct fields, as in `Get`, or a schema, as in `Create`. An omitted payload or success is `Schema.Void`; no declared rejections gives `Schema.Never`. A declared query requires `readPolicy`, and a declared command requires `invalidates`. The server resolves `reads` with the decoded payload and session viewer. For local command dependencies, the browser also evaluates it with `Option.none()`; return no viewer keys for that case. Authorized subscription scopes always come from the server. A declared command's `invalidates` receives the decoded payload, successful result and optional session viewer, so a create call can invalidate the ID the server assigned.
296
+ Save this module as `notes.ts`. The payload can be struct fields, as in `Get`, or a schema, as in `Create`. An omitted payload or success is `Schema.Void`; no declared rejections gives `Schema.Never`. A declared query requires `readPolicy`, and a declared command requires `invalidates`. The server resolves `reads` with the decoded payload and session viewer. Authorized subscription scopes always come from the server. A declared command's `invalidates` receives the decoded payload, successful result and optional session viewer, so a create call can invalidate the ID the server assigned.
297
297
 
298
298
  The collection's ID schema gives `item` its ID type. Here, `notes.item` takes a number. Query and command callbacks retain their payload and result types, including when the operations are declared inline inside `contract`.
299
299
 
@@ -444,24 +444,35 @@ export class NotesClient extends AtomRpc.Service<NotesClient>()("app/NotesClient
444
444
  Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),
445
445
  ),
446
446
  }) {}
447
- export const api = bind(Notes, NotesClient, { live: false });
447
+ export const api = bind(Notes, NotesClient);
448
448
  ```
449
449
 
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.
450
+ Over HTTP, each bound operation's `run` makes one call, so `api.rename.run(...)` and `api.get.run(...)` work. A bound query's atom subscribes to the server's change stream, which needs a WebSocket: over HTTP it fails with `WebSocketRequired`, so a screen that mounts queries uses the shared WebSocket client below. 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.
451
451
 
452
452
  ### Build a shared WebSocket client
453
453
 
454
- Use `makeClient` once per session to build a native AtomRpc client and bind the contract. Clients for the same identified session, URL and upgrade options share Effect RPC's socket protocol, including when they bind different contracts or use independent registries.
454
+ Use `makeClient` once per session with a record of the contracts the browser calls. It builds one native AtomRpc client over all of them, with one activity and one atom runtime, and binds each contract under its key. Clients for the same identified session, URL and upgrade options share Effect RPC's socket protocol, so a second client opens no second socket.
455
455
 
456
456
  ```ts
457
- import { makeClient } from "@shivaedev/contract/bind.ts";
457
+ import { makeClient } from "@shivaedev/contract/makeClient.ts";
458
458
  import { Notes } from "./notes.ts";
459
+ import { Tasks } from "./tasks.ts";
459
460
 
460
- const { api, runtime } = makeClient(Notes, {
461
- url: new URL("/rpc", window.location.href).href,
462
- });
463
- const note = api.get.query({ id: 1 });
464
- const rename = runtime.fn(api.rename.run);
461
+ export const client = makeClient({ notes: Notes, tasks: Tasks });
462
+ export const notes = client.api.notes;
463
+ ```
464
+
465
+ Save it as `session.ts`. In a browser the client connects to `/rpc` beside the page's location, so browser code passes no URL; story kits, native shells and Node callers pass `url` or `protocol`.
466
+
467
+ A binding's type depends only on its contract: `ContractClient<typeof Notes>` from the same module is the type of `client.api.notes` in every client whose record holds `Notes`, because every client made this way has the same service identity, `ContractsClient`. A screen typed with it accepts the binding of any client that contains the contract:
468
+
469
+ ```ts
470
+ import type { ContractClient } from "@shivaedev/contract/makeClient.ts";
471
+ import type { Notes } from "./notes.ts";
472
+
473
+ export function noteTitles(notes: ContractClient<typeof Notes>) {
474
+ return notes.list.query();
475
+ }
465
476
  ```
466
477
 
467
478
  Browsers send the session cookie at upgrade. Mounting a query opens its subscription before running its first authorized read; unmounting cancels that subscription without restarting the socket or another query. Changed keys rerun only their readers, and equal results retain the bound atom's value. Connection failures use Effect RPC's reconnect backoff; subscriptions reopen and the server pushes current results because there is no retained key history. `LiveConnection.status` reports `connecting`, `live` or `reconnecting`.
@@ -472,7 +483,7 @@ On visible `visibilitychange`, `online` and `pageshow` events, or an injected na
472
483
 
473
484
  For a native WebView, pass the signed session credential as `bearerToken` to `makeClient`. The browser WebSocket constructor needs no upgrade headers. The client adds `auth=frame` to the RPC URL and sends `{"_tag":"Authenticate","token":"<credential>"}` as its first text frame on every connection, before native RPC traffic. The bearer never enters the URL. Use a host session provider that admits bearer sessions and configure the WebView's Origin on the host. Authentication failures close the socket with code 1008 and reason `Authentication required`; an unavailable session provider closes it with code 1011 and reason `Authentication unavailable`. Sign-out or session expiry also closes an established bearer socket. Pass a native `resume` source to `makeClient` as shown below to reconcile live reads when the shell resumes.
474
485
 
475
- `group` supplies a larger native RPC group containing the contract, such as an admin registry. The result is a native client Layer for `ManagedRuntime.make`, plus the native `Client` service, atom `runtime` and scoped `client` Effect. Session-scoped contracts require `registry`. For Node clients, supply upgrade `headers` and `webSocketConstructor: NodeWS.layerWebSocketConstructor` from `@effect/platform-node`. A native `protocol` Layer selects another transport explicitly. A `protocol: (identity) => layer` factory follows the live session identity instead: the client rebuilds its transport when that identity changes. The scoped `client` Effect uses `undefined` as the factory identity. Return a shared Layer for clients that should share a socket within one session. Use `live: false` for ordinary clients without subscriptions.
486
+ The result is a native client Layer for `ManagedRuntime.make`, plus `api`, the native `Client` service, atom `runtime`, `sync` and a scoped `client` Effect that calls every RPC of the record by its tag. A record that holds a session-scoped contract requires `registry`. For Node clients, supply upgrade `headers` and `webSocketConstructor: NodeWS.layerWebSocketConstructor` from `@effect/platform-node`. A native `protocol` Layer selects another transport explicitly. A `protocol: (identity) => layer` factory follows the live session identity instead: the client rebuilds its transport when that identity changes. The scoped `client` Effect uses `undefined` as the factory identity. Return a shared Layer for clients that should share a socket within one session.
476
487
 
477
488
  ### 3. Every day: read and change
478
489
 
@@ -483,14 +494,14 @@ const readOnce = api.get.run({ id: 1 });
483
494
  const rename = api.rename.run({ id: 1, title: "Uno" });
484
495
  ```
485
496
 
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`.
497
+ `one` and `list` are native query atoms. `readOnce` and `rename` are Effects for individual calls. A query's Effect requires the client's service; 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`.
487
498
 
488
499
  Mount the atoms and run commands through the service's atom runtime in the same registry:
489
500
 
490
501
  ```ts
491
502
  import { Effect } from "effect";
492
503
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
493
- import { api, NotesClient } from "./client.ts";
504
+ import { api, runtime } from "./session.ts";
494
505
 
495
506
  const registry = AtomRegistry.make();
496
507
  const one = api.get.query({ id: 1 });
@@ -498,14 +509,14 @@ const list = api.list.query();
498
509
  const releaseOne = registry.mount(one);
499
510
  const releaseList = registry.mount(list);
500
511
 
501
- const renamed = await Effect.runPromise(AtomRegistry.getResult(registry, NotesClient.runtime.atom(api.rename.run({ id: 1, title: "Uno" }))));
512
+ const renamed = await Effect.runPromise(AtomRegistry.getResult(registry, runtime.atom(api.rename.run({ id: 1, title: "Uno" }))));
502
513
 
503
514
  releaseOne();
504
515
  releaseList();
505
516
  registry.dispose();
506
517
  ```
507
518
 
508
- The successful rename invalidates note 1 and the list in the browser, and because this client is bound with `live: false`, that invalidation refreshes both queries. A rejected rename invalidates neither. Bound queries and commands take the schema's decoded payload type; native clients take its constructor input, which can differ when a field has a constructor default. Result and failure types preserve operation rejections, middleware errors and `RpcClientError`.
519
+ The server publishes the successful rename's keys, note 1 and the list, reruns both mounted queries and pushes their changed results to this client. A rejected rename publishes nothing. Bound queries and commands take the schema's decoded payload type; native clients take its constructor input, which can differ when a field has a constructor default. Result and failure types preserve operation rejections, middleware errors and `RpcClientError`.
509
520
 
510
521
  The dependency rule is deliberately asymmetric:
511
522
 
@@ -516,7 +527,7 @@ The dependency rule is deliberately asymmetric:
516
527
 
517
528
  `readKeys` and `invalidationKeys` from `@shivaedev/changes/keys.ts` produce these native keys and remove duplicates. An item change reaches readers of that item and its list, preserving other item queries. A list-only invalidation reaches list readers and leaves item queries alone. These keys match native Reactivity's record-key hashing of `{ notes: [1] }`.
518
529
 
519
- The browser invalidates a command's keys after RPC success, together with a key of the command's contract. That local invalidation refreshes queries bound with `live: false`. A query with no keys in the browser, because it leaves out `reads` or its `reads` returns none for `Option.none()`, listens on that contract key instead, so bound with `live: false` it refreshes after every successful command of its contract on that client, including a command that declares no keys. A live bound query, the default on database hosts, gets its refresh from the server push instead: the server reruns it when the command's keys are published there, and the local invalidation only retries its subscription after that subscription failed with something other than `QueryReadDenied` ([Server-pushed live queries](#4-server-pushed-live-queries)). Database hosts from `@shivaedev/server` publish declared command invalidations on the server after the handler succeeds, excluding keys already announced by repository commits, using `transact` from [`sql`](https://github.com/ShivaeDev/platform/tree/main/packages/sql); commit-bound changes belong to [`changes`](https://github.com/ShivaeDev/platform/tree/main/packages/changes).
530
+ The browser keeps no keys and refreshes nothing itself: a mounted query reruns on the server when a command's keys are published there, and the server pushes its new result. After the client's next reflected command, a live subscription that failed with something other than `QueryReadDenied` reopens, because the command may have changed what it reads ([Server-pushed live queries](#4-server-pushed-live-queries)). Database hosts from `@shivaedev/server` publish declared command invalidations on the server after the handler succeeds, excluding keys already announced by repository commits, using `transact` from [`sql`](https://github.com/ShivaeDev/platform/tree/main/packages/sql); commit-bound changes belong to [`changes`](https://github.com/ShivaeDev/platform/tree/main/packages/changes).
520
531
 
521
532
  #### Server-only command keys
522
533
 
@@ -574,9 +585,9 @@ To follow each state, provide `CommandSignal` from the same module to the comman
574
585
  `sync` on the value `makeClient` returns is an Effect that writes nothing and waits the same way. It completes once every open live query shows the changes committed before it, including writes of other clients through other hosts. Use it to wait for a write this client did not make.
575
586
 
576
587
  ```ts
577
- import { makeClient } from "@shivaedev/contract/bind.ts";
588
+ import { makeClient } from "@shivaedev/contract/makeClient.ts";
578
589
 
579
- const client = makeClient(Notes, { url: "/rpc" });
590
+ const client = makeClient({ notes: Notes });
580
591
  const current = client.sync;
581
592
  ```
582
593
 
@@ -593,11 +604,11 @@ The wait rests on a sync token. The client names itself on each live stream and
593
604
 
594
605
  ### Host build announcements
595
606
 
596
- `HostVersion` from `@shivaedev/contract/HostVersion.ts` declares the native `platform.hostVersion.watch` string stream shared by the application host and React's deploy controller. The host announces its configured build ID on subscription, including after a host replacement reconnects. It uses the same shared WebSocket connection as other `makeClient` bindings with matching transport options. Applications normally use the controller from `@shivaedev/react/client/deployUpdate.ts` rather than consuming this stream directly.
607
+ `HostVersion` from `@shivaedev/contract/HostVersion.ts` declares the native `platform.hostVersion.watch` string stream shared by the application host and React's deploy controller. The host announces its configured build ID on subscription, including after a host replacement reconnects. It uses the same shared WebSocket connection as other `makeClient` clients with matching transport options. Applications normally use the controller from `@shivaedev/react/client/deployUpdate.ts` rather than consuming this stream directly.
597
608
 
598
609
  ### Client activity
599
610
 
600
- `clientActivity(client)` from `@shivaedev/contract/clientActivity.ts` returns a native Effect `Stream` with a `current` Effect for a client made by `makeClient`. Its state includes `connectionStatus`, a `"live" | "reconnecting" | "waiting-for-connection"` value aggregated across mounted queries from all bindings of the same client service, with live subscription changes debounced for 300 ms on the client runtime’s Clock and held commands reported immediately. Refused subscriptions do not count as reconnecting. The stream also exposes its native `connectionStatus` atom for React readers.
611
+ `clientActivity(client)` from `@shivaedev/contract/clientActivity.ts` returns a native Effect `Stream` with a `current` Effect for a client made by `makeClient`. Its state includes `connectionStatus`, a `"live" | "reconnecting" | "waiting-for-connection"` value aggregated across mounted queries from every binding of the client, with live subscription changes debounced for 300 ms on the client runtime’s Clock and held commands reported immediately. Refused subscriptions do not count as reconnecting. The stream also exposes its native `connectionStatus` atom for React readers.
601
612
 
602
613
  The state's `firstSettled` flag is `false` until the stream's `rendered` Effect has run once, which React's `useFirstSettled` does after the screen that calls it has rendered, and, with that, no mounted query awaits a first result and no command is in flight. It then stays `true` for that client: a later command or a newly mounted query does not turn it back. A query listed in the registry's `warmQueries` atom from `@shivaedev/contract/warmQueries.ts` when it is mounted, which React's `SessionBoundary` sets from its `warm` prop, does not hold the flag back while it awaits its first result, and neither does a query that shows a stored or retained result while it revalidates; both still count in `initialQueries`, so screen stories wait for them. The stream exposes it as its native `firstSettled` atom, which React reads through `useFirstSettled`.
603
614
 
@@ -607,7 +618,7 @@ For screen stories, pass `activityScreenSignal(clientActivity(client))` to a tes
607
618
 
608
619
  ### Query completion
609
620
 
610
- `querySignals(query)` from `@shivaedev/contract/querySignals.ts` returns a native atom scoped to the query's registry. Its `completed` counter advances when the initial query or a refresh finishes, including typed failures and equal results. `pending` describes the query result awaiting completion. `subscription` is `disabled` for an ordinary query, `opening` while connecting, `open` once accepted, or `refused` after a terminal refusal. Read the query's `AsyncResult` for its value or typed failure.
621
+ `querySignals(query)` from `@shivaedev/contract/querySignals.ts` returns a native atom scoped to the query's registry. Its `completed` counter advances when the initial query or a refresh finishes, including typed failures and equal results. `pending` describes the query result awaiting completion. `subscription` is `disabled` before a bound query's subscription starts, `opening` while connecting, `open` once accepted, or `refused` after a terminal refusal. Read the query's `AsyncResult` for its value or typed failure.
611
622
 
612
623
  ```ts
613
624
  import { querySignals } from "@shivaedev/contract/querySignals.ts";
@@ -658,33 +669,25 @@ export const Preferences = defineModule({
658
669
  });
659
670
  ```
660
671
 
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:
672
+ `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 makes its client with the session's registry:
662
673
 
663
674
  ```ts
664
- import { bind } from "@shivaedev/contract/bind.ts";
675
+ import { makeClient } from "@shivaedev/contract/makeClient.ts";
665
676
  import { Preferences } from "#generated/modules/preferences/Preferences.ts";
666
677
 
667
- const api = bind(Preferences, Client, { registry });
668
- const self = api.self.query(undefined);
669
- const save = api.save.run({ title: "My preferences" });
678
+ const { preferences } = makeClient({ preferences: Preferences }, { registry }).api;
679
+ const self = preferences.self.query(undefined);
680
+ const save = preferences.save.run({ title: "My preferences" });
670
681
  ```
671
682
 
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.
683
+ `registry` is the atom registry that owns the session's queries; a record that holds a session-scoped contract does not compile without it. 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.
673
684
 
674
685
  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.
675
686
 
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.
687
+ 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.
677
688
 
678
689
  Server subscriptions and committed writes use the same plain record, list and bucket keys, including for `keyScope: "session"`. A background worker needs no request identity or account prefix to refresh a session's query. Matching keys trigger the query's own read policy; authorized reads remain responsible for filtering rows to the viewer. A shared key can therefore trigger authorized rechecks for several accounts. Use model buckets to narrow that fan-out.
679
690
 
680
- In the browser, `bind` gives each owning registry an opaque id and prefixes every client read and invalidation key of a session-scoped contract with it, so a command in one session's registry refreshes none of another session's queries, even when the registries share one runtime and its Reactivity. The server adds no prefix. Custom client coordination uses these helpers and context type:
681
-
682
- ```ts
683
- import { clientInvalidationKeys, clientReadKeys, type KeyContext } from "@shivaedev/contract/clientKeys.ts";
684
- ```
685
-
686
- `clientReadKeys(keys, context)` registers client dependencies; `clientInvalidationKeys(keys, context)` announces client cache changes. The context has type `KeyContext`. Never publish contextual client keys on the server.
687
-
688
691
  ### Compose feature bindings
689
692
 
690
693
  Use `composeBindings(client, bindings)` when a connection contains several feature modules. The returned object keeps the client's fields and types and carries an explicit list of bound APIs. `liveBindings(connection)` reads this list; without an explicit list it finds bindings through nested object properties and arrays at any depth. It visits shared objects once and handles cycles. Explicit lists remain authoritative at each composition.
@@ -699,7 +702,7 @@ const connection = composeBindings(
699
702
  );
700
703
  ```
701
704
 
702
- `notesModule` and `tasksModule` are application modules whose `api` values come from `bind` or `makeClient`. Return `connection` from React's `SessionBoundary` connection callback to mount both bindings while keeping the modules nested.
705
+ `notesModule` and `tasksModule` are application modules whose `api` values are bindings from `makeClient`. Return `connection` from React's `SessionBoundary` connection callback to mount both bindings while keeping the modules nested.
703
706
 
704
707
  ### 4. Server-pushed live queries
705
708
 
@@ -717,9 +720,9 @@ The `paused` atom at `api[LiveConnection]` suppresses applying pushed values to
717
720
 
718
721
  A live query's result stays a native initial result with `waiting: true` from mount until its subscription delivers the first result. An explicit query refresh reopens its subscription, retaining its current value with `waiting: true` until the fresh result arrives. Retryable connection failures retain the current query value during reconnection. Declared query failures and read denials still reach the query's error channel.
719
722
 
720
- Visible browser `online` and `visibilitychange` events reopen active subscriptions for current values. Supply an optional native `resume` source on `makeClient` or `bind` for application or network lifecycle events; it registers a callback and returns its cleanup function. `resumeWindow` selects an embedded browser window. Disposing the registry releases the source, query subscriptions and socket resources.
723
+ Visible browser `online` and `visibilitychange` events reopen active subscriptions for current values. Supply an optional native `resume` source on `makeClient` for application or network lifecycle events; it registers a callback and returns its cleanup function. `resumeWindow` selects an embedded browser window. Disposing the registry releases the source, query subscriptions and socket resources.
721
724
 
722
- `status` exposes `connection`, `failure`, `needsResync` and `pending`. A resume keeps `connection` unchanged and sets `needsResync` until the reopened subscription delivers its first update, while the query results keep their values and report nothing pending. A typed stream rejection settles as `failed`; transport failures and defects retry with the existing jittered exponential backoff. A denied subscription stays refused through matching local invalidations and resume events; it reopens when the viewer changes or the query is refreshed explicitly. A matching local invalidation still retries a subscription that settled with another failure, such as a declared `NotFound`. A query with no keys in the browser has nothing for a local invalidation to match, so such a subscription stays settled through its contract's commands, and an explicit refresh reopens it. An established subscription remains open after a policy denial so a later authorized change can restore its value. A `$changes` request is authorized as a whole; automatic query atoms subscribe separately so independent permissions remain independent.
725
+ `status` exposes `connection`, `failure`, `needsResync` and `pending`. A resume keeps `connection` unchanged and sets `needsResync` until the reopened subscription delivers its first update, while the query results keep their values and report nothing pending. A typed stream rejection settles as `failed`; transport failures and defects retry with the existing jittered exponential backoff. A denied subscription stays refused through commands and resume events; it reopens when the viewer changes or the query is refreshed explicitly. A subscription that settled with another failure, such as a declared `NotFound`, reopens after the client's next reflected command, whatever keys that command declares. An established subscription remains open after a policy denial so a later authorized change can restore its value. A `$changes` request is authorized as a whole; automatic query atoms subscribe separately so independent permissions remain independent.
723
726
 
724
727
  Custom native hosts use `changesHandlerLayer`, `querySubscription(rpc, references, viewer)` and `subscribe(subscription, read)`. The authorized query runner is required and must use the same handler and read policy as an ordinary read; session-backed hosts must provide a fresh session context on each rerun. Platform's host supplies this composition. The caller owns consumption and interruption of a raw `$changes` stream, whose values are `Result`, `Unchanged` and `QueryReadDenied`. A request that names its client in the `x-shivaedev-sync` header also receives `Syncing` before each full read and `Synced` with the sync tokens the stream passed; a host passes that name as the subscription's `syncClient`, read with `syncClient(headers)` from `@shivaedev/contract/syncHeader.ts`. The command boundary of `commandGuardLayer` receives the command's sync token as its third argument, and a host without `@shivaedev/server` serves the `LiveSync` contract from `@shivaedev/contract/LiveSync.ts` with a handler that does nothing.
725
728
 
@@ -800,7 +803,7 @@ Provide `TimelineData` on the server to read the workspace's entries, and to loa
800
803
 
801
804
  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.
802
805
 
803
- A query may leave out `reads`. Declared keys are used exactly as declared, even when `reads` returns `[]`. A query that declares none, with no `reads`, `serverReads` or `readsCollections`, listens on what its repository reads from `@shivaedev/sql` pin: a row, a bucket, or the whole table for an unfiltered read. The [sql guide](https://github.com/ShivaeDev/platform/blob/main/packages/sql/README.md#live-reads-listen-on-what-they-filter-by) lists which key each filter pins. Keys a handler records itself with `recordRead` count either way. A raw SQL read written with `readSql` from `@shivaedev/sql/readSql.ts` listens on the bucket and row keys interpolated as its parameters, as the [sql guide](https://github.com/ShivaeDev/platform/blob/main/packages/sql/README.md#a-raw-read-names-its-key-at-its-parameter) shows. A read through the native `sql` tag records no key, so a query whose handler reads only that way and leaves out `reads` registers nothing and never reruns; such a query keeps its `reads`. When a query that declares no keys finishes a run with no key recorded, the host logs a warning that names the query and says to mark its raw reads or declare `reads`; the subscription carries on, because a handler may read nothing for some payloads. Declare `reads: () => []` for a query that reads nothing, which logs no warning. The browser never sees the keys a host records, so there a query without `reads` has no keys, like one with `reads: () => []`; [read and change](#3-every-day-read-and-change) says how a `live: false` binding refreshes such a query, and [server-pushed live queries](#4-server-pushed-live-queries) when its failed subscription reopens.
806
+ A query may leave out `reads`. Declared keys are used exactly as declared, even when `reads` returns `[]`. A query that declares none, with no `reads`, `serverReads` or `readsCollections`, listens on what its repository reads from `@shivaedev/sql` pin: a row, a bucket, or the whole table for an unfiltered read. The [sql guide](https://github.com/ShivaeDev/platform/blob/main/packages/sql/README.md#live-reads-listen-on-what-they-filter-by) lists which key each filter pins. Keys a handler records itself with `recordRead` count either way. A raw SQL read written with `readSql` from `@shivaedev/sql/readSql.ts` listens on the bucket and row keys interpolated as its parameters, as the [sql guide](https://github.com/ShivaeDev/platform/blob/main/packages/sql/README.md#a-raw-read-names-its-key-at-its-parameter) shows. A read through the native `sql` tag records no key, so a query whose handler reads only that way and leaves out `reads` registers nothing and never reruns; such a query keeps its `reads`. When a query that declares no keys finishes a run with no key recorded, the host logs a warning that names the query and says to mark its raw reads or declare `reads`; the subscription carries on, because a handler may read nothing for some payloads. Declare `reads: () => []` for a query that reads nothing, which logs no warning.
804
807
 
805
808
  Live query handlers read at READ COMMITTED, PostgreSQL's default, which statements and plain Effect SQL transactions keep: each statement takes its snapshot after the key recorded before it is registered, so a commit to that key is either read by the statement or heard afterwards. A handler that opens a REPEATABLE READ or SERIALIZABLE transaction keeps one snapshot from its first statement, so it declares its keys in `reads` or `serverReads` instead. The [changes guide](https://github.com/ShivaeDev/platform/blob/main/packages/changes/README.md#record-what-a-live-read-listens-on) shows the call.
806
809
 
@@ -915,13 +918,16 @@ The module's handlers check the policy with the services the registration provid
915
918
 
916
919
  ```ts
917
920
  import { Layer } from "effect";
918
- import { makeClient } from "@shivaedev/contract/bind.ts";
921
+ import { makeClient } from "@shivaedev/contract/makeClient.ts";
919
922
  import { layerMemoryProtocol } from "@shivaedev/test-kits/contract/testing.ts";
920
923
 
921
- const client = makeClient(Notes, {
922
- protocol: layerMemoryProtocol(Notes).pipe(Layer.provide(handlers)),
923
- url: "memory://notes",
924
- });
924
+ const client = makeClient(
925
+ { notes: Notes },
926
+ {
927
+ protocol: layerMemoryProtocol(Notes).pipe(Layer.provide(handlers)),
928
+ url: "memory://notes",
929
+ },
930
+ );
925
931
  ```
926
932
 
927
933
  The URL identifies the client configuration; the in-memory protocol opens no socket. The client's direct calls and bound query atoms use the real handlers, schema decoding and middleware. Live subscriptions use the supplied handlers and change source, and mounted queries refresh from their updates. Closing a subscription interrupts its server stream. The protocol does not add handlers or publish changes: provide the same live handlers and change source that the application serves over WebSocket. It refuses a group the application host would refuse to start, such as one whose RPC uses a field name both as sensitive and as public, with the host's error; the [test-kits README](https://github.com/ShivaeDev/platform/tree/main/packages/test-kits#contract-subscriptions) describes the check.
@@ -935,7 +941,7 @@ import { Effect } from "effect";
935
941
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
936
942
  import { settledQueries } from "@shivaedev/test-kits/contract/settledQueries.ts";
937
943
 
938
- const results = yield* settledQueries(client.api.list.query()).pipe(Effect.provideService(AtomRegistry.AtomRegistry, registry));
944
+ const results = yield* settledQueries(client.api.notes.list.query()).pipe(Effect.provideService(AtomRegistry.AtomRegistry, registry));
939
945
  const first = yield* results.next;
940
946
  const current = yield* results.latest;
941
947
  ```
@@ -950,44 +956,44 @@ Observe raw result streams with `watchHints` from `@shivaedev/test-kits/contract
950
956
 
951
957
  Import the module that defines the name; the package has no root entry.
952
958
 
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
- | `QueryStorage.ts` | `QueryStorage`, the port for results that outlive the page, and `QueryStorageProvider`, the service a storage Layer supplies. |
982
- | `retainQuery.ts` | `queryRuntime(query)` returns the atom runtime a bound query runs on, so a reader can schedule work on the same Effect `Clock`. |
983
- | `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. |
984
- | `commandSignal.ts` | `untilReflected(command)` completes a command's Effect when it is reflected; `CommandSignal` receives each `CommandState`. |
985
- | `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`. |
986
- | `liveSyncRpc.ts` | `liveSyncRpc`, the RPC group a client declares for that command without importing its operation file, and `LIVE_SYNC`, its tag. |
987
- | `syncHeader.ts` | `syncClient(headers)` and `syncToken(headers)` read the client name and the sync token a request carries. |
988
- | `operationKind.ts` | `operationKind(rpc)`: `"read"` for a query, a changes stream or a stream, `"write"` for a command or an RPC no contract marked. |
989
- | `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. |
990
- | `screenSync.ts` | `screenSync(client, registry)` runs a client's `sync` through a registry, for a screen driver's `sync` option. |
959
+ | Module | Functions and schemas |
960
+ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
961
+ | `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 })`. |
962
+ | `contract.ts` | `contract(name, { queries?, commands?, streams?, keyScope? })`, returning a native RPC group with `declaration: { name, queries, commands, streams, keyScope }`. |
963
+ | `defineModule.ts` | `defineModule({ name, operations, wire, middleware?, subject?, keyScope? })`, returning the module's contract, whose type carries the services each operation yields. |
964
+ | `moduleHandlers.ts` | `moduleHandlers(module)`, the module's handler Layer, requiring exactly the services its operations yield beyond its middleware and subject. |
965
+ | `clientContract.ts` | `clientContract({ name, wire, payloads?, queries?, commands?, middleware?, subject?, keyScope? })`, the browser's contract of a module that generated files build. |
966
+ | `clientMatchesModule.ts` | `ClientMatchesModule<Client, Module>`, `true` when the browser's contract and the server module have the same RPCs, else `ClientDiffersFromModule`. |
967
+ | `rejection.ts` | `fieldRejection(struct, fields?)`; lower-level `rejectionSet(specs)`, which constructs the rejection classes, union schema and failure helpers used by operations. |
968
+ | `bind.ts` | `bind(contract, atomRpcService, { registry?, 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, for an `AtomRpc.Service` the caller builds itself. |
969
+ | `makeClient.ts` | `makeClient(contracts, { url?, protocol?, headers?, bearerToken?, webSocketConstructor?, registry?, resume?, resumeWindow?, runtime? }?)`, which builds one shared WebSocket client over a record of contracts and binds each under its key in `api`, with `sync` beside it; `ContractClient<Contract>`, a binding's type; `ContractsClient`, the clients' shared service identity. |
970
+ | `live.ts` | `LiveHint` schema; `live(runtime, { stream, resume?, retryDelay? })`, exposing `connection`, `paused` and `status`; `isLiveConnection(atom)` tells whether an atom is such a `connection`, which waits for as long as its subscription runs. |
971
+ | `querySubscription.ts` | `querySubscription(rpc, references, viewer)` checks each referenced query, resolves its payload and server-derived keys, and captures its scopes and ongoing authorization. |
972
+ | `live-server/service.ts` | `LiveServer`, the shared live server service. |
973
+ | `live-server/layer.ts` | `liveServerLayer`, providing `LiveServer` and its dispatcher dependency, requiring `Reactivity`. |
974
+ | `live-server/subscribe.ts` | `subscribe(subscription, read?)`, an Effect requiring `LiveServer` that returns an authorized subscription Stream with its policy and query-runner requirements. |
975
+ | `makeLiveServer.ts` | `makeLiveServer`, an Effect requiring `Reactivity` that creates scoped server hint streams, a `resync` Effect and `synced(token)`. |
976
+ | `readPolicy.ts` | `QueryReadPolicy`, `Viewer`, `signedIn`, `CurrentViewer`; `authorizeReads(effect, request, viewer)` for direct handler reruns outside RPC middleware. |
977
+ | `ReadPolicyGuard.ts` | `ReadPolicyGuard`, the defaulted middleware reference attached to contract queries; `readPolicyGuardLayer({ websocket? })`, an optional override that refuses HTTP `$changes` calls by default. |
978
+ | `validateReadPolicies.ts` | `validateReadPolicies(group)`, an Effect that fails with `MissingReadPolicies` when any served or subscribable query omits its policy. |
979
+ | `readPolicyErrors.ts` | `MissingReadPolicies` (boot), `MissingReadPolicy` (native-server request fallback) and `QueryReadDenied`. |
980
+ | `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. |
981
+ | `commandResult.ts` | `commandResult({ result, invalidates })` contributes server-only keys from a guarded command's `run` or handler and returns only its success value. |
982
+ | `serverMetadata.ts` | `QueryDefinition.definition`, `CommandInvalidation.invalidates`, `ChangesQueries.queries`, `ChangesQueries.resolve(references)` and `changesRpc(name, queries)` for server adapters. |
983
+ | `queryKeys.ts` | `queryKeys(queries, references, viewer?)` authorizes references and resolves payload and server-derived keys using the provided services. |
984
+ | `QueryServerReads.ts` | `QueryServerReads<Payload, E, R>`, the server-only resolver type. |
985
+ | `resume.ts` | `resumeSignal({ window?, native? })`, returning a native numeric signal atom. |
986
+ | `querySignals.ts` | `querySignals(query)` exposes completion counts and subscription status as a native atom. |
987
+ | `QueryStorage.ts` | `QueryStorage`, the port for results that outlive the page, and `QueryStorageProvider`, the service a storage Layer supplies. |
988
+ | `retainQuery.ts` | `queryRuntime(query)` returns the atom runtime a bound query runs on, so a reader can schedule work on the same Effect `Clock`. |
989
+ | `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. |
990
+ | `commandSignal.ts` | `untilReflected(command)` completes a command's Effect when it is reflected; `CommandSignal` receives each `CommandState`. |
991
+ | `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`. |
992
+ | `liveSyncRpc.ts` | `liveSyncRpc`, the RPC group a client declares for that command without importing its operation file, and `LIVE_SYNC`, its tag. |
993
+ | `syncHeader.ts` | `syncClient(headers)` and `syncToken(headers)` read the client name and the sync token a request carries. |
994
+ | `operationKind.ts` | `operationKind(rpc)`: `"read"` for a query, a changes stream or a stream, `"write"` for a command or an RPC no contract marked. |
995
+ | `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. |
996
+ | `screenSync.ts` | `screenSync(client, registry)` runs a client's `sync` through a registry, for a screen driver's `sync` option. |
991
997
 
992
998
  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.
993
999
 
@@ -0,0 +1,18 @@
1
+ import type { Layer } from "effect";
2
+ import type * as Atom from "effect/reactivity/Atom";
3
+ import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
+ import type { RpcClient } from "effect/rpc";
5
+ import type * as Socket from "effect/socket/Socket";
6
+ import type { ResumeSource, ResumeWindow } from "#resume.ts";
7
+ export interface ClientOptions {
8
+ readonly bearerToken?: string;
9
+ readonly headers?: Readonly<Record<string, string>>;
10
+ readonly protocol?: Layer.Layer<RpcClient.Protocol> | ((identity: string | undefined) => Layer.Layer<RpcClient.Protocol>);
11
+ readonly registry?: AtomRegistry.AtomRegistry;
12
+ readonly resume?: ResumeSource;
13
+ readonly resumeWindow?: ResumeWindow;
14
+ readonly runtime?: Atom.RuntimeFactory;
15
+ readonly url?: string;
16
+ readonly webSocketConstructor?: Layer.Layer<Socket.WebSocketConstructor>;
17
+ }
18
+ //# sourceMappingURL=ClientOptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ClientOptions.d.ts","sourceRoot":"","sources":["../src/ClientOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,KAAK,KAAK,IAAI,MAAM,wBAAwB,CAAC;AACpD,OAAO,KAAK,KAAK,YAAY,MAAM,gCAAgC,CAAC;AACpE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,KAAK,MAAM,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE7D,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACpD,QAAQ,CAAC,QAAQ,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,KAAK,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC1H,QAAQ,CAAC,QAAQ,CAAC,EAAE,YAAY,CAAC,YAAY,CAAC;IAC9C,QAAQ,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC;IAC/B,QAAQ,CAAC,YAAY,CAAC,EAAE,YAAY,CAAC;IACrC,QAAQ,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,CAAC;IACvC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,oBAAoB,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;CACzE"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ClientOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ClientOptions.js","sourceRoot":"","sources":["../src/ClientOptions.ts"],"names":[],"mappings":""}
@@ -1,7 +1,5 @@
1
1
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
2
- import type { KeyContext } from "#clientKeys.ts";
3
2
  export interface BindingOwner {
4
- readonly context: KeyContext;
5
3
  readonly registry: AtomRegistry.AtomRegistry;
6
4
  }
7
5
  export declare function bindingOwner(scope: "session" | undefined, registry?: AtomRegistry.AtomRegistry): BindingOwner | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"bindingOwner.d.ts","sourceRoot":"","sources":["../../src/adapters/bindingOwner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,YAAY,MAAM,gCAAgC,CAAC;AAEpE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjD,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC,YAAY,CAAC;CAC7C;AAID,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS,EAAE,QAAQ,CAAC,EAAE,YAAY,CAAC,YAAY,GAAG,YAAY,GAAG,SAAS,CAazH"}
1
+ {"version":3,"file":"bindingOwner.d.ts","sourceRoot":"","sources":["../../src/adapters/bindingOwner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,YAAY,MAAM,gCAAgC,CAAC;AAEpE,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC,YAAY,CAAC;CAC7C;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS,EAAE,QAAQ,CAAC,EAAE,YAAY,CAAC,YAAY,GAAG,YAAY,GAAG,SAAS,CAQzH"}
@@ -1,5 +1,3 @@
1
- import { clientId } from "#adapters/clientId.ts";
2
- const contexts = new WeakMap();
3
1
  export function bindingOwner(scope, registry) {
4
2
  if (scope === undefined) {
5
3
  return undefined;
@@ -7,11 +5,6 @@ export function bindingOwner(scope, registry) {
7
5
  if (registry === undefined) {
8
6
  throw new Error("A session-scoped contract requires its owning registry");
9
7
  }
10
- let context = contexts.get(registry);
11
- if (context === undefined) {
12
- context = { scope: clientId() };
13
- contexts.set(registry, context);
14
- }
15
- return { context, registry };
8
+ return { registry };
16
9
  }
17
10
  //# sourceMappingURL=bindingOwner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bindingOwner.js","sourceRoot":"","sources":["../../src/adapters/bindingOwner.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAQjD,MAAM,QAAQ,GAAG,IAAI,OAAO,EAAyC,CAAC;AAEtE,MAAM,UAAU,YAAY,CAAC,KAA4B,EAAE,QAAoC;IAC9F,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC3E,CAAC;IACD,IAAI,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACrC,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC3B,OAAO,GAAG,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC;QAChC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;AAC9B,CAAC"}
1
+ {"version":3,"file":"bindingOwner.js","sourceRoot":"","sources":["../../src/adapters/bindingOwner.ts"],"names":[],"mappings":"AAMA,MAAM,UAAU,YAAY,CAAC,KAA4B,EAAE,QAAoC;IAC9F,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,CAAC;AACrB,CAAC"}
@@ -3,7 +3,6 @@ import type * as AsyncResult from "effect/reactivity/AsyncResult";
3
3
  import * as Atom from "effect/reactivity/Atom";
4
4
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
5
5
  import type { Rpc } from "effect/rpc";
6
- import type { Key } from "@shivaedev/changes/keys.ts";
7
6
  import type { BindingOwner } from "#adapters/bindingOwner.ts";
8
7
  import { type LiveStatus } from "#live.ts";
9
8
  import { type ResumeSource, type ResumeWindow } from "#resume.ts";
@@ -17,8 +16,8 @@ export interface LiveBound {
17
16
  readonly status: Atom.Atom<LiveStatus<unknown>>;
18
17
  };
19
18
  }
20
- export declare function automaticLive(operations: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>, name: string, owner?: BindingOwner, resume?: ResumeSource, enabled?: boolean, resumeWindow?: ResumeWindow): {
21
- query: <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>, reference: QueryReference, keys: readonly Key[], equivalent: (left: A, right: A) => boolean, decode: (value: unknown) => A, reactive: (source: Atom.Atom<AsyncResult.AsyncResult<A, E>>) => Atom.Atom<AsyncResult.AsyncResult<A, E>>, headers?: Headers.Input) => any;
19
+ export declare function automaticLive(operations: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>, name: string, owner?: BindingOwner, resume?: ResumeSource, resumeWindow?: ResumeWindow): {
20
+ query: <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>, reference: QueryReference, equivalent: (left: A, right: A) => boolean, decode: (value: unknown) => A, headers?: Headers.Input) => any;
22
21
  subscription: {
23
22
  connection: Atom.Atom<LiveStatus<unknown>>;
24
23
  identity: Atom.Writable<string | undefined, string | undefined>;