@shivaedev/contract 0.28.0 → 0.30.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 (79) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +63 -4
  3. package/dist/QueryServerReads.d.ts +5 -0
  4. package/dist/QueryServerReads.d.ts.map +1 -0
  5. package/dist/QueryServerReads.js +2 -0
  6. package/dist/QueryServerReads.js.map +1 -0
  7. package/dist/WebSocketRequired.d.ts +8 -0
  8. package/dist/WebSocketRequired.d.ts.map +1 -0
  9. package/dist/WebSocketRequired.js +4 -0
  10. package/dist/WebSocketRequired.js.map +1 -0
  11. package/dist/automaticLive.js +1 -1
  12. package/dist/automaticLive.js.map +1 -1
  13. package/dist/internal/automaticQuery.d.ts +1 -1
  14. package/dist/internal/automaticQuery.d.ts.map +1 -1
  15. package/dist/internal/automaticQuery.js +21 -4
  16. package/dist/internal/automaticQuery.js.map +1 -1
  17. package/dist/internal/operationDeclaration.d.ts +17 -3
  18. package/dist/internal/operationDeclaration.d.ts.map +1 -1
  19. package/dist/internal/operationDeclaration.js.map +1 -1
  20. package/dist/internal/queryReactivity.d.ts.map +1 -1
  21. package/dist/internal/queryReactivity.js +10 -5
  22. package/dist/internal/queryReactivity.js.map +1 -1
  23. package/dist/internal/queryReadKeys.d.ts +5 -0
  24. package/dist/internal/queryReadKeys.d.ts.map +1 -0
  25. package/dist/internal/queryReadKeys.js +6 -0
  26. package/dist/internal/queryReadKeys.js.map +1 -0
  27. package/dist/internal/resolveQueries.d.ts +8 -0
  28. package/dist/internal/resolveQueries.d.ts.map +1 -0
  29. package/dist/internal/resolveQueries.js +8 -0
  30. package/dist/internal/resolveQueries.js.map +1 -0
  31. package/dist/internal/retryOnChange.d.ts.map +1 -1
  32. package/dist/internal/retryOnChange.js +8 -3
  33. package/dist/internal/retryOnChange.js.map +1 -1
  34. package/dist/makeLiveServer.d.ts +1 -1
  35. package/dist/makeLiveServer.d.ts.map +1 -1
  36. package/dist/makeLiveServer.js +5 -3
  37. package/dist/makeLiveServer.js.map +1 -1
  38. package/dist/operation.d.ts +12 -11
  39. package/dist/operation.d.ts.map +1 -1
  40. package/dist/operation.js +4 -1
  41. package/dist/operation.js.map +1 -1
  42. package/dist/permissionReadPolicy.d.ts +21 -0
  43. package/dist/permissionReadPolicy.d.ts.map +1 -0
  44. package/dist/permissionReadPolicy.js +10 -0
  45. package/dist/permissionReadPolicy.js.map +1 -0
  46. package/dist/publicConfig.d.ts +1 -1
  47. package/dist/publicConfig.d.ts.map +1 -1
  48. package/dist/queryKeys.d.ts +9 -0
  49. package/dist/queryKeys.d.ts.map +1 -0
  50. package/dist/queryKeys.js +13 -0
  51. package/dist/queryKeys.js.map +1 -0
  52. package/dist/querySubscription.d.ts +1 -0
  53. package/dist/querySubscription.d.ts.map +1 -1
  54. package/dist/querySubscription.js +5 -2
  55. package/dist/querySubscription.js.map +1 -1
  56. package/dist/readPolicy.d.ts.map +1 -1
  57. package/dist/readPolicy.js +4 -0
  58. package/dist/readPolicy.js.map +1 -1
  59. package/dist/serverMetadata.d.ts +3 -5
  60. package/dist/serverMetadata.d.ts.map +1 -1
  61. package/dist/serverMetadata.js +4 -12
  62. package/dist/serverMetadata.js.map +1 -1
  63. package/package.json +8 -7
  64. package/src/QueryServerReads.ts +8 -0
  65. package/src/WebSocketRequired.ts +3 -0
  66. package/src/automaticLive.ts +1 -1
  67. package/src/internal/automaticQuery.ts +21 -5
  68. package/src/internal/operationDeclaration.ts +26 -3
  69. package/src/internal/queryReactivity.ts +14 -5
  70. package/src/internal/queryReadKeys.ts +8 -0
  71. package/src/internal/resolveQueries.ts +10 -0
  72. package/src/internal/retryOnChange.ts +10 -3
  73. package/src/makeLiveServer.ts +5 -3
  74. package/src/operation.ts +14 -14
  75. package/src/permissionReadPolicy.ts +28 -0
  76. package/src/queryKeys.ts +23 -0
  77. package/src/querySubscription.ts +8 -2
  78. package/src/readPolicy.ts +4 -0
  79. package/src/serverMetadata.ts +5 -21
@@ -1,4 +1,4 @@
1
- import { Duration, Effect } from "effect";
1
+ import { Cause, Duration, Effect, Option, Predicate } from "effect";
2
2
  import * as AsyncResult from "effect/reactivity/AsyncResult";
3
3
  import * as Atom from "effect/reactivity/Atom";
4
4
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
@@ -55,6 +55,15 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
55
55
  pending = undefined;
56
56
  dequeue();
57
57
  }
58
+ function reread() {
59
+ if (
60
+ !Option.exists(AsyncResult.cause(get.once(source)), (cause) =>
61
+ Option.exists(Cause.findErrorOption(cause), Predicate.isTagged("QueryReadDenied")),
62
+ )
63
+ ) {
64
+ get.refresh(source);
65
+ }
66
+ }
58
67
  function refresh(active: () => boolean) {
59
68
  if (!active()) {
60
69
  dequeue();
@@ -64,7 +73,7 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
64
73
  pending = active;
65
74
  } else {
66
75
  pending = undefined;
67
- get.refresh(source);
76
+ reread();
68
77
  dequeue();
69
78
  }
70
79
  }
@@ -77,7 +86,7 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
77
86
  const delay = Duration.toMillis(Duration.fromInputUnsafe(get.once(queryCoalesceWindow(wrapped)) ?? batch.window ?? 0));
78
87
  if (delay === 0) {
79
88
  clear();
80
- get.refresh(source);
89
+ reread();
81
90
  } else if (!scheduled) {
82
91
  queued ??= queue?.();
83
92
  scheduled = true;
@@ -90,7 +99,7 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
90
99
  reactivity.registerUnsafe(keys, () => {
91
100
  if (!liveBatches.has(reactivity)) {
92
101
  clear();
93
- get.refresh(source);
102
+ reread();
94
103
  }
95
104
  }),
96
105
  );
@@ -100,7 +109,7 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
100
109
  const active = pending;
101
110
  pending = undefined;
102
111
  if (active()) {
103
- get.refresh(source);
112
+ reread();
104
113
  }
105
114
  dequeue();
106
115
  }
@@ -0,0 +1,8 @@
1
+ import { Effect, type Option } from "effect";
2
+ import type { QueryShape } from "#operation.ts";
3
+ import type { Viewer } from "#readPolicy.ts";
4
+
5
+ export const queryReadKeys = Effect.fnUntraced(function* <E, R>(query: QueryShape<E, R>, payload: unknown, viewer: Option.Option<Viewer>) {
6
+ const derived = query.serverReads === undefined ? [] : yield* query.serverReads(payload, viewer);
7
+ return [...query.reads(payload, viewer), ...derived];
8
+ });
@@ -0,0 +1,10 @@
1
+ import { Effect } from "effect";
2
+ import type { QueryShape } from "#operation.ts";
3
+ import type { QueryReference } from "#serverMetadata.ts";
4
+
5
+ export function resolveQueries(queries: readonly QueryShape[], requested: readonly QueryReference[]) {
6
+ return Effect.forEach(requested, (reference) => {
7
+ const query = queries.find((candidate) => candidate.name === reference.query);
8
+ return query === undefined ? Effect.die(new Error(`Unknown query: ${reference.query}`)) : Effect.succeed({ payload: reference.payload, query });
9
+ });
10
+ }
@@ -1,4 +1,4 @@
1
- import { Effect } from "effect";
1
+ import { Cause, Effect, Option, Predicate } from "effect";
2
2
  import type * as Atom from "effect/reactivity/Atom";
3
3
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import * as Reactivity from "effect/reactivity/Reactivity";
@@ -9,13 +9,20 @@ export const retryOnChange = Effect.fnUntraced(function* <E>(status: Atom.Atom<L
9
9
  const registry = yield* AtomRegistry.AtomRegistry;
10
10
  const dispatcher = registry.schedulerAsync.makeDispatcher();
11
11
  let active = true;
12
+ function canRetry() {
13
+ const current = registry.get(status);
14
+ return (
15
+ current.connection === "failed"
16
+ && !Option.exists(current.failure, (cause) => Option.exists(Cause.findErrorOption(cause), Predicate.isTagged("QueryReadDenied")))
17
+ );
18
+ }
12
19
  function retry() {
13
- if (active && registry.get(status).connection === "failed") {
20
+ if (active && canRetry()) {
14
21
  restart();
15
22
  }
16
23
  }
17
24
  function changed() {
18
- if (registry.get(status).connection === "failed") {
25
+ if (canRetry()) {
19
26
  dispatcher.scheduleTask(retry, 0);
20
27
  }
21
28
  }
@@ -12,7 +12,7 @@ export const makeLiveServer = Effect.gen(function* () {
12
12
  const reactivity = yield* Reactivity.Reactivity;
13
13
  let openStreams = 0;
14
14
  const resyncKey = `@shivaedev/contract/resync/${yield* Random.nextInt}`;
15
- function open(keys: readonly Key[], context?: KeyContext): Stream.Stream<LiveHint> {
15
+ function open(keys: readonly Key[], context?: KeyContext, globalKeys: readonly Key[] = []): Stream.Stream<LiveHint> {
16
16
  return Stream.unwrap(
17
17
  Effect.gen(function* () {
18
18
  const { offer, queue } = yield* liveHintQueue;
@@ -20,6 +20,7 @@ export const makeLiveServer = Effect.gen(function* () {
20
20
  let scheduled = false;
21
21
  let resync = false;
22
22
  let active = true;
23
+ const global = new Set(readKeys(globalKeys));
23
24
  function flush() {
24
25
  if (scheduled) {
25
26
  return;
@@ -35,7 +36,8 @@ export const makeLiveServer = Effect.gen(function* () {
35
36
  });
36
37
  }
37
38
  const cancel = keys.map((key) => {
38
- const own = readKeys([key], context);
39
+ const bare = readKeys([key]);
40
+ const own = global.has(bare[0] ?? "") ? bare : readKeys([key], context);
39
41
  return reactivity.registerUnsafe(own, () => {
40
42
  pending.set(own[0] ?? "", key);
41
43
  flush();
@@ -82,7 +84,7 @@ export const makeLiveServer = Effect.gen(function* () {
82
84
  }
83
85
  return yield* compare(hint);
84
86
  });
85
- return open(subscription.keys, context).pipe(Stream.mapEffect(next), Stream.flatMap(Stream.fromIterable));
87
+ return open(subscription.keys, context, subscription.globalKeys).pipe(Stream.mapEffect(next), Stream.flatMap(Stream.fromIterable));
86
88
  }),
87
89
  );
88
90
  }
package/src/operation.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { Option, Schema } from "effect";
2
2
  import type { Key } from "@shivaedev/changes/keys.ts";
3
3
  import type { Bivariant } from "@shivaedev/types/Bivariant.ts";
4
- import { type Loose, operation } from "#internal/operationDeclaration.ts";
4
+ import { type Declaration, type Loose, operation, type QueryDeclaration } from "#internal/operationDeclaration.ts";
5
+ import type { QueryServerReads } from "#QueryServerReads.ts";
5
6
  import type { QueryReadPolicy, Viewer } from "#readPolicy.ts";
6
- import type { MatchingTags, Reject, RejectedBy, RejectionSpecs, Rejections, RejectionUnion } from "#rejection.ts";
7
+ import type { Reject, RejectedBy, RejectionSpecs, Rejections, RejectionUnion } from "#rejection.ts";
7
8
 
8
9
  export type PayloadSchema<TPayload extends Schema.Top | Schema.Struct.Fields> = TPayload extends Schema.Struct.Fields
9
10
  ? Schema.Struct<TPayload>
@@ -27,6 +28,8 @@ export interface QueryShape<E = unknown, R = unknown> extends OperationShape {
27
28
  readonly live?: "rerun-and-compare" | undefined;
28
29
  readonly readPolicy: Bivariant<QueryReadPolicy<unknown, E, R>>;
29
30
  reads: Bivariant<(payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[]>;
31
+ readonly readsCollections?: readonly { readonly name: string }[] | undefined;
32
+ readonly serverReads?: Bivariant<QueryServerReads<unknown, E, R>>;
30
33
  }
31
34
 
32
35
  export interface StreamShape extends OperationShape {
@@ -62,6 +65,8 @@ export interface Query<
62
65
  readonly live?: TLive;
63
66
  readonly readPolicy: QueryReadPolicy<TPayload["Type"], RejectedBy<TSpecs>, R>;
64
67
  reads: (payload: TPayload["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
68
+ readonly readsCollections?: readonly { readonly name: string }[] | undefined;
69
+ readonly serverReads?: QueryServerReads<TPayload["Type"], RejectedBy<TSpecs>, R>;
65
70
  }
66
71
 
67
72
  export interface Streaming<TName extends string, TPayload extends Schema.Top, TSuccess extends Schema.Top, TSpecs extends RejectionSpecs>
@@ -76,12 +81,6 @@ export interface Command<TName extends string, TPayload extends Schema.Top, TSuc
76
81
  readonly kind: "command";
77
82
  }
78
83
 
79
- interface Declaration<TPayload extends Schema.Top | Schema.Struct.Fields, TSuccess extends Schema.Top, TSpecs extends RejectionSpecs> {
80
- readonly payload?: TPayload;
81
- readonly rejections?: TSpecs & MatchingTags<TSpecs>;
82
- readonly success?: TSuccess;
83
- }
84
-
85
84
  export function query<
86
85
  const TName extends string,
87
86
  TPayload extends Schema.Top | Schema.Struct.Fields = Schema.Void,
@@ -91,11 +90,7 @@ export function query<
91
90
  const TLive extends "rerun-and-compare" | undefined = undefined,
92
91
  >(
93
92
  name: TName,
94
- declaration: Declaration<TPayload, TSuccess, TSpecs> & {
95
- readonly live?: TLive;
96
- readonly reads: (payload: PayloadSchema<TPayload>["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
97
- readonly readPolicy: QueryReadPolicy<PayloadSchema<TPayload>["Type"], NoInfer<RejectedBy<TSpecs>>, R>;
98
- },
93
+ declaration: QueryDeclaration<TPayload, TSuccess, TSpecs, R, TLive>,
99
94
  ): NoInfer<Query<TName, PayloadSchema<TPayload>, TSuccess, TSpecs, R, TLive>>;
100
95
  export function query(
101
96
  name: string,
@@ -103,13 +98,18 @@ export function query(
103
98
  readonly live?: "rerun-and-compare" | undefined;
104
99
  readonly reads: (payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[];
105
100
  readonly readPolicy: QueryReadPolicy<unknown, unknown, unknown>;
101
+ readonly readsCollections?: readonly { readonly name: string }[];
102
+ readonly serverReads?: QueryServerReads<unknown, unknown, unknown>;
106
103
  },
107
104
  ): QueryShape {
105
+ const collections: readonly Key[] = declaration.readsCollections?.map((collection) => ({ _tag: "List", collection: collection.name })) ?? [];
108
106
  return {
109
107
  ...operation("query", name, declaration),
110
108
  live: declaration.live,
111
109
  readPolicy: declaration.readPolicy,
112
- reads: declaration.reads,
110
+ reads: (payload, viewer) => [...declaration.reads(payload, viewer), ...collections],
111
+ readsCollections: declaration.readsCollections,
112
+ ...(declaration.serverReads === undefined ? {} : { serverReads: declaration.serverReads }),
113
113
  };
114
114
  }
115
115
 
@@ -0,0 +1,28 @@
1
+ import type { Effect, Option } from "effect";
2
+ import type { QueryReadPolicy, Viewer } from "#readPolicy.ts";
3
+
4
+ const PermissionReadPolicyId = Symbol.for("@shivaedev/contract/PermissionReadPolicy");
5
+
6
+ export interface PermissionReadPolicy<TPayload, E = never, R = never> extends QueryReadPolicy<TPayload, E, R> {
7
+ readonly [PermissionReadPolicyId]: true;
8
+ }
9
+
10
+ export function permissionReadPolicy<TPermission extends { readonly name: string }, E, R>(
11
+ permission: TPermission,
12
+ check: (permission: TPermission, viewer: Option.Option<Viewer>) => Effect.Effect<boolean, E, R>,
13
+ ): PermissionReadPolicy<unknown, E, R> {
14
+ return Object.assign((_payload: unknown, viewer: Option.Option<Viewer>) => check(permission, viewer), {
15
+ [PermissionReadPolicyId]: true as const,
16
+ });
17
+ }
18
+
19
+ export function isPermissionReadPolicy(policy: QueryReadPolicy<unknown, unknown, unknown>): boolean {
20
+ return PermissionReadPolicyId in policy;
21
+ }
22
+
23
+ export type CollectionReads<TPayload, E, R> =
24
+ | { readonly readsCollections?: never; readonly readPolicy: QueryReadPolicy<TPayload, E, R> }
25
+ | {
26
+ readonly readsCollections: readonly { readonly name: string }[];
27
+ readonly readPolicy: PermissionReadPolicy<TPayload, E, R>;
28
+ };
@@ -0,0 +1,23 @@
1
+ import { Effect, Option } from "effect";
2
+ import type { Key } from "@shivaedev/changes/keys.ts";
3
+ import type { QueryServices } from "#contract.ts";
4
+ import { queryReadKeys } from "#internal/queryReadKeys.ts";
5
+ import { resolveQueries } from "#internal/resolveQueries.ts";
6
+ import type { QueryShape } from "#operation.ts";
7
+ import { checkQuery, type Viewer } from "#readPolicy.ts";
8
+ import type { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
9
+ import type { QueryReference } from "#serverMetadata.ts";
10
+
11
+ export function queryKeys<const TQueries extends readonly QueryShape[]>(
12
+ queries: TQueries,
13
+ requested: readonly QueryReference[],
14
+ viewer?: Option.Option<Viewer>,
15
+ ): Effect.Effect<readonly Key[], TQueries[number]["error"]["Type"] | MissingReadPolicy | QueryReadDenied, QueryServices<TQueries[number]>>;
16
+ export function queryKeys(queries: readonly QueryShape[], requested: readonly QueryReference[], viewer: Option.Option<Viewer> = Option.none()) {
17
+ return Effect.fnUntraced(function* () {
18
+ const resolved = yield* resolveQueries(queries, requested);
19
+ yield* Effect.forEach(resolved, ({ query, payload }) => checkQuery(query, payload, viewer));
20
+ const scopes = yield* Effect.forEach(resolved, ({ query, payload }) => queryReadKeys(query, payload, viewer));
21
+ return scopes.flat();
22
+ })();
23
+ }
@@ -2,6 +2,7 @@ import { Context, Effect, type Option } from "effect";
2
2
  import { Rpc } from "effect/rpc";
3
3
  import type { Key } from "@shivaedev/changes/keys.ts";
4
4
  import { policyContext } from "#internal/policyContext.ts";
5
+ import { queryReadKeys } from "#internal/queryReadKeys.ts";
5
6
  import { checkQuery, type PolicyChannels, type Viewer } from "#readPolicy.ts";
6
7
  import type { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
7
8
  import { ChangesQueries, type QueryReference, type QueryRequest } from "#serverMetadata.ts";
@@ -10,6 +11,7 @@ export type QueryRerun<E = unknown, R = never> = (request: QueryRequest) => Effe
10
11
 
11
12
  export interface QuerySubscription<E = never, R = never> {
12
13
  readonly authorized: Effect.Effect<boolean, E, R>;
14
+ readonly globalKeys?: readonly Key[];
13
15
  readonly keys: readonly Key[];
14
16
  readonly queries?: readonly QueryRequest[];
15
17
  readonly scopes: readonly (readonly Key[])[];
@@ -34,16 +36,20 @@ export function querySubscription(rpc: Rpc.Any, references: readonly QueryRefere
34
36
  const context = yield* policyContext(Rpc.make(`${prefix}${query.name}`));
35
37
  return {
36
38
  check: Effect.provideContext(checkQuery(query, payload, viewer), context),
39
+ keys: queryReadKeys(query, payload, viewer).pipe(Effect.provideContext(context)),
37
40
  permitted: Effect.suspend(() => query.readPolicy?.(payload, viewer) ?? Effect.succeed(false)).pipe(Effect.provideContext(context)),
38
41
  };
39
42
  }),
40
43
  );
41
44
  yield* Effect.forEach(policies, ({ check }) => check);
42
- const scopes = queries.map(({ query, payload }) => query.reads(payload, viewer));
45
+ const scopes = yield* Effect.forEach(policies, ({ keys }) => keys);
43
46
  const authorized = Effect.map(
44
47
  Effect.forEach(policies, ({ permitted }) => permitted),
45
48
  (permissions) => permissions.every(Boolean),
46
49
  );
47
- return { authorized, keys: scopes.flat(), queries, scopes } satisfies QuerySubscription<unknown, unknown>;
50
+ const globalKeys = queries.flatMap(
51
+ ({ query }) => query.readsCollections?.map((collection) => ({ _tag: "List" as const, collection: collection.name })) ?? [],
52
+ );
53
+ return { authorized, globalKeys, keys: scopes.flat(), queries, scopes } satisfies QuerySubscription<unknown, unknown>;
48
54
  })();
49
55
  }
package/src/readPolicy.ts CHANGED
@@ -2,6 +2,7 @@ import { Context, Effect, Option, type Stream, type Types } from "effect";
2
2
  import type { Rpc } from "effect/rpc";
3
3
  import { policyContext } from "#internal/policyContext.ts";
4
4
  import type { QueryShape } from "#operation.ts";
5
+ import { isPermissionReadPolicy } from "#permissionReadPolicy.ts";
5
6
  import { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
6
7
  import { QueryDefinition } from "#serverMetadata.ts";
7
8
 
@@ -17,6 +18,9 @@ export const checkQuery = Effect.fnUntraced(function* <E, R>(query: QueryShape<E
17
18
  if (query.readPolicy === undefined) {
18
19
  return yield* new MissingReadPolicy({ message: `Declare a readPolicy on query ${query.name} before reading it or subscribing` });
19
20
  }
21
+ if (query.readsCollections !== undefined && !isPermissionReadPolicy(query.readPolicy)) {
22
+ return yield* new QueryReadDenied({ message: `Collection reads require a permission policy on query ${query.name}` });
23
+ }
20
24
  if (!(yield* query.readPolicy(payload, viewer))) {
21
25
  return yield* new QueryReadDenied({ message: `Read not allowed for query ${query.name}` });
22
26
  }
@@ -1,11 +1,11 @@
1
- import { Context, Effect, Option, Schema } from "effect";
1
+ import { Context, type Effect, Schema } from "effect";
2
2
  import { Rpc, type RpcSchema } from "effect/rpc";
3
- import type { Key } from "@shivaedev/changes/keys.ts";
4
3
  import type { QueryServices } from "#contract.ts";
5
4
  import { changesSuccess } from "#internal/changesSuccess.ts";
5
+ import { resolveQueries } from "#internal/resolveQueries.ts";
6
6
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
7
- import type { Viewer } from "#readPolicy.ts";
8
7
  import { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
8
+ import { WebSocketRequired } from "#WebSocketRequired.ts";
9
9
 
10
10
  export class QueryDefinition extends Context.Service<QueryDefinition, { readonly definition: QueryShape }>()("@shivaedev/contract/QueryDefinition") {}
11
11
  export interface QueryRequest<E = unknown, R = unknown> {
@@ -35,22 +35,6 @@ type ReferenceSchema<TQuery extends QueryShape> = TQuery extends QueryShape
35
35
  ? Schema.Struct<{ query: Schema.Literal<TQuery["name"]>; payload: TQuery["payload"] }>
36
36
  : never;
37
37
 
38
- function resolveQueries(queries: readonly QueryShape[], requested: readonly QueryReference[]) {
39
- return Effect.forEach(requested, (reference) => {
40
- const query = queries.find((candidate) => candidate.name === reference.query);
41
- return query === undefined ? Effect.die(new Error(`Unknown query: ${reference.query}`)) : Effect.succeed({ payload: reference.payload, query });
42
- });
43
- }
44
-
45
- export const queryKeys = Effect.fnUntraced(function* (
46
- queries: readonly QueryShape[],
47
- requested: readonly QueryReference[],
48
- viewer: Option.Option<Viewer> = Option.none(),
49
- ): Effect.fn.Return<readonly Key[]> {
50
- const resolved = yield* resolveQueries(queries, requested);
51
- return resolved.flatMap(({ query, payload }) => query.reads(payload, viewer));
52
- });
53
-
54
38
  function referenceSchemas<const TQueries extends readonly QueryShape[]>(
55
39
  queries: TQueries,
56
40
  ): Schema.$Array<Schema.Union<readonly ReferenceSchema<TQueries[number]>[]>>;
@@ -59,7 +43,7 @@ function referenceSchemas(queries: readonly QueryShape[]) {
59
43
  }
60
44
 
61
45
  type ChangesError<TQueries extends readonly QueryShape[]> = Schema.Union<
62
- readonly [typeof MissingReadPolicy, typeof QueryReadDenied, ...TQueries[number]["error"][]]
46
+ readonly [typeof MissingReadPolicy, typeof QueryReadDenied, typeof WebSocketRequired, ...TQueries[number]["error"][]]
63
47
  >;
64
48
 
65
49
  export function changesRpc<const TName extends string, const TQueries extends readonly QueryShape[]>(
@@ -75,7 +59,7 @@ export function changesRpc<const TName extends string, const TQueries extends re
75
59
  >;
76
60
  export function changesRpc(name: string, queries: readonly QueryShape[]) {
77
61
  return Rpc.make(`${name}.$changes`, {
78
- error: Schema.Union([MissingReadPolicy, QueryReadDenied, ...queries.map((query) => query.error)]),
62
+ error: Schema.Union([MissingReadPolicy, QueryReadDenied, WebSocketRequired, ...queries.map((query) => query.error)]),
79
63
  payload: { queries: referenceSchemas(queries) },
80
64
  stream: true,
81
65
  success: changesSuccess(queries),