@shivaedev/contract 0.47.0 → 0.49.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 (104) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +131 -109
  3. package/dist/adapters/erasedClient.d.ts +18 -0
  4. package/dist/adapters/erasedClient.d.ts.map +1 -0
  5. package/dist/adapters/erasedClient.js +10 -0
  6. package/dist/adapters/erasedClient.js.map +1 -0
  7. package/dist/automaticLive.d.ts +2 -10
  8. package/dist/automaticLive.d.ts.map +1 -1
  9. package/dist/automaticLive.js +3 -1
  10. package/dist/automaticLive.js.map +1 -1
  11. package/dist/bind.d.ts +13 -9
  12. package/dist/bind.d.ts.map +1 -1
  13. package/dist/bind.js.map +1 -1
  14. package/dist/catchUp.d.ts +2 -1
  15. package/dist/catchUp.d.ts.map +1 -1
  16. package/dist/catchUp.js.map +1 -1
  17. package/dist/clientContract.d.ts +3 -3
  18. package/dist/clientContract.d.ts.map +1 -1
  19. package/dist/clientContract.js +1 -1
  20. package/dist/clientContract.js.map +1 -1
  21. package/dist/clientOperations.d.ts +5 -5
  22. package/dist/clientOperations.d.ts.map +1 -1
  23. package/dist/clientOperations.js +22 -11
  24. package/dist/clientOperations.js.map +1 -1
  25. package/dist/contract.d.ts +1 -0
  26. package/dist/contract.d.ts.map +1 -1
  27. package/dist/contract.js +1 -0
  28. package/dist/contract.js.map +1 -1
  29. package/dist/defineModule.d.ts +2 -2
  30. package/dist/defineModule.d.ts.map +1 -1
  31. package/dist/defineModule.js +1 -1
  32. package/dist/defineModule.js.map +1 -1
  33. package/dist/liveSyncRequest.d.ts +2 -2
  34. package/dist/liveSyncRequest.d.ts.map +1 -1
  35. package/dist/liveSyncRequest.js +1 -2
  36. package/dist/liveSyncRequest.js.map +1 -1
  37. package/dist/liveSyncRpc.d.ts +1 -0
  38. package/dist/liveSyncRpc.d.ts.map +1 -1
  39. package/dist/moduleProof.d.ts +8 -23
  40. package/dist/moduleProof.d.ts.map +1 -1
  41. package/dist/operation.d.ts +5 -5
  42. package/dist/operation.d.ts.map +1 -1
  43. package/dist/operation.js +2 -2
  44. package/dist/operation.js.map +1 -1
  45. package/dist/operationKind.d.ts +3 -0
  46. package/dist/operationKind.d.ts.map +1 -0
  47. package/dist/operationKind.js +14 -0
  48. package/dist/operationKind.js.map +1 -0
  49. package/dist/rpcClient.d.ts +2 -1
  50. package/dist/rpcClient.d.ts.map +1 -1
  51. package/dist/rpcClient.js.map +1 -1
  52. package/dist/runProof.d.ts +3 -41
  53. package/dist/runProof.d.ts.map +1 -1
  54. package/dist/servedOperation.d.ts +28 -25
  55. package/dist/servedOperation.d.ts.map +1 -1
  56. package/dist/servedOperation.js +9 -3
  57. package/dist/servedOperation.js.map +1 -1
  58. package/dist/serverMetadata.d.ts.map +1 -1
  59. package/dist/serverMetadata.js +6 -1
  60. package/dist/serverMetadata.js.map +1 -1
  61. package/dist/subject.d.ts +1 -1
  62. package/dist/subject.d.ts.map +1 -1
  63. package/dist/subjectHeader.d.ts +5 -0
  64. package/dist/subjectHeader.d.ts.map +1 -0
  65. package/dist/subjectHeader.js +14 -0
  66. package/dist/subjectHeader.js.map +1 -0
  67. package/dist/subjectLayers.d.ts +1 -1
  68. package/dist/subjectLayers.d.ts.map +1 -1
  69. package/dist/subjectLayers.js.map +1 -1
  70. package/dist/wire.d.ts.map +1 -1
  71. package/dist/wire.js +2 -1
  72. package/dist/wire.js.map +1 -1
  73. package/dist/wireProof.d.ts +48 -0
  74. package/dist/wireProof.d.ts.map +1 -0
  75. package/dist/wireProof.js +2 -0
  76. package/dist/wireProof.js.map +1 -0
  77. package/package.json +15 -15
  78. package/src/adapters/erasedClient.ts +43 -0
  79. package/src/automaticLive.ts +5 -15
  80. package/src/bind.ts +17 -9
  81. package/src/catchUp.ts +2 -1
  82. package/src/clientContract.ts +5 -5
  83. package/src/clientOperations.ts +30 -19
  84. package/src/contract.ts +2 -0
  85. package/src/defineModule.ts +4 -4
  86. package/src/liveSyncRequest.ts +3 -11
  87. package/src/liveSyncRpc.ts +2 -0
  88. package/src/moduleProof.ts +18 -27
  89. package/src/operation.ts +9 -16
  90. package/src/operationKind.ts +15 -0
  91. package/src/rpcClient.ts +3 -3
  92. package/src/runProof.ts +3 -61
  93. package/src/servedOperation.ts +47 -47
  94. package/src/serverMetadata.ts +6 -1
  95. package/src/subject.ts +1 -1
  96. package/src/subjectHeader.ts +17 -0
  97. package/src/subjectLayers.ts +6 -2
  98. package/src/wire.ts +2 -1
  99. package/src/wireProof.ts +104 -0
  100. package/dist/successProof.d.ts +0 -51
  101. package/dist/successProof.d.ts.map +0 -1
  102. package/dist/successProof.js +0 -2
  103. package/dist/successProof.js.map +0 -1
  104. package/src/successProof.ts +0 -120
@@ -1,15 +1,12 @@
1
- import type { Effect, Scope } from "effect";
1
+ import type { Effect, Schema, Scope } from "effect";
2
2
  import type { RpcMiddleware } from "effect/rpc";
3
- import type { InfrastructureFailure } from "@shivaedev/errors/infrastructure.ts";
4
3
  import type { RequirementRecord, RequirementsOf } from "@shivaedev/service/ServiceRequirements.ts";
5
4
  import type { Duplicated } from "#declarationError.ts";
6
5
  import type { OperationShape } from "#operation.ts";
7
- import type { QueryReadDenied } from "#readPolicyErrors.ts";
8
- import type { RejectedBy, RejectionSpecs } from "#rejection.ts";
9
- import type { Raised, RejectionProblem } from "#runProof.ts";
6
+ import type { Raised } from "#runProof.ts";
10
7
  import type { SubjectDeclaration, SubjectProvides } from "#subject.ts";
11
- import type { SuccessProblem } from "#successProof.ts";
12
8
  import type { WireEntry, WireEntryOf } from "#wire.ts";
9
+ import type { RejectionsDiffer, SuccessDiffers } from "#wireProof.ts";
13
10
 
14
11
  export interface OperationNeedsUndeclaredServices<TOperation extends string, TMissing> {
15
12
  readonly missingServices: TMissing;
@@ -17,12 +14,6 @@ export interface OperationNeedsUndeclaredServices<TOperation extends string, TMi
17
14
  readonly problem: "run or readPolicy uses services that the module's requires and middleware do not provide";
18
15
  }
19
16
 
20
- export interface OperationFailsOutsideItsRejections<TOperation extends string, TUndeclared> {
21
- readonly operation: TOperation;
22
- readonly problem: "run or readPolicy fails with errors outside the operation's rejections";
23
- readonly undeclaredFailures: TUndeclared;
24
- }
25
-
26
17
  type Regenerate = "the generated file is stale; run pnpm generate";
27
18
 
28
19
  export interface WireSuccessStale<TOperation extends string, TFix extends Regenerate, TRun, TWire> {
@@ -42,7 +33,7 @@ export interface WireRejectionsStale<TOperation extends string, TFix extends Reg
42
33
  export interface OperationMissingFromWire<TOperation extends string, TFix extends Regenerate> {
43
34
  readonly fix: TFix;
44
35
  readonly operation: TOperation;
45
- readonly problem: "the operation declares no success and the module's wire has no entry for it";
36
+ readonly problem: "run returns a value or fails with a rejection, and the module's wire has no entry for the operation";
46
37
  }
47
38
 
48
39
  export interface OperationNameRepeated<TOperation extends string> {
@@ -57,31 +48,27 @@ type Parts<TOperation> =
57
48
  | (TOperation extends { readonly kind: "query"; readonly readPolicy: infer TPolicy extends Effectful } ? ReturnType<TPolicy> : never);
58
49
 
59
50
  type Returns<TOperation> = TOperation extends { readonly run: infer TRun extends Effectful } ? Effect.Success<ReturnType<TRun>> : never;
60
- type Declared<TOperation> = TOperation extends { readonly rejections: infer TSpecs extends RejectionSpecs } ? RejectedBy<TSpecs> : never;
61
51
  type Tags<E> = E extends { readonly _tag: infer TTag } ? TTag : E;
62
- type Success<TOperation> = TOperation extends { readonly success: infer TSuccess } ? TSuccess : never;
63
52
  type NameOf<TOperation> = TOperation extends { readonly name: infer TName extends string } ? TName : string;
64
53
 
65
54
  type Missing<TOperation, TAllowed> = Exclude<Effect.Services<Parts<TOperation>>, TAllowed | Scope.Scope>;
66
- type Undeclared<TOperation> = Exclude<Effect.Error<Parts<TOperation>>, Declared<TOperation> | InfrastructureFailure | QueryReadDenied>;
67
55
 
68
- // An entry stands in for the operation's own success and rejections, so only the entry is compared with run.
69
- type WireProblem<TOperation, TEntry extends WireEntry> = [SuccessProblem<NameOf<TOperation>, TEntry["success"], Returns<TOperation>>] extends [never]
70
- ? [RejectionProblem<NameOf<TOperation>, TEntry["rejections"], Effect.Error<Parts<TOperation>>>] extends [never]
56
+ type WireProblem<TOperation, TEntry extends WireEntry> = [SuccessDiffers<TEntry["success"], Returns<TOperation>>] extends [never]
57
+ ? [RejectionsDiffer<TEntry["rejections"], Effect.Error<Parts<TOperation>>>] extends [never]
71
58
  ? never
72
59
  : WireRejectionsStale<NameOf<TOperation>, Regenerate, Tags<Raised<Effect.Error<Parts<TOperation>>>>, keyof TEntry["rejections"]>
73
60
  : WireSuccessStale<NameOf<TOperation>, Regenerate, Returns<TOperation>, TEntry["success"]["Type"]>;
74
61
 
75
- type OwnProblem<TOperation> = [Undeclared<TOperation>] extends [never]
76
- ? [SuccessProblem<NameOf<TOperation>, Success<TOperation>, Returns<TOperation>>] extends [never]
77
- ? never
78
- : OperationMissingFromWire<NameOf<TOperation>, Regenerate>
79
- : OperationFailsOutsideItsRejections<NameOf<TOperation>, Tags<Undeclared<TOperation>>>;
62
+ // Without an entry the operation is served with Void and the automatic rejections, which fit only a run that returns nothing
63
+ // and raises nothing else.
64
+ type EntryProblem<TOperation> = [SuccessDiffers<Schema.Void, Returns<TOperation>> | Raised<Effect.Error<Parts<TOperation>>>] extends [never]
65
+ ? never
66
+ : OperationMissingFromWire<NameOf<TOperation>, Regenerate>;
80
67
 
81
68
  type OperationProblem<TOperation, TWire, TAllowed> = [Missing<TOperation, TAllowed>] extends [never]
82
69
  ? WireEntryOf<TWire, NameOf<TOperation>> extends infer TEntry extends WireEntry
83
70
  ? WireProblem<TOperation, TEntry>
84
- : OwnProblem<TOperation>
71
+ : EntryProblem<TOperation>
85
72
  : OperationNeedsUndeclaredServices<NameOf<TOperation>, Missing<TOperation, TAllowed>>;
86
73
 
87
74
  type SubjectServices<TSubject> = TSubject extends SubjectDeclaration ? SubjectProvides<TSubject> : never;
@@ -96,6 +83,10 @@ type Problems<TOperations extends readonly OperationShape[], TWire, TAllowed> =
96
83
  | (Duplicated<TOperations> extends infer TName extends string ? (TName extends string ? OperationNameRepeated<TName> : never) : never);
97
84
 
98
85
  // The proof sits on the module's name, so the first line of the compiler's message names the operation and its problem.
99
- export type NameProof<TOperations extends readonly OperationShape[], TWire, TAllowed> = [Problems<TOperations, TWire, TAllowed>] extends [never]
86
+ // A definition without a wire leaves TWire at its constraint, whose index signature has every name; proving nothing then
87
+ // lets the compiler's own error say that wire is missing.
88
+ export type NameProof<TOperations extends readonly OperationShape[], TWire, TAllowed> = string extends keyof TWire
100
89
  ? unknown
101
- : Problems<TOperations, TWire, TAllowed>;
90
+ : [Problems<TOperations, TWire, TAllowed>] extends [never]
91
+ ? unknown
92
+ : Problems<TOperations, TWire, TAllowed>;
package/src/operation.ts CHANGED
@@ -5,9 +5,8 @@ import { type CommandDeclaration, type Loose, operation, type QueryDeclaration,
5
5
  import type { QueryServerReads } from "#QueryServerReads.ts";
6
6
  import { type QueryReadPolicy, signedIn, type Viewer } from "#readPolicy.ts";
7
7
  import type { Reject, RejectedBy, RejectionSpecs, Rejections, RejectionUnion } from "#rejection.ts";
8
- import type { ClassRejections, Pending, RunEffect, SpecsOf, SuccessSchema } from "#runProof.ts";
9
- import type { LooseCommand, LooseQuery, RunCommandDeclaration, RunQueryDeclaration, ServedCommand, ServedQueryOf } from "#servedOperation.ts";
10
- import { runOf, withAutomatic } from "#servedOperation.ts";
8
+ import type { LooseCommand, LooseQuery, RunCommandDeclaration, RunQueryDeclaration, ServedCommandOf, ServedQueryOf } from "#servedOperation.ts";
9
+ import { invalidatesOf, runOf, withAutomatic } from "#servedOperation.ts";
11
10
 
12
11
  export type PayloadSchema<TPayload extends Schema.Top | Schema.Struct.Fields> = TPayload extends Schema.Struct.Fields
13
12
  ? Schema.Struct<TPayload>
@@ -17,6 +16,7 @@ type NoRejections = Record<never, never>;
17
16
 
18
17
  export interface OperationShape {
19
18
  readonly error: Schema.Top;
19
+ readonly generatedSuccess?: true;
20
20
  readonly kind: "query" | "command" | "stream";
21
21
  readonly name: string;
22
22
  readonly payload: Schema.Top;
@@ -89,18 +89,16 @@ export function query<
89
89
  export function query<
90
90
  const TName extends string,
91
91
  TYielded extends Effect.Effect<unknown, unknown, unknown> = never,
92
- TReturn = Pending,
92
+ TReturn = unknown,
93
93
  TPayload extends Schema.Top | Schema.Struct.Fields = Schema.Void,
94
- TSuccess extends Schema.Top | undefined = undefined,
95
- const TSpecs extends ClassRejections | undefined = undefined,
96
94
  TPolicyError = never,
97
95
  TPolicyServices = never,
98
96
  TReads extends Effect.Effect<readonly Key[], unknown, unknown> = never,
99
97
  const TCollections extends readonly { readonly name: string }[] | undefined = undefined,
100
98
  >(
101
99
  name: TName,
102
- declaration: RunQueryDeclaration<TName, TPayload, TYielded, TReturn, TSuccess, TSpecs, TPolicyError, TPolicyServices, TReads, TCollections>,
103
- ): NoInfer<ServedQueryOf<TName, TPayload, TYielded, TReturn, TSuccess, TSpecs, TPolicyError, TPolicyServices, TReads>>;
100
+ declaration: RunQueryDeclaration<TName, TPayload, TYielded, TReturn, TPolicyError, TPolicyServices, TReads, TCollections>,
101
+ ): NoInfer<ServedQueryOf<TName, TPayload, TYielded, TReturn, TPolicyError, TPolicyServices, TReads>>;
104
102
  export function query(name: string, declaration: LooseQuery): QueryShape {
105
103
  const collections: readonly Key[] = declaration.readsCollections?.map((collection) => ({ _tag: "List", collection: collection.name })) ?? [];
106
104
  return {
@@ -125,16 +123,11 @@ export function command<
125
123
  export function command<
126
124
  const TName extends string,
127
125
  TYielded extends Effect.Effect<unknown, unknown, unknown> = never,
128
- TReturn = Pending,
126
+ TReturn = unknown,
129
127
  TPayload extends Schema.Top | Schema.Struct.Fields = Schema.Void,
130
- TSuccess extends Schema.Top | undefined = undefined,
131
- const TSpecs extends ClassRejections | undefined = undefined,
132
- >(
133
- name: TName,
134
- declaration: RunCommandDeclaration<TName, TPayload, TYielded, TReturn, TSuccess, TSpecs>,
135
- ): NoInfer<ServedCommand<TName, PayloadSchema<TPayload>, SuccessSchema<TSuccess>, SpecsOf<TSpecs>, RunEffect<TYielded, TReturn>>>;
128
+ >(name: TName, declaration: RunCommandDeclaration<TName, TPayload, TYielded, TReturn>): NoInfer<ServedCommandOf<TName, TPayload, TYielded, TReturn>>;
136
129
  export function command(name: string, declaration: LooseCommand): CommandShape {
137
- return { ...operation("command", name, withAutomatic(declaration)), invalidates: declaration.invalidates ?? (() => []), ...runOf(declaration) };
130
+ return { ...operation("command", name, withAutomatic(declaration)), invalidates: invalidatesOf(declaration), ...runOf(declaration) };
138
131
  }
139
132
 
140
133
  export function stream<
@@ -0,0 +1,15 @@
1
+ import { Context, Option } from "effect";
2
+ import { type Rpc, RpcSchema } from "effect/rpc";
3
+ import { ChangesQueries, CommandInvalidation, QueryDefinition } from "#serverMetadata.ts";
4
+
5
+ // A query, a live query's changes stream and any other stream only read; a command, or an RPC no contract marked, may write.
6
+ export function operationKind(rpc: Pick<Rpc.AnyWithProps, "annotations" | "successSchema">): "read" | "write" {
7
+ if (Option.isSome(Context.getOption(rpc.annotations, CommandInvalidation))) {
8
+ return "write";
9
+ }
10
+ const reads =
11
+ Option.isSome(Context.getOption(rpc.annotations, QueryDefinition))
12
+ || Option.isSome(Context.getOption(rpc.annotations, ChangesQueries))
13
+ || RpcSchema.isStreamSchema(rpc.successSchema);
14
+ return reads ? "read" : "write";
15
+ }
package/src/rpcClient.ts CHANGED
@@ -10,7 +10,7 @@ import { Activity } from "#clientActivity.ts";
10
10
  import type { ClientOptions } from "#clientOptions.ts";
11
11
  import { ConnectionScope, connectionProtocol } from "#connectionProtocol.ts";
12
12
  import { commandConnections } from "#connectionReadiness.ts";
13
- import { liveSyncRpc } from "#liveSyncRpc.ts";
13
+ import { type LiveSyncRpc, liveSyncRpc } from "#liveSyncRpc.ts";
14
14
  import { reflections } from "#reflection.ts";
15
15
  import type { ResumeWindow } from "#resume.ts";
16
16
  import { CommandInvalidation } from "#serverMetadata.ts";
@@ -53,7 +53,7 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
53
53
  }
54
54
  const protocolFor = configuredProtocol();
55
55
  const protocol = protocolFor(undefined);
56
- function observeClient(client: RpcClient.RpcClient.Flat<Rpc.Any, RpcClientError>, wait: Effect.Effect<void, RpcClientError>) {
56
+ function observeClient(client: RpcClient.RpcClient.Flat<Rpc.Any | LiveSyncRpc, RpcClientError>, wait: Effect.Effect<void, RpcClientError>) {
57
57
  const observed = new Proxy(client, {
58
58
  apply(target, receiver, args) {
59
59
  const result = Reflect.apply(target, receiver, args);
@@ -72,7 +72,7 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
72
72
  const make = Effect.gen(function* () {
73
73
  const { connection, reflection } = yield* ConnectionScope;
74
74
  const wait = Effect.suspend(() => (connection.isReady() ? Effect.void : activity.hold(connection.wait)));
75
- const native = yield* RpcClient.make<Rpc.Any, true>(group, { flatten: true });
75
+ const native = yield* RpcClient.make(group, { flatten: true });
76
76
  const observed = observeClient(native, wait);
77
77
  // Only the shared socket proves a command reaches the host that holds its streams; any other protocol syncs after the reply.
78
78
  reflections.set(observed, { piggyback: options.protocol === undefined, reflection });
package/src/runProof.ts CHANGED
@@ -1,9 +1,8 @@
1
- import type { Effect, Schema } from "effect";
1
+ import type { Effect } from "effect";
2
2
  import type { InfrastructureFailure } from "@shivaedev/errors/infrastructure.ts";
3
3
  import type { InternalServerError, ServiceUnavailable } from "@shivaedev/errors/taxonomy.ts";
4
4
  import type { QueryReadDenied } from "#readPolicyErrors.ts";
5
5
  import type { TaggedRejection } from "#rejection.ts";
6
- import type { Identical, SuccessProblem } from "#successProof.ts";
7
6
 
8
7
  export type RunBody<TPayload, TYielded, A> = (payload: TPayload) => Generator<TYielded, A, never>;
9
8
 
@@ -22,75 +21,18 @@ export interface Automatic {
22
21
 
23
22
  export type Raised<E> = Exclude<E, InfrastructureFailure | QueryReadDenied | InternalServerError | ServiceUnavailable>;
24
23
 
25
- export interface RunFailsOutsideRejections<TOperation extends string, TTags> {
26
- readonly missingRejections: TTags;
27
- readonly operation: TOperation;
28
- }
29
-
30
- export interface RejectionsRunNeverRaises<TOperation extends string, TTags> {
31
- readonly neverRaised: TTags;
32
- readonly operation: TOperation;
33
- }
34
-
35
- export interface RejectionAutomatic<TOperation extends string, TTags> {
36
- readonly automatic: TTags;
37
- readonly operation: TOperation;
38
- }
39
-
40
- export interface RejectionClassDiffers<TOperation extends string, TTags> {
41
- readonly operation: TOperation;
42
- readonly raisedClassDiffers: TTags;
43
- }
44
-
45
24
  export interface RunReturnsAny<TOperation extends string, TFix extends string> {
46
25
  readonly fix: TFix;
47
26
  readonly operation: TOperation;
48
27
  }
49
28
 
50
- type Tags<E> = E extends { readonly _tag: infer TTag extends string } ? TTag : never;
51
29
  type IsAny<T> = 0 extends 1 & T ? true : false;
52
- type Declared<TSpecs> = TSpecs extends ClassRejections ? keyof TSpecs & string : never;
53
- type AutomaticTags = keyof Automatic;
54
-
55
- type DifferentClasses<TSpecs, E> = {
56
- readonly [TTag in Declared<TSpecs>]: TSpecs extends { readonly [TKey in TTag]: new (...args: never) => infer TDeclared }
57
- ? Identical<TDeclared, Extract<Raised<E>, { readonly _tag: TTag }>> extends true
58
- ? never
59
- : TTag
60
- : never;
61
- }[Declared<TSpecs>];
62
-
63
- export type RejectionProblem<TName extends string, TSpecs, E> = TSpecs extends undefined
64
- ? never
65
- : [Extract<Declared<TSpecs>, AutomaticTags>] extends [never]
66
- ? [Exclude<Tags<Raised<E>>, Declared<TSpecs>>] extends [never]
67
- ? [Exclude<Declared<TSpecs>, Tags<Raised<E>>>] extends [never]
68
- ? [DifferentClasses<TSpecs, E>] extends [never]
69
- ? never
70
- : RejectionClassDiffers<TName, DifferentClasses<TSpecs, E>>
71
- : RejectionsRunNeverRaises<TName, Exclude<Declared<TSpecs>, Tags<Raised<E>>>>
72
- : RunFailsOutsideRejections<TName, Exclude<Tags<Raised<E>>, Declared<TSpecs>>>
73
- : RejectionAutomatic<TName, Extract<Declared<TSpecs>, AutomaticTags>>;
74
30
 
75
- type Problems<TName extends string, TSuccess, TSpecs, TReturn, E> = SuccessProblem<TName, TSuccess, TReturn> | RejectionProblem<TName, TSpecs, E>;
76
-
77
- export type SuccessSchema<TSuccess> = TSuccess extends Schema.Top ? TSuccess : Schema.Void;
78
31
  // A mapped type, unlike the Automatic interface, satisfies the index signature of RejectionSpecs.
79
32
  type Flat<T> = { readonly [TKey in keyof T]: T[TKey] };
80
33
  export type SpecsOf<TSpecs> = TSpecs extends ClassRejections ? Flat<TSpecs & Automatic> : Flat<Automatic>;
81
34
 
82
- // TypeScript checks the declaration once with run skipped, before it infers run's types; Pending is the default it sees then.
83
- export interface Pending {
84
- readonly pendingInference: unique symbol;
85
- }
86
-
87
- type IsPending<TReturn> = [TReturn] extends [never] ? false : [TReturn] extends [Pending] ? true : false;
88
-
89
- export type RunCheck<TName extends string, TSuccess, TSpecs, TReturn, E> =
35
+ export type RunCheck<TName extends string, TReturn> =
90
36
  IsAny<TReturn> extends true
91
37
  ? { readonly operationProblem: RunReturnsAny<TName, "decode the value with a schema, or give run's return a type"> }
92
- : IsPending<TReturn> extends true
93
- ? unknown
94
- : [Problems<TName, TSuccess, TSpecs, TReturn, E>] extends [never]
95
- ? unknown
96
- : { readonly operationProblem: Problems<TName, TSuccess, TSpecs, TReturn, E> };
38
+ : unknown;
@@ -6,8 +6,8 @@ import type { Loose } from "#operationDeclaration.ts";
6
6
  import type { PermissionReadPolicy } from "#permissionReadPolicy.ts";
7
7
  import type { QueryServerReads } from "#QueryServerReads.ts";
8
8
  import type { QueryReadPolicy, Viewer } from "#readPolicy.ts";
9
- import type { MatchingTags, RejectionSpecs } from "#rejection.ts";
10
- import type { ErrorOf, RunBody, RunCheck, RunEffect, ServicesOf, SpecsOf, SuccessSchema } from "#runProof.ts";
9
+ import type { RejectionSpecs } from "#rejection.ts";
10
+ import type { ErrorOf, RunBody, RunCheck, RunEffect, ServicesOf, SpecsOf } from "#runProof.ts";
11
11
 
12
12
  export interface ServedQuery<
13
13
  TName extends string,
@@ -38,22 +38,14 @@ export interface ServedCommand<
38
38
  readonly run: (payload: TPayload["Type"]) => TRun;
39
39
  }
40
40
 
41
- interface RunFields<TPayload extends Schema.Top | Schema.Struct.Fields, TYielded, TReturn, TSuccess, TSpecs> {
41
+ interface RunFields<TPayload extends Schema.Top | Schema.Struct.Fields, TYielded, TReturn> {
42
42
  readonly payload?: TPayload;
43
- readonly rejections?: TSpecs & MatchingTags<NonNullable<TSpecs>>;
44
43
  readonly run?: RunBody<PayloadSchema<TPayload>["Type"], TYielded, TReturn>;
45
- readonly success?: TSuccess;
46
44
  }
47
45
 
48
46
  // A run required where its types are inferred makes TypeScript report a declaration without run against default type
49
47
  // arguments, hiding the declaration's own mistakes; requiring it apart keeps those errors.
50
- export type RunDeclaration<TPayload extends Schema.Top | Schema.Struct.Fields, TYielded, TReturn, TSuccess, TSpecs> = RunFields<
51
- TPayload,
52
- TYielded,
53
- TReturn,
54
- TSuccess,
55
- TSpecs
56
- > &
48
+ export type RunDeclaration<TPayload extends Schema.Top | Schema.Struct.Fields, TYielded, TReturn> = RunFields<TPayload, TYielded, TReturn> &
57
49
  NoInfer<{ readonly run: RunBody<never, unknown, unknown> }>;
58
50
 
59
51
  export type CollectionReadPolicy<TCollections, TPayload, E, R> = TCollections extends undefined
@@ -65,27 +57,23 @@ export type RunQueryDeclaration<
65
57
  TPayload extends Schema.Top | Schema.Struct.Fields,
66
58
  TYielded,
67
59
  TReturn,
68
- TSuccess,
69
- TSpecs,
70
60
  TPolicyError,
71
61
  TPolicyServices,
72
62
  TReads,
73
63
  TCollections,
74
- > = RunDeclaration<TPayload, TYielded, TReturn, TSuccess, TSpecs> &
64
+ > = RunDeclaration<TPayload, TYielded, TReturn> &
75
65
  CollectionReadPolicy<TCollections, PayloadSchema<TPayload>["Type"], TPolicyError, TPolicyServices> & {
76
66
  readonly readPolicy?: QueryReadPolicy<PayloadSchema<TPayload>["Type"], TPolicyError, TPolicyServices>;
77
67
  readonly reads?: (payload: PayloadSchema<TPayload>["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
78
68
  readonly readsCollections?: TCollections;
79
69
  readonly serverReads?: (payload: PayloadSchema<TPayload>["Type"], viewer: Option.Option<Viewer>) => TReads;
80
- } & NoInfer<RunCheck<TName, TSuccess, TSpecs, TReturn, ErrorOf<TYielded> | TPolicyError | ErrorOf<TReads>>>;
70
+ } & NoInfer<RunCheck<TName, TReturn>>;
81
71
 
82
72
  export type ServedQueryOf<
83
73
  TName extends string,
84
74
  TPayload extends Schema.Top | Schema.Struct.Fields,
85
75
  TYielded,
86
76
  TReturn,
87
- TSuccess,
88
- TSpecs,
89
77
  TPolicyError,
90
78
  TPolicyServices,
91
79
  TReads,
@@ -93,53 +81,65 @@ export type ServedQueryOf<
93
81
  ? ServedQuery<
94
82
  TName,
95
83
  PayloadSchema<TPayload>,
96
- SuccessSchema<TSuccess>,
97
- SpecsOf<TSpecs>,
84
+ Schema.Void,
85
+ SpecsOf<undefined>,
98
86
  TPolicyError | ErrorOf<TReads>,
99
87
  TPolicyServices | ServicesOf<TReads>,
100
88
  RunEffect<TYielded, TReturn>
101
89
  >
102
90
  : never;
103
91
 
104
- // Object keys are sorted, so invalidates is checked before run and cannot see run's inferred result; a declared success types it.
105
- export interface ResultNeedsDeclaredSuccess {
106
- readonly declareSuccess: unique symbol;
107
- }
92
+ export type ServedCommandOf<TName extends string, TPayload extends Schema.Top | Schema.Struct.Fields, TYielded, TReturn> = ServedCommand<
93
+ TName,
94
+ PayloadSchema<TPayload>,
95
+ Schema.Void,
96
+ SpecsOf<undefined>,
97
+ RunEffect<TYielded, TReturn>
98
+ >;
108
99
 
109
- type ResultOf<TSuccess> = TSuccess extends Schema.Top ? TSuccess["Type"] : ResultNeedsDeclaredSuccess;
110
-
111
- export type RunCommandDeclaration<
112
- TName extends string,
113
- TPayload extends Schema.Top | Schema.Struct.Fields,
100
+ // Object keys are sorted, so invalidates is checked before run and cannot see its result: it is called without one, and
101
+ // keys computed from the result are contributed inside run with commandResult.
102
+ export type RunCommandDeclaration<TName extends string, TPayload extends Schema.Top | Schema.Struct.Fields, TYielded, TReturn> = RunDeclaration<
103
+ TPayload,
114
104
  TYielded,
115
- TReturn,
116
- TSuccess,
117
- TSpecs,
118
- > = RunDeclaration<TPayload, TYielded, TReturn, TSuccess, TSpecs> & {
119
- readonly invalidates?: (payload: PayloadSchema<TPayload>["Type"], result: ResultOf<TSuccess>, viewer?: Option.Option<Viewer>) => readonly Key[];
120
- } & NoInfer<RunCheck<TName, TSuccess, TSpecs, TReturn, ErrorOf<TYielded>>>;
121
-
122
- interface LooseRun extends Loose {
123
- readonly run?: (payload: never) => Generator<Effect.Effect<unknown, unknown, unknown>, unknown, never>;
124
- }
105
+ TReturn
106
+ > & {
107
+ readonly invalidates?: (payload: PayloadSchema<TPayload>["Type"], viewer?: Option.Option<Viewer>) => readonly Key[];
108
+ } & NoInfer<RunCheck<TName, TReturn>>;
125
109
 
126
- export interface LooseQuery extends LooseRun {
110
+ type RunGenerator = (payload: never) => Generator<Effect.Effect<unknown, unknown, unknown>, unknown, never>;
111
+
112
+ export interface LooseQuery extends Loose {
127
113
  readonly readPolicy?: QueryReadPolicy<unknown, unknown, unknown>;
128
114
  readonly reads?: (payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[];
129
115
  readonly readsCollections?: readonly { readonly name: string }[];
116
+ readonly run?: RunGenerator;
130
117
  readonly serverReads?: QueryServerReads<unknown, unknown, unknown>;
131
118
  }
132
119
 
133
- export interface LooseCommand extends LooseRun {
134
- readonly invalidates?: (payload: unknown, result: unknown, viewer?: Option.Option<Viewer>) => readonly Key[];
120
+ type Invalidates = (payload: unknown, result: unknown, viewer?: Option.Option<Viewer>) => readonly Key[];
121
+
122
+ export type LooseCommand =
123
+ | (Loose & { readonly invalidates?: Invalidates; readonly run?: undefined })
124
+ | {
125
+ readonly invalidates?: (payload: unknown, viewer?: Option.Option<Viewer>) => readonly Key[];
126
+ readonly payload?: Schema.Top | Schema.Struct.Fields;
127
+ readonly run: RunGenerator;
128
+ };
129
+
130
+ export function withAutomatic(declaration: LooseQuery | LooseCommand): Loose {
131
+ const { payload, run } = declaration;
132
+ return run === undefined ? declaration : { ...(payload === undefined ? {} : { payload }), rejections: { InternalServerError, ServiceUnavailable } };
135
133
  }
136
134
 
137
- export function withAutomatic(declaration: LooseRun): Loose {
138
- return declaration.run === undefined
139
- ? declaration
140
- : { ...declaration, rejections: { ...declaration.rejections, InternalServerError, ServiceUnavailable } };
135
+ export function invalidatesOf(declaration: LooseCommand): Invalidates {
136
+ if (declaration.run === undefined) {
137
+ return declaration.invalidates ?? (() => []);
138
+ }
139
+ const { invalidates } = declaration;
140
+ return invalidates === undefined ? () => [] : (payload, _result, viewer) => invalidates(payload, viewer);
141
141
  }
142
142
 
143
- export function runOf({ run }: LooseRun) {
143
+ export function runOf({ run }: { readonly run?: RunGenerator | undefined }) {
144
144
  return run === undefined ? {} : { run: Effect.fnUntraced(run) };
145
145
  }
@@ -1,5 +1,6 @@
1
1
  import { Context, type Effect, Schema } from "effect";
2
2
  import { Rpc, type RpcSchema } from "effect/rpc";
3
+ import { GeneratedSuccess } from "@shivaedev/errors/GeneratedSuccess.ts";
3
4
  import { changesSuccess } from "#changesSuccess.ts";
4
5
  import type { QueryServices } from "#contract.ts";
5
6
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
@@ -64,9 +65,13 @@ export function changesRpc(name: string, queries: readonly QueryShape[]) {
64
65
  }).annotate(ChangesQueries, { queries, resolve: (references) => resolveQueries(queries, references) });
65
66
  }
66
67
 
67
- export function operationAnnotations(operation: QueryShape | CommandShape | StreamShape) {
68
+ function kindAnnotations(operation: QueryShape | CommandShape | StreamShape) {
68
69
  if (operation.kind === "command") {
69
70
  return Context.make(CommandInvalidation, { invalidates: operation.invalidates });
70
71
  }
71
72
  return operation.kind === "query" ? Context.make(QueryDefinition, { definition: operation }) : Context.empty();
72
73
  }
74
+ export function operationAnnotations(operation: QueryShape | CommandShape | StreamShape) {
75
+ const annotations = kindAnnotations(operation);
76
+ return operation.generatedSuccess === true ? Context.add(annotations, GeneratedSuccess, true) : annotations;
77
+ }
package/src/subject.ts CHANGED
@@ -4,7 +4,7 @@ import type { subjectMiddleware } from "#subjectMiddleware.ts";
4
4
 
5
5
  export interface SubjectDeclaration {
6
6
  readonly error: Schema.Top;
7
- readonly middleware: Effect.Effect<RpcMiddleware.Any, never, unknown>;
7
+ readonly middleware: Effect.Effect<RpcMiddleware.Any, unknown, unknown>;
8
8
  }
9
9
 
10
10
  export type SubjectProvides<TSubject extends SubjectDeclaration> =
@@ -0,0 +1,17 @@
1
+ import { Headers } from "effect/http";
2
+
3
+ const HEADER = "x-platform-subject";
4
+
5
+ export function subjectHeader(headers: Headers.Headers): string | undefined {
6
+ return headers[HEADER];
7
+ }
8
+
9
+ export function withSubject(headers: Headers.Input | undefined, subject: string | undefined): Headers.Input | undefined {
10
+ return subject === undefined ? headers : Headers.set(Headers.fromInput(headers), HEADER, subject);
11
+ }
12
+
13
+ // Effect keys a serialized query by its tag and this key alone, so a subject that the key leaves out would hydrate into another subject's query.
14
+ export function subjectSerializationKey(key: string | undefined, headers: Headers.Input | undefined): string | undefined {
15
+ const subject = headers === undefined ? undefined : subjectHeader(Headers.fromInput(headers));
16
+ return key === undefined || subject === undefined ? key : `${key}:subject:${subject}`;
17
+ }
@@ -15,9 +15,13 @@ function isSubject(middleware: RpcMiddleware.AnyServiceWithProps): middleware is
15
15
 
16
16
  export function subjectLayers<R extends Rpc.Any>(
17
17
  group: RpcGroup.RpcGroup<R>,
18
- ): Layer.Layer<Context.Service.Identifier<Middleware<R>>, never, Effect.Services<Middleware<R>[typeof SUBJECT_TYPE_ID]["middleware"]>>;
18
+ ): Layer.Layer<
19
+ Context.Service.Identifier<Middleware<R>>,
20
+ Effect.Error<Middleware<R>[typeof SUBJECT_TYPE_ID]["middleware"]>,
21
+ Effect.Services<Middleware<R>[typeof SUBJECT_TYPE_ID]["middleware"]>
22
+ >;
19
23
  export function subjectLayers(group: RpcGroup.RpcGroup<Rpc.Any>) {
20
- const layers: Layer.Layer<never, never, unknown>[] = [];
24
+ const layers: Layer.Layer<never, unknown, unknown>[] = [];
21
25
  for (const rpc of group.requests.values()) {
22
26
  if (!Rpc.isRpc(rpc)) {
23
27
  continue;
package/src/wire.ts CHANGED
@@ -36,10 +36,11 @@ export function wireRejections(rejections: ClassRejections) {
36
36
  return { ...rejections, InternalServerError, ServiceUnavailable };
37
37
  }
38
38
 
39
+ // A wire's success is generated from run's type and carries no annotation, so its RPC takes it out of the sensitivity policy.
39
40
  export function wired(operation: QueryShape | CommandShape, entry: WireEntry | undefined): QueryShape | CommandShape {
40
41
  if (entry === undefined) {
41
42
  return operation;
42
43
  }
43
44
  const rejections = wireRejections(entry.rejections);
44
- return { ...operation, rejections, success: entry.success, ...rejectionSet(rejections) };
45
+ return { ...operation, generatedSuccess: true, rejections, success: entry.success, ...rejectionSet(rejections) };
45
46
  }
@@ -0,0 +1,104 @@
1
+ import type { Option, Schema } from "effect";
2
+ import type { ClassRejections, Raised } from "#runProof.ts";
3
+
4
+ type Same<TLeft, TRight> = [TLeft] extends [TRight] ? ([TRight] extends [TLeft] ? true : false) : false;
5
+ type Identical<TLeft, TRight> = (<T>() => T extends TLeft ? 1 : 2) extends <T>() => T extends TRight ? 1 : 2 ? true : false;
6
+
7
+ type Fields<TFields, TReturn> = {
8
+ readonly [TKey in keyof TFields]: NotEncodedAsReturned<TFields[TKey], TKey extends keyof TReturn ? TReturn[TKey] : never>;
9
+ }[keyof TFields];
10
+
11
+ type Elements<TElements extends readonly unknown[], TReturn> = {
12
+ readonly [TIndex in keyof TElements]: NotEncodedAsReturned<TElements[TIndex], TIndex extends keyof TReturn ? TReturn[TIndex] : never>;
13
+ }[number];
14
+
15
+ type Members<TMembers extends readonly unknown[], TReturn> = {
16
+ readonly [TIndex in keyof TMembers]: TMembers[TIndex] extends Schema.Top
17
+ ? NotEncodedAsReturned<TMembers[TIndex], Extract<TReturn, TMembers[TIndex]["Type"]>>
18
+ : never;
19
+ }[number];
20
+
21
+ type Matches<TReturn, TMembers extends readonly unknown[]> = true extends {
22
+ readonly [TIndex in keyof TMembers]: TMembers[TIndex] extends Schema.Top ? (TReturn extends TMembers[TIndex]["Type"] ? true : false) : false;
23
+ }[number]
24
+ ? true
25
+ : false;
26
+
27
+ type Covered<TMembers extends readonly unknown[], TReturn> = {
28
+ readonly [TIndex in keyof TMembers]: TMembers[TIndex] extends Schema.Struct<infer TFields>
29
+ ? Schema.Struct<TFields>["Type"] extends TReturn
30
+ ? { readonly fields: Fields<TFields, TReturn>; readonly type: Schema.Struct<TFields>["Type"] }
31
+ : never
32
+ : never;
33
+ }[number];
34
+
35
+ // A returned member whose discriminant is itself a union extends no single member, so it is compared with the members it covers.
36
+ type Unmatched<TMembers extends readonly unknown[], TReturn> = TReturn extends unknown
37
+ ? Matches<TReturn, TMembers> extends true
38
+ ? never
39
+ : Covered<TMembers, TReturn> extends infer TCovered extends { readonly fields: unknown; readonly type: unknown }
40
+ ? [TCovered] extends [never]
41
+ ? never
42
+ : TCovered["fields"] | KeysDiffer<TCovered["type"], TReturn>
43
+ : never
44
+ : never;
45
+
46
+ type InCollection<TSchema, TReturn> =
47
+ TSchema extends Schema.Union<infer TMembers>
48
+ ? Members<TMembers, TReturn> | Unmatched<TMembers, TReturn>
49
+ : TSchema extends Schema.$Record<infer _TKey, infer TValue>
50
+ ? NotEncodedAsReturned<TValue, TReturn[keyof TReturn]>
51
+ : TSchema extends Schema.Option<infer TValue>
52
+ ? NotEncodedAsReturned<TValue, TReturn extends Option.Option<infer TReturned> ? TReturned : never>
53
+ : never;
54
+
55
+ type KeysOf<T> = T extends unknown ? keyof T : never;
56
+
57
+ type KeysDiffer<TType, TReturn> = [TReturn] extends [never] ? never : Same<KeysOf<TType>, KeysOf<TReturn>> extends true ? never : true;
58
+
59
+ type InComposite<TSchema, TReturn> =
60
+ TSchema extends Schema.Struct<infer TFields>
61
+ ? Fields<TFields, TReturn> | KeysDiffer<Schema.Struct<TFields>["Type"], TReturn>
62
+ : TSchema extends Schema.Tuple<infer TElements>
63
+ ? Elements<TElements, TReturn>
64
+ : InCollection<TSchema, TReturn>;
65
+
66
+ type InContainer<TSchema, TReturn> = TSchema extends Schema.$Array<infer TItem> | Schema.NonEmptyArray<infer TItem>
67
+ ? NotEncodedAsReturned<TItem, TReturn extends readonly (infer TReturned)[] ? TReturned : never>
68
+ : TSchema extends Schema.mutable<infer TInner>
69
+ ? NotEncodedAsReturned<TInner, TReturn>
70
+ : TSchema extends Schema.mutableKey<infer TInner>
71
+ ? NotEncodedAsReturned<TInner, TReturn>
72
+ : TSchema extends Schema.optionalKey<infer TInner>
73
+ ? NotEncodedAsReturned<TInner, Exclude<TReturn, undefined>>
74
+ : InComposite<TSchema, TReturn>;
75
+
76
+ // Mutual assignability passed, yet encoding still depends on what each position holds: a class position must carry exactly
77
+ // that class, or encoding it fails, and a struct position exactly its keys, since an optional key may sit on one side only.
78
+ type NotEncodedAsReturned<TSchema, TReturn> =
79
+ TSchema extends Schema.Class<infer TClass, infer _TStruct, infer _TInherited>
80
+ ? Identical<TClass, TReturn> extends true
81
+ ? never
82
+ : true
83
+ : InContainer<TSchema, TReturn>;
84
+
85
+ export type SuccessDiffers<TSuccess extends Schema.Top, TReturn> =
86
+ Same<TSuccess["Type"], TReturn> extends true ? NotEncodedAsReturned<TSuccess, TReturn> : true;
87
+
88
+ type Tags<E> = E extends { readonly _tag: infer TTag extends string } ? TTag : never;
89
+ type Listed<TSpecs extends ClassRejections> = keyof TSpecs & string;
90
+ type AutomaticTags = "InternalServerError" | "ServiceUnavailable";
91
+
92
+ type DifferentClasses<TSpecs extends ClassRejections, E> = {
93
+ readonly [TTag in Listed<TSpecs>]: TSpecs extends { readonly [TKey in TTag]: new (...args: never) => infer TListed }
94
+ ? Identical<TListed, Extract<Raised<E>, { readonly _tag: TTag }>> extends true
95
+ ? never
96
+ : TTag
97
+ : never;
98
+ }[Listed<TSpecs>];
99
+
100
+ export type RejectionsDiffer<TSpecs extends ClassRejections, E> = [Extract<Listed<TSpecs>, AutomaticTags>] extends [never]
101
+ ? [Exclude<Tags<Raised<E>>, Listed<TSpecs>> | Exclude<Listed<TSpecs>, Tags<Raised<E>>> | DifferentClasses<TSpecs, E>] extends [never]
102
+ ? never
103
+ : true
104
+ : true;