@shivaedev/contract 0.54.1 → 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 (68) hide show
  1. package/CHANGELOG.md +13 -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/bind.d.ts +1 -10
  16. package/dist/bind.d.ts.map +1 -1
  17. package/dist/bind.js +1 -12
  18. package/dist/bind.js.map +1 -1
  19. package/dist/clientOperations.d.ts.map +1 -1
  20. package/dist/clientOperations.js +17 -16
  21. package/dist/clientOperations.js.map +1 -1
  22. package/dist/commandReflected.d.ts +2 -0
  23. package/dist/commandReflected.d.ts.map +1 -0
  24. package/dist/commandReflected.js +3 -0
  25. package/dist/commandReflected.js.map +1 -0
  26. package/dist/live.d.ts +0 -4
  27. package/dist/live.d.ts.map +1 -1
  28. package/dist/live.js +2 -2
  29. package/dist/live.js.map +1 -1
  30. package/dist/makeClient.d.ts +41 -0
  31. package/dist/makeClient.d.ts.map +1 -0
  32. package/dist/makeClient.js +25 -0
  33. package/dist/makeClient.js.map +1 -0
  34. package/dist/queryProgress.d.ts +1 -3
  35. package/dist/queryProgress.d.ts.map +1 -1
  36. package/dist/queryProgress.js +0 -22
  37. package/dist/queryProgress.js.map +1 -1
  38. package/dist/retryOnChange.d.ts.map +1 -1
  39. package/dist/retryOnChange.js +4 -0
  40. package/dist/retryOnChange.js.map +1 -1
  41. package/dist/rpcClient.d.ts +1 -1
  42. package/dist/rpcClient.d.ts.map +1 -1
  43. package/dist/rpcClient.js +4 -1
  44. package/dist/rpcClient.js.map +1 -1
  45. package/dist/socketProtocol.d.ts +1 -1
  46. package/package.json +6 -6
  47. package/src/ClientOptions.ts +18 -0
  48. package/src/adapters/bindingOwner.ts +1 -11
  49. package/src/automaticLive.ts +0 -10
  50. package/src/bind.ts +3 -39
  51. package/src/clientOperations.ts +17 -22
  52. package/src/commandReflected.ts +2 -0
  53. package/src/live.ts +2 -4
  54. package/src/makeClient.ts +78 -0
  55. package/src/queryProgress.ts +1 -24
  56. package/src/retryOnChange.ts +4 -0
  57. package/src/rpcClient.ts +7 -2
  58. package/src/socketProtocol.ts +1 -1
  59. package/dist/clientKeys.d.ts +0 -7
  60. package/dist/clientKeys.d.ts.map +0 -1
  61. package/dist/clientKeys.js +0 -11
  62. package/dist/clientKeys.js.map +0 -1
  63. package/dist/clientOptions.d.ts +0 -31
  64. package/dist/clientOptions.d.ts.map +0 -1
  65. package/dist/clientOptions.js +0 -2
  66. package/dist/clientOptions.js.map +0 -1
  67. package/src/clientKeys.ts +0 -17
  68. package/src/clientOptions.ts +0 -44
@@ -1,6 +1,6 @@
1
1
  import { Layer } from "effect";
2
2
  import { RpcClient } from "effect/rpc";
3
- import type { ClientOptions } from "#clientOptions.ts";
3
+ import type { ClientOptions } from "#ClientOptions.ts";
4
4
  interface SocketOptions {
5
5
  readonly bearerToken: ClientOptions["bearerToken"];
6
6
  readonly headers: ClientOptions["headers"];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/contract",
3
- "version": "0.54.1",
3
+ "version": "0.55.0",
4
4
  "description": "Typed query and command contracts over native Effect RPC and reactivity",
5
5
  "keywords": [
6
6
  "effect"
@@ -51,13 +51,13 @@
51
51
  "devDependencies": {
52
52
  "@effect/platform-node": "4.1.4",
53
53
  "@effect/vitest": "4.1.4",
54
- "@shivaedev/identity": "0.38.0",
55
- "@shivaedev/quality": "0.82.1",
56
- "@shivaedev/server": "0.40.0",
54
+ "@shivaedev/identity": "0.38.1",
55
+ "@shivaedev/quality": "0.83.0",
56
+ "@shivaedev/server": "0.41.0",
57
57
  "@shivaedev/sql": "0.54.0",
58
- "@shivaedev/test-kits": "0.16.0",
58
+ "@shivaedev/test-kits": "0.16.1",
59
59
  "@shivaedev/test-sql": "0.26.0",
60
- "@shivaedev/test-story": "0.52.0",
60
+ "@shivaedev/test-story": "0.52.1",
61
61
  "@types/node": "24.19.2",
62
62
  "effect": "4.1.4",
63
63
  "fake-indexeddb": "6.2.8",
@@ -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
+
8
+ export interface ClientOptions {
9
+ readonly bearerToken?: string;
10
+ readonly headers?: Readonly<Record<string, string>>;
11
+ readonly protocol?: Layer.Layer<RpcClient.Protocol> | ((identity: string | undefined) => Layer.Layer<RpcClient.Protocol>);
12
+ readonly registry?: AtomRegistry.AtomRegistry;
13
+ readonly resume?: ResumeSource;
14
+ readonly resumeWindow?: ResumeWindow;
15
+ readonly runtime?: Atom.RuntimeFactory;
16
+ readonly url?: string;
17
+ readonly webSocketConstructor?: Layer.Layer<Socket.WebSocketConstructor>;
18
+ }
@@ -1,14 +1,9 @@
1
1
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
2
- import { clientId } from "#adapters/clientId.ts";
3
- import type { KeyContext } from "#clientKeys.ts";
4
2
 
5
3
  export interface BindingOwner {
6
- readonly context: KeyContext;
7
4
  readonly registry: AtomRegistry.AtomRegistry;
8
5
  }
9
6
 
10
- const contexts = new WeakMap<AtomRegistry.AtomRegistry, KeyContext>();
11
-
12
7
  export function bindingOwner(scope: "session" | undefined, registry?: AtomRegistry.AtomRegistry): BindingOwner | undefined {
13
8
  if (scope === undefined) {
14
9
  return undefined;
@@ -16,10 +11,5 @@ export function bindingOwner(scope: "session" | undefined, registry?: AtomRegist
16
11
  if (registry === undefined) {
17
12
  throw new Error("A session-scoped contract requires its owning registry");
18
13
  }
19
- let context = contexts.get(registry);
20
- if (context === undefined) {
21
- context = { scope: clientId() };
22
- contexts.set(registry, context);
23
- }
24
- return { context, registry };
14
+ return { registry };
25
15
  }
@@ -5,7 +5,6 @@ import * as Atom from "effect/reactivity/Atom";
5
5
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
6
6
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
7
7
  import type { Rpc } from "effect/rpc";
8
- import type { Key } from "@shivaedev/changes/keys.ts";
9
8
  import type { BindingOwner } from "#adapters/bindingOwner.ts";
10
9
  import { changesClient } from "#adapters/erasedClient.ts";
11
10
  import { aggregateLiveStatus } from "#aggregateLiveStatus.ts";
@@ -13,7 +12,6 @@ import { automaticQuery } from "#automaticQuery.ts";
13
12
  import { clientActivities } from "#clientActivities.ts";
14
13
  import { type LiveStatus, live } from "#live.ts";
15
14
  import { queryDelivery } from "#queryDelivery.ts";
16
- import { queryProgress } from "#queryProgress.ts";
17
15
  import { querySignals, shareQuerySignals } from "#querySignals.ts";
18
16
  import { followReflection, type StreamAnchor } from "#reflectedStream.ts";
19
17
  import { type ResumeSource, type ResumeWindow, resumeSignal } from "#resume.ts";
@@ -39,7 +37,6 @@ export function automaticLive(
39
37
  name: string,
40
38
  owner?: BindingOwner,
41
39
  resume?: ResumeSource,
42
- enabled = true,
43
40
  resumeWindow?: ResumeWindow,
44
41
  ) {
45
42
  const service = changesClient(operations);
@@ -62,15 +59,10 @@ export function automaticLive(
62
59
  function query<A, E>(
63
60
  atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
64
61
  reference: QueryReference,
65
- keys: readonly Key[],
66
62
  equivalent: (left: A, right: A) => boolean,
67
63
  decode: (value: unknown) => A,
68
- reactive: (source: Atom.Atom<AsyncResult.AsyncResult<A, E>>) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
69
64
  headers?: Headers.Input,
70
65
  ) {
71
- if (!enabled) {
72
- return queryProgress(reactive(atom));
73
- }
74
66
  const ready = Atom.make(false);
75
67
  const signals = querySignals(atom);
76
68
  const delivery = queryDelivery(decode, paused, signals);
@@ -86,9 +78,7 @@ export function automaticLive(
86
78
  return made;
87
79
  }
88
80
  const subscription = live(service.runtime, {
89
- keyContext: owner?.context,
90
81
  resume: signal,
91
- retryKeys: keys,
92
82
  stream: Stream.unwrap(
93
83
  service.use((client) =>
94
84
  Effect.map(AtomRegistry.AtomRegistry, (registry) => {
package/src/bind.ts CHANGED
@@ -1,22 +1,20 @@
1
- import type { Effect, Layer, Stream } from "effect";
1
+ import type { Effect, Stream } from "effect";
2
2
  import type { Headers } from "effect/http";
3
3
  import type * as AsyncResult from "effect/reactivity/AsyncResult";
4
4
  import type * as Atom from "effect/reactivity/Atom";
5
5
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
6
6
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
7
7
  import type * as Reactivity from "effect/reactivity/Reactivity";
8
- import type { Rpc, RpcGroup } from "effect/rpc";
8
+ import type { Rpc } from "effect/rpc";
9
9
  import type { RpcClientError } from "effect/rpc/RpcClientError";
10
10
  import { bindingOwner } from "#adapters/bindingOwner.ts";
11
11
  import { automaticLive, type LiveBound } from "#automaticLive.ts";
12
12
  import { bindOperations } from "#bindOperations.ts";
13
13
  import { clientOperations } from "#clientOperations.ts";
14
- import type { ClientOptions, MadeClient } from "#clientOptions.ts";
15
14
  import type { Contract, Declared } from "#contract.ts";
16
15
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
17
16
  import type { Tag } from "#operationRpc.ts";
18
17
  import type { ResumeSource, ResumeWindow } from "#resume.ts";
19
- import { type RpcSource, rpcClient } from "#rpcClient.ts";
20
18
 
21
19
  // Like Effect's own `Rpc` helpers, these take any type: `Rpc.ExtractTag` of a generic group is not provably an `Rpc.Any`.
22
20
  export type Failure<R> =
@@ -83,7 +81,6 @@ type MatchingClient<TRpcs extends Rpc.Any, TClientRpcs extends Rpc.Any> = [TRpcs
83
81
  : "Client must implement the contract RPCs";
84
82
 
85
83
  interface BindOptions {
86
- readonly live?: boolean;
87
84
  readonly registry?: AtomRegistry.AtomRegistry;
88
85
  readonly resume?: ResumeSource;
89
86
  readonly resumeWindow?: ResumeWindow;
@@ -111,39 +108,6 @@ export function bind(
111
108
  ): unknown {
112
109
  const { name, keyScope } = contract.declaration;
113
110
  const owner = bindingOwner(keyScope, options?.registry);
114
- const automatic = automaticLive(service, name, owner, options?.resume, options?.live, options?.resumeWindow);
111
+ const automatic = automaticLive(service, name, owner, options?.resume, options?.resumeWindow);
115
112
  return bindOperations(contract.declaration, clientOperations(service, automatic, owner), automatic.subscription);
116
113
  }
117
-
118
- export function makeClient<
119
- TName extends string,
120
- TQueries extends readonly QueryShape[],
121
- TCommands extends readonly CommandShape[],
122
- TRpcs extends Rpc.Any,
123
- TStreams extends readonly StreamShape[],
124
- TScope extends "session" | undefined,
125
- TExtra extends Rpc.Any = never,
126
- >(
127
- contract: Contract<TName, TQueries, TCommands, TRpcs, TStreams, TScope>,
128
- options: ClientOptions & { readonly group?: RpcGroup.RpcGroup<TRpcs | TExtra> } & ("session" extends TScope
129
- ? { readonly registry: AtomRegistry.AtomRegistry }
130
- : { readonly registry?: AtomRegistry.AtomRegistry }),
131
- ): MadeClient<TName, TQueries, TCommands, TRpcs, TStreams, TExtra>;
132
- export function makeClient(
133
- contract: RpcSource & {
134
- readonly declaration: Declared<string, readonly QueryShape[], readonly CommandShape[], readonly StreamShape[], "session" | undefined>;
135
- },
136
- options: ClientOptions & {
137
- readonly group?: RpcSource;
138
- readonly registry?: AtomRegistry.AtomRegistry;
139
- },
140
- ): Layer.Layer<never> {
141
- const connection = rpcClient(contract.declaration.name, options.group ?? contract, options);
142
- const bindingOptions: BindOptions = options;
143
- const owner = bindingOwner(contract.declaration.keyScope, bindingOptions.registry);
144
- const { live, resume, resumeWindow } = bindingOptions;
145
- const automatic = automaticLive(connection.Client, contract.declaration.name, owner, resume, live, resumeWindow);
146
- const operations = clientOperations(connection.Client, automatic, owner);
147
- const api = bindOperations(contract.declaration, operations, automatic.subscription);
148
- return Object.assign(connection, { api, sync: operations.sync });
149
- }
@@ -1,18 +1,16 @@
1
- import { Effect, Option, Schema, Stream } from "effect";
1
+ import { Effect, Schema, Stream } from "effect";
2
2
  import * as Atom from "effect/reactivity/Atom";
3
3
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
5
5
  import * as Reactivity from "effect/reactivity/Reactivity";
6
6
  import type { Rpc } from "effect/rpc";
7
- import type { Key } from "@shivaedev/changes/keys.ts";
8
7
  import type { BindingOwner } from "#adapters/bindingOwner.ts";
9
- import { clientId } from "#adapters/clientId.ts";
10
8
  import { streamingClient, unaryClient } from "#adapters/erasedClient.ts";
11
9
  import type { automaticLive } from "#automaticLive.ts";
12
10
  import type { QueryOptions, RunOptions } from "#bind.ts";
13
11
  import { clientActivities } from "#clientActivities.ts";
14
- import { clientInvalidationKeys, clientReadKeys } from "#clientKeys.ts";
15
12
  import { commandPayload } from "#commandPayload.ts";
13
+ import { COMMAND_REFLECTED } from "#commandReflected.ts";
16
14
  import { CommandSignal, untilReflected } from "#commandSignal.ts";
17
15
  import { waitForConnection } from "#connectionReadiness.ts";
18
16
  import { LIVE_SYNC } from "#liveSyncRpc.ts";
@@ -39,10 +37,21 @@ export function clientOperations(
39
37
  return owner === undefined ? effect : Effect.suspend(() => AtomRegistry.getResult(owner.registry, ordinaryClient.runtime.atom(effect)));
40
38
  }
41
39
 
42
- const observed = Effect.map(
43
- CommandSignal,
44
- (signal): CommandObserver => ({ pending: () => clientActivities.get(ordinaryClient)?.reflecting() ?? (() => undefined), signal }),
45
- );
40
+ const observed = Effect.gen(function* () {
41
+ const signal = yield* CommandSignal;
42
+ const reactivity = yield* Reactivity.Reactivity;
43
+ return yield* Effect.sync(
44
+ (): CommandObserver => ({
45
+ pending: () => clientActivities.get(ordinaryClient)?.reflecting() ?? (() => undefined),
46
+ signal: (state) => {
47
+ signal(state);
48
+ if (state === "reflected") {
49
+ reactivity.invalidateUnsafe([COMMAND_REFLECTED]);
50
+ }
51
+ },
52
+ }),
53
+ );
54
+ });
46
55
 
47
56
  function boundQuery(tag: string, query: QueryShape) {
48
57
  const cached = new WeakMap<ReturnType<typeof ordinaryClient.query>, ReturnType<typeof ordinaryClient.query>>();
@@ -59,18 +68,12 @@ export function clientOperations(
59
68
  if (existing !== undefined) {
60
69
  return existing;
61
70
  }
62
- const local = query.reads(payload, Option.none());
63
- const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${clientId()}` }];
64
- const dependencies =
65
- local.length === 0 ? [...keys, { _tag: "List" as const, collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` }] : keys;
66
71
  const reference = { payload, query: query.name };
67
72
  const result = automatic.query(
68
73
  atom,
69
74
  reference,
70
- keys,
71
75
  Schema.toEquivalence(query.success),
72
76
  Schema.decodeUnknownSync(Schema.toType(query.success)),
73
- (source) => ordinaryClient.runtime.factory.withReactivity(clientReadKeys(dependencies, owner?.context))(source),
74
77
  headers,
75
78
  );
76
79
  function warm(get: Atom.AtomContext): boolean {
@@ -88,13 +91,6 @@ export function clientOperations(
88
91
  }
89
92
 
90
93
  function boundCommand(tag: string, command: CommandShape) {
91
- function invalidate(payload: unknown, result: unknown) {
92
- const keys: readonly Key[] = [
93
- ...command.invalidates(payload, result),
94
- { _tag: "List", collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` },
95
- ];
96
- return Reactivity.invalidate(clientInvalidationKeys(keys, owner?.context));
97
- }
98
94
  function send(observer: CommandObserver, payload: unknown, subject: string | undefined) {
99
95
  return ordinaryClient.use((client) =>
100
96
  commandPayload(command, payload).pipe(
@@ -102,7 +98,6 @@ export function clientOperations(
102
98
  Effect.flatMap((validated) =>
103
99
  reflectCommand(client, observer, (options) => client(tag, validated, { headers: withSubject(options?.headers, subject) })),
104
100
  ),
105
- Effect.tap((result) => invalidate(payload, result)),
106
101
  ),
107
102
  );
108
103
  }
@@ -0,0 +1,2 @@
1
+ // A client's live subscriptions that failed open again after its next reflected command, which may have changed what they read.
2
+ export const COMMAND_REFLECTED = "@shivaedev/contract/commandReflected";
package/src/live.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Cause, Effect, Option, Queue, Schema, type Stream } from "effect";
2
2
  import * as Atom from "effect/reactivity/Atom";
3
3
  import { Key } from "@shivaedev/changes/keys.ts";
4
- import { clientReadKeys, type KeyContext } from "#clientKeys.ts";
4
+ import { COMMAND_REFLECTED } from "#commandReflected.ts";
5
5
  import { liveAttempt } from "#liveAttempt.ts";
6
6
  import { liveRetry } from "#liveRetry.ts";
7
7
  import type { SubscriptionEvent } from "#queryUpdate.ts";
@@ -20,10 +20,8 @@ export interface LiveStatus<E> {
20
20
  readonly pending: number;
21
21
  }
22
22
  export interface LiveOptions<E, R> {
23
- readonly keyContext?: KeyContext | undefined;
24
23
  readonly resume?: Atom.Atom<unknown>;
25
24
  readonly retryDelay?: import("effect").Duration.Input;
26
- readonly retryKeys?: readonly (typeof Key.Type)[];
27
25
  readonly stream: Stream.Stream<SubscriptionEvent, E, R>;
28
26
  }
29
27
 
@@ -53,7 +51,7 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
53
51
  get.mount(status);
54
52
  get.mount(paused);
55
53
  const resumed = yield* Queue.unbounded<void>();
56
- yield* retryOnChange(status, clientReadKeys(options.retryKeys ?? [], options.keyContext), () => get.refreshSelf());
54
+ yield* retryOnChange(status, [COMMAND_REFLECTED], () => get.refreshSelf());
57
55
  function update(value: Partial<LiveStatus<E>>) {
58
56
  get.set(status, { ...get.once(status), ...value });
59
57
  }
@@ -0,0 +1,78 @@
1
+ import { Context, type Effect, type Layer, type Scope } from "effect";
2
+ import type * as Atom from "effect/reactivity/Atom";
3
+ import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
+ import type * as AtomRpc from "effect/reactivity/AtomRpc";
5
+ import type { Rpc, RpcClient, RpcGroup } from "effect/rpc";
6
+ import type { RpcClientError } from "effect/rpc/RpcClientError";
7
+ import { bindingOwner } from "#adapters/bindingOwner.ts";
8
+ import { automaticLive, type LiveBound } from "#automaticLive.ts";
9
+ import type { Bound } from "#bind.ts";
10
+ import { bindOperations } from "#bindOperations.ts";
11
+ import type { ClientOptions } from "#ClientOptions.ts";
12
+ import type { ActiveClient } from "#clientActivity.ts";
13
+ import { clientOperations } from "#clientOperations.ts";
14
+ import type { Contract, Declared } from "#contract.ts";
15
+ import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
16
+ import { rpcClient } from "#rpcClient.ts";
17
+
18
+ // Every client made from contracts shares this service identity, so a contract's bound type does not depend on the record it was made from.
19
+ export interface ContractsClient {
20
+ readonly ContractsClient: unique symbol;
21
+ }
22
+
23
+ export interface ClientContract {
24
+ readonly annotations: Context.Context<never>;
25
+ readonly declaration: Declared<string, readonly QueryShape[], readonly CommandShape[], readonly StreamShape[], "session" | undefined>;
26
+ readonly requests: ReadonlyMap<string, Rpc.Any>;
27
+ }
28
+
29
+ export type Contracts = Readonly<Record<string, ClientContract>>;
30
+
31
+ export type ContractClient<TContract> =
32
+ TContract extends Contract<infer TName, infer TQueries, infer TCommands, infer TRpcs, infer TStreams, infer _TScope>
33
+ ? Bound<TName, TQueries, TCommands, TRpcs, ContractsClient, TStreams> & LiveBound
34
+ : never;
35
+
36
+ export type ContractClients<TContracts extends Contracts> = { readonly [TKey in keyof TContracts]: ContractClient<TContracts[TKey]> };
37
+
38
+ type ContractRpcs<TContracts extends Contracts> = { [TKey in keyof TContracts]: RpcGroup.Rpcs<TContracts[TKey]> }[keyof TContracts];
39
+
40
+ type KeyScope<TContracts extends Contracts> = TContracts[keyof TContracts]["declaration"]["keyScope"];
41
+
42
+ export type MadeClient<TContracts extends Contracts> = Layer.Layer<ContractsClient> &
43
+ ActiveClient & {
44
+ readonly api: ContractClients<TContracts>;
45
+ readonly Client: AtomRpc.AtomRpcClient<ContractsClient, string, ContractRpcs<TContracts>>;
46
+ readonly client: Effect.Effect<
47
+ RpcClient.RpcClient<ContractRpcs<TContracts>, RpcClientError>,
48
+ never,
49
+ Scope.Scope | Rpc.MiddlewareClient<ContractRpcs<TContracts>>
50
+ >;
51
+ readonly runtime: Atom.AtomRuntime<ContractsClient>;
52
+ readonly sync: Effect.Effect<void, RpcClientError, ContractsClient>;
53
+ };
54
+
55
+ export function makeClient<const TContracts extends Contracts>(
56
+ contracts: TContracts,
57
+ ...options: "session" extends KeyScope<TContracts>
58
+ ? [options: ClientOptions & { readonly registry: AtomRegistry.AtomRegistry }]
59
+ : [options?: ClientOptions]
60
+ ): MadeClient<TContracts>;
61
+ export function makeClient(contracts: Contracts, options: ClientOptions = {}): Layer.Layer<never> {
62
+ const list = Object.values(contracts);
63
+ const source = {
64
+ annotations: Context.mergeAll(...list.map((contract) => contract.annotations)),
65
+ requests: new Map(list.flatMap((contract) => [...contract.requests])),
66
+ };
67
+ const connection = rpcClient("@shivaedev/contract/Contracts", source, options);
68
+ const { registry, resume, resumeWindow } = options;
69
+ const bound = Object.entries(contracts).map(([key, { declaration }]) => {
70
+ const owner = bindingOwner(declaration.keyScope, registry);
71
+ const automatic = automaticLive(connection.Client, declaration.name, owner, resume, resumeWindow);
72
+ const operations = clientOperations(connection.Client, automatic, owner);
73
+ return { api: [key, bindOperations(declaration, operations, automatic.subscription)] as const, owner, sync: operations.sync };
74
+ });
75
+ // A sync runs through the session's registry when the record holds a session-scoped contract, as that contract's own calls do.
76
+ const sync = (bound.find((binding) => binding.owner !== undefined) ?? bound[0])?.sync;
77
+ return Object.assign(connection, { api: Object.fromEntries(bound.map((binding) => binding.api)), sync });
78
+ }
@@ -1,29 +1,6 @@
1
1
  import * as AsyncResult from "effect/reactivity/AsyncResult";
2
- import type * as Atom from "effect/reactivity/Atom";
3
2
  import type { LiveStatus } from "#live.ts";
4
- import { type QuerySignals, querySignals, shareQuerySignals } from "#querySignals.ts";
5
- import { wrapAtom } from "#wrapAtom.ts";
6
-
7
- export function queryProgress<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
8
- const signals = querySignals(atom);
9
- const tracked = wrapAtom(atom, (get) => {
10
- get.mount(signals);
11
- let published = false;
12
- function publish(result: AsyncResult.AsyncResult<A, E>) {
13
- published = true;
14
- get.setSelf(result);
15
- get.set(signals, recordCompletion(get.once(signals), result));
16
- }
17
- const context = new Proxy(get, { get: (target, key, receiver) => (key === "setSelf" ? publish : Reflect.get(target, key, receiver)) });
18
- const value = atom.read(context);
19
- if (!published) {
20
- get.set(signals, recordCompletion(get.once(signals), value));
21
- }
22
- return value;
23
- });
24
- shareQuerySignals(tracked, atom);
25
- return tracked;
26
- }
3
+ import type { QuerySignals } from "#querySignals.ts";
27
4
 
28
5
  export function recordCompletion<A, E>(current: QuerySignals, result: AsyncResult.AsyncResult<A, E>): QuerySignals {
29
6
  const pending = AsyncResult.isInitial(result) || result.waiting;
@@ -10,6 +10,10 @@ export const retryOnChange = Effect.fnUntraced(function* <E>(status: Atom.Atom<L
10
10
  const dispatcher = registry.schedulerAsync.makeDispatcher();
11
11
  let active = true;
12
12
  function canRetry() {
13
+ // A command can be reflected while its registry disposes the connection, after the status is gone and before this listener leaves.
14
+ if (!registry.getNodes().has(status)) {
15
+ return false;
16
+ }
13
17
  const current = registry.get(status);
14
18
  return (
15
19
  current.connection === "failed"
package/src/rpcClient.ts CHANGED
@@ -3,10 +3,10 @@ import * as Atom from "effect/reactivity/Atom";
3
3
  import * as AtomRpc from "effect/reactivity/AtomRpc";
4
4
  import { type Rpc, RpcClient, RpcGroup } from "effect/rpc";
5
5
  import type { RpcClientError } from "effect/rpc/RpcClientError";
6
+ import type { ClientOptions } from "#ClientOptions.ts";
6
7
  import { catchUp } from "#catchUp.ts";
7
8
  import { clientActivities, makeActivity } from "#clientActivities.ts";
8
9
  import { Activity } from "#clientActivity.ts";
9
- import type { ClientOptions } from "#clientOptions.ts";
10
10
  import { ConnectionScope, connectionProtocol } from "#connectionProtocol.ts";
11
11
  import { commandConnections } from "#connectionReadiness.ts";
12
12
  import { type LiveSyncRpc, liveSyncRpc } from "#liveSyncRpc.ts";
@@ -17,6 +17,7 @@ import { socketProtocol } from "#socketProtocol.ts";
17
17
  import { withClientProtocol } from "#withClientProtocol.ts";
18
18
 
19
19
  declare const window: ResumeWindow | undefined;
20
+ declare const location: { readonly href: string } | undefined;
20
21
 
21
22
  export interface RpcSource {
22
23
  readonly annotations: Context.Context<never>;
@@ -36,7 +37,7 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
36
37
  identity,
37
38
  resume: options.resume,
38
39
  resumeWindow: options.resumeWindow ?? (typeof window === "undefined" ? undefined : window),
39
- url: options.url.replace(/^http/u, "ws"),
40
+ url: (options.url ?? pageRpcUrl()).replace(/^http/u, "ws"),
40
41
  webSocketConstructor: options.webSocketConstructor,
41
42
  });
42
43
  }
@@ -95,4 +96,8 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
95
96
  return Object.assign(layer, { [Activity]: activity.activity, Client, client: directClient, runtime: Client.runtime });
96
97
  }
97
98
 
99
+ function pageRpcUrl() {
100
+ return new URL("/rpc", typeof location === "undefined" ? undefined : location.href).href;
101
+ }
102
+
98
103
  export const socketIdentity = Atom.make<string | undefined>(undefined);
@@ -3,7 +3,7 @@ import * as Atom from "effect/reactivity/Atom";
3
3
  import { RpcClient, RpcSerialization } from "effect/rpc";
4
4
  import * as Socket from "effect/socket/Socket";
5
5
  import { resumeSocket } from "#adapters/resumeSocket.ts";
6
- import type { ClientOptions } from "#clientOptions.ts";
6
+ import type { ClientOptions } from "#ClientOptions.ts";
7
7
  import { connectionProtocol } from "#connectionProtocol.ts";
8
8
  import type { ResumeWindow } from "#resume.ts";
9
9
  import { SocketClock } from "#SocketClock.ts";
@@ -1,7 +0,0 @@
1
- import { type Key } from "@shivaedev/changes/keys.ts";
2
- export interface KeyContext {
3
- readonly scope: string;
4
- }
5
- export declare function clientReadKeys(keys: readonly Key[], context?: KeyContext): readonly string[];
6
- export declare function clientInvalidationKeys(keys: readonly Key[], context?: KeyContext): readonly string[];
7
- //# sourceMappingURL=clientKeys.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"clientKeys.d.ts","sourceRoot":"","sources":["../src/clientKeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,GAAG,EAAY,MAAM,4BAA4B,CAAC;AAElF,MAAM,WAAW,UAAU;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB;AAMD,wBAAgB,cAAc,CAAC,IAAI,EAAE,SAAS,GAAG,EAAE,EAAE,OAAO,CAAC,EAAE,UAAU,GAAG,SAAS,MAAM,EAAE,CAE5F;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,SAAS,GAAG,EAAE,EAAE,OAAO,CAAC,EAAE,UAAU,GAAG,SAAS,MAAM,EAAE,CAEpG"}
@@ -1,11 +0,0 @@
1
- import { invalidationKeys, readKeys } from "@shivaedev/changes/keys.ts";
2
- function contextual(keys, context) {
3
- return context === undefined ? keys : keys.map((key) => `${JSON.stringify(["session", context.scope])}:${key}`);
4
- }
5
- export function clientReadKeys(keys, context) {
6
- return contextual(readKeys(keys), context);
7
- }
8
- export function clientInvalidationKeys(keys, context) {
9
- return contextual(invalidationKeys(keys), context);
10
- }
11
- //# sourceMappingURL=clientKeys.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"clientKeys.js","sourceRoot":"","sources":["../src/clientKeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAY,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAMlF,SAAS,UAAU,CAAC,IAAuB,EAAE,OAAoB;IAChE,OAAO,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC;AACjH,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,IAAoB,EAAE,OAAoB;IACxE,OAAO,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,IAAoB,EAAE,OAAoB;IAChF,OAAO,UAAU,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;AACpD,CAAC"}
@@ -1,31 +0,0 @@
1
- import type { Context, Effect, Layer, Scope } from "effect";
2
- import type * as Atom from "effect/reactivity/Atom";
3
- import type * as AtomRpc from "effect/reactivity/AtomRpc";
4
- import type { Rpc, RpcClient } from "effect/rpc";
5
- import type { RpcClientError } from "effect/rpc/RpcClientError";
6
- import type * as Socket from "effect/socket/Socket";
7
- import type { LiveBound } from "#automaticLive.ts";
8
- import type { Bound } from "#bind.ts";
9
- import type { ActiveClient } from "#clientActivity.ts";
10
- import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
11
- import type { ResumeSource, ResumeWindow } from "#resume.ts";
12
- export interface ClientOptions {
13
- readonly bearerToken?: string;
14
- readonly headers?: Readonly<Record<string, string>>;
15
- readonly live?: boolean;
16
- readonly protocol?: Layer.Layer<RpcClient.Protocol> | ((identity: string | undefined) => Layer.Layer<RpcClient.Protocol>);
17
- readonly resume?: ResumeSource;
18
- readonly resumeWindow?: ResumeWindow;
19
- readonly runtime?: Atom.RuntimeFactory;
20
- readonly url: string;
21
- readonly webSocketConstructor?: Layer.Layer<Socket.WebSocketConstructor>;
22
- }
23
- export type ClientService<TName extends string, TRpcs extends Rpc.Any> = Context.ServiceClass.Shape<`${TName}/Client`, RpcClient.RpcClient.Flat<TRpcs, RpcClientError>>;
24
- export type MadeClient<TName extends string, TQueries extends readonly QueryShape[], TCommands extends readonly CommandShape[], TRpcs extends Rpc.Any, TStreams extends readonly StreamShape[], TExtra extends Rpc.Any> = Layer.Layer<ClientService<TName, TRpcs | TExtra>> & ActiveClient & {
25
- readonly api: Bound<TName, TQueries, TCommands, TRpcs, ClientService<TName, TRpcs | TExtra>, TStreams> & LiveBound;
26
- readonly Client: AtomRpc.AtomRpcClient<ClientService<TName, TRpcs | TExtra>, `${TName}/Client`, TRpcs | TExtra>;
27
- readonly client: Effect.Effect<RpcClient.RpcClient<TRpcs | TExtra, RpcClientError>, never, Scope.Scope | Rpc.MiddlewareClient<TRpcs | TExtra>>;
28
- readonly runtime: Atom.AtomRuntime<ClientService<TName, TRpcs | TExtra>>;
29
- readonly sync: Effect.Effect<void, RpcClientError, ClientService<TName, TRpcs | TExtra>>;
30
- };
31
- //# sourceMappingURL=clientOptions.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"clientOptions.d.ts","sourceRoot":"","sources":["../src/clientOptions.ts"],"names":[],"mappings":"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"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=clientOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"clientOptions.js","sourceRoot":"","sources":["../src/clientOptions.ts"],"names":[],"mappings":""}
package/src/clientKeys.ts DELETED
@@ -1,17 +0,0 @@
1
- import { invalidationKeys, type Key, readKeys } from "@shivaedev/changes/keys.ts";
2
-
3
- export interface KeyContext {
4
- readonly scope: string;
5
- }
6
-
7
- function contextual(keys: readonly string[], context?: KeyContext): readonly string[] {
8
- return context === undefined ? keys : keys.map((key) => `${JSON.stringify(["session", context.scope])}:${key}`);
9
- }
10
-
11
- export function clientReadKeys(keys: readonly Key[], context?: KeyContext): readonly string[] {
12
- return contextual(readKeys(keys), context);
13
- }
14
-
15
- export function clientInvalidationKeys(keys: readonly Key[], context?: KeyContext): readonly string[] {
16
- return contextual(invalidationKeys(keys), context);
17
- }
@@ -1,44 +0,0 @@
1
- import type { Context, Effect, Layer, Scope } from "effect";
2
- import type * as Atom from "effect/reactivity/Atom";
3
- import type * as AtomRpc from "effect/reactivity/AtomRpc";
4
- import type { Rpc, RpcClient } from "effect/rpc";
5
- import type { RpcClientError } from "effect/rpc/RpcClientError";
6
- import type * as Socket from "effect/socket/Socket";
7
- import type { LiveBound } from "#automaticLive.ts";
8
- import type { Bound } from "#bind.ts";
9
- import type { ActiveClient } from "#clientActivity.ts";
10
- import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
11
- import type { ResumeSource, ResumeWindow } from "#resume.ts";
12
-
13
- export interface ClientOptions {
14
- readonly bearerToken?: string;
15
- readonly headers?: Readonly<Record<string, string>>;
16
- readonly live?: boolean;
17
- readonly protocol?: Layer.Layer<RpcClient.Protocol> | ((identity: string | undefined) => Layer.Layer<RpcClient.Protocol>);
18
- readonly resume?: ResumeSource;
19
- readonly resumeWindow?: ResumeWindow;
20
- readonly runtime?: Atom.RuntimeFactory;
21
- readonly url: string;
22
- readonly webSocketConstructor?: Layer.Layer<Socket.WebSocketConstructor>;
23
- }
24
-
25
- export type ClientService<TName extends string, TRpcs extends Rpc.Any> = Context.ServiceClass.Shape<
26
- `${TName}/Client`,
27
- RpcClient.RpcClient.Flat<TRpcs, RpcClientError>
28
- >;
29
-
30
- export type MadeClient<
31
- TName extends string,
32
- TQueries extends readonly QueryShape[],
33
- TCommands extends readonly CommandShape[],
34
- TRpcs extends Rpc.Any,
35
- TStreams extends readonly StreamShape[],
36
- TExtra extends Rpc.Any,
37
- > = Layer.Layer<ClientService<TName, TRpcs | TExtra>> &
38
- ActiveClient & {
39
- readonly api: Bound<TName, TQueries, TCommands, TRpcs, ClientService<TName, TRpcs | TExtra>, TStreams> & LiveBound;
40
- readonly Client: AtomRpc.AtomRpcClient<ClientService<TName, TRpcs | TExtra>, `${TName}/Client`, TRpcs | TExtra>;
41
- readonly client: Effect.Effect<RpcClient.RpcClient<TRpcs | TExtra, RpcClientError>, never, Scope.Scope | Rpc.MiddlewareClient<TRpcs | TExtra>>;
42
- readonly runtime: Atom.AtomRuntime<ClientService<TName, TRpcs | TExtra>>;
43
- readonly sync: Effect.Effect<void, RpcClientError, ClientService<TName, TRpcs | TExtra>>;
44
- };