@effect-app/vue 4.0.0-beta.2 → 4.0.0-beta.200

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 (103) hide show
  1. package/CHANGELOG.md +1611 -0
  2. package/dist/commander.d.ts +628 -0
  3. package/dist/commander.d.ts.map +1 -0
  4. package/dist/commander.js +1055 -0
  5. package/dist/confirm.d.ts +19 -0
  6. package/dist/confirm.d.ts.map +1 -0
  7. package/dist/confirm.js +24 -0
  8. package/dist/errorReporter.d.ts +4 -4
  9. package/dist/errorReporter.d.ts.map +1 -1
  10. package/dist/errorReporter.js +12 -18
  11. package/dist/form.d.ts +14 -5
  12. package/dist/form.d.ts.map +1 -1
  13. package/dist/form.js +41 -12
  14. package/dist/index.d.ts +1 -1
  15. package/dist/intl.d.ts +15 -0
  16. package/dist/intl.d.ts.map +1 -0
  17. package/dist/intl.js +9 -0
  18. package/dist/lib.d.ts +6 -9
  19. package/dist/lib.d.ts.map +1 -1
  20. package/dist/lib.js +35 -10
  21. package/dist/makeClient.d.ts +153 -340
  22. package/dist/makeClient.d.ts.map +1 -1
  23. package/dist/makeClient.js +222 -377
  24. package/dist/makeContext.d.ts +1 -1
  25. package/dist/makeContext.d.ts.map +1 -1
  26. package/dist/makeIntl.d.ts +1 -1
  27. package/dist/makeIntl.d.ts.map +1 -1
  28. package/dist/makeUseCommand.d.ts +8 -0
  29. package/dist/makeUseCommand.d.ts.map +1 -0
  30. package/dist/makeUseCommand.js +13 -0
  31. package/dist/mutate.d.ts +53 -35
  32. package/dist/mutate.d.ts.map +1 -1
  33. package/dist/mutate.js +138 -47
  34. package/dist/query.d.ts +20 -40
  35. package/dist/query.d.ts.map +1 -1
  36. package/dist/query.js +138 -71
  37. package/dist/routeParams.d.ts +1 -1
  38. package/dist/runtime.d.ts +7 -4
  39. package/dist/runtime.d.ts.map +1 -1
  40. package/dist/runtime.js +27 -17
  41. package/dist/toast.d.ts +46 -0
  42. package/dist/toast.d.ts.map +1 -0
  43. package/dist/toast.js +32 -0
  44. package/dist/withToast.d.ts +26 -0
  45. package/dist/withToast.d.ts.map +1 -0
  46. package/dist/withToast.js +54 -0
  47. package/examples/streamMutation.ts +70 -0
  48. package/package.json +48 -50
  49. package/src/commander.ts +3384 -0
  50. package/src/{experimental/confirm.ts → confirm.ts} +10 -14
  51. package/src/errorReporter.ts +62 -74
  52. package/src/form.ts +56 -17
  53. package/src/intl.ts +12 -0
  54. package/src/lib.ts +47 -20
  55. package/src/makeClient.ts +569 -1135
  56. package/src/{experimental/makeUseCommand.ts → makeUseCommand.ts} +6 -4
  57. package/src/mutate.ts +266 -128
  58. package/src/query.ts +207 -181
  59. package/src/runtime.ts +41 -20
  60. package/src/{experimental/toast.ts → toast.ts} +11 -25
  61. package/src/{experimental/withToast.ts → withToast.ts} +28 -10
  62. package/test/Mutation.test.ts +176 -23
  63. package/test/dist/form.test.d.ts.map +1 -1
  64. package/test/dist/lib.test.d.ts.map +1 -0
  65. package/test/dist/streamFinal.test.d.ts.map +1 -0
  66. package/test/dist/streamFn.test.d.ts.map +1 -0
  67. package/test/dist/stubs.d.ts +3274 -122
  68. package/test/dist/stubs.d.ts.map +1 -1
  69. package/test/dist/stubs.js +178 -31
  70. package/test/form-validation-errors.test.ts +23 -19
  71. package/test/form.test.ts +20 -2
  72. package/test/lib.test.ts +240 -0
  73. package/test/makeClient.test.ts +292 -38
  74. package/test/streamFinal.test.ts +63 -0
  75. package/test/streamFn.test.ts +455 -0
  76. package/test/stubs.ts +214 -42
  77. package/tsconfig.examples.json +20 -0
  78. package/tsconfig.json +0 -1
  79. package/tsconfig.json.bak +5 -2
  80. package/tsconfig.src.json +34 -34
  81. package/tsconfig.test.json +2 -2
  82. package/vitest.config.ts +5 -5
  83. package/dist/experimental/commander.d.ts +0 -359
  84. package/dist/experimental/commander.d.ts.map +0 -1
  85. package/dist/experimental/commander.js +0 -558
  86. package/dist/experimental/confirm.d.ts +0 -19
  87. package/dist/experimental/confirm.d.ts.map +0 -1
  88. package/dist/experimental/confirm.js +0 -28
  89. package/dist/experimental/intl.d.ts +0 -16
  90. package/dist/experimental/intl.d.ts.map +0 -1
  91. package/dist/experimental/intl.js +0 -5
  92. package/dist/experimental/makeUseCommand.d.ts +0 -8
  93. package/dist/experimental/makeUseCommand.d.ts.map +0 -1
  94. package/dist/experimental/makeUseCommand.js +0 -13
  95. package/dist/experimental/toast.d.ts +0 -47
  96. package/dist/experimental/toast.d.ts.map +0 -1
  97. package/dist/experimental/toast.js +0 -41
  98. package/dist/experimental/withToast.d.ts +0 -25
  99. package/dist/experimental/withToast.d.ts.map +0 -1
  100. package/dist/experimental/withToast.js +0 -45
  101. package/eslint.config.mjs +0 -24
  102. package/src/experimental/commander.ts +0 -1836
  103. package/src/experimental/intl.ts +0 -9
package/src/makeClient.ts CHANGED
@@ -1,129 +1,194 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
3
2
  import { type InvalidateOptions, type InvalidateQueryFilters, isCancelledError, type QueryObserverResult, type RefetchOptions, type UseQueryReturnType } from "@tanstack/vue-query"
4
3
  import { camelCase } from "change-case"
5
- import { Cause, Data, Effect, Exit, Layer, type ManagedRuntime, Match, Option, S, ServiceMap, Struct } from "effect-app"
4
+ import { type Context, Effect, Exit, Hash, type Layer, type ManagedRuntime, S, Struct } from "effect-app"
6
5
  import { type ApiClientFactory, type Req } from "effect-app/client"
7
- import type { RequestHandler, RequestHandlers, RequestHandlerWithInput, Requests } from "effect-app/client/clientFor"
8
- import { ErrorSilenced, type SupportedErrors } from "effect-app/client/errors"
9
- import { constant, identity, pipe, tuple } from "effect-app/Function"
10
- import { type OperationFailure, OperationSuccess } from "effect-app/Operations"
11
- import { dropUndefinedT, extendM } from "effect-app/utils"
6
+ import type { ExtractModuleName, HandlerInput, RequestHandlers, RequestHandlerWithInput, RequestsAny, RequestStreamHandlerWithInput } from "effect-app/client/clientFor"
7
+ import type { InvalidationCallback } from "effect-app/client/makeClient"
8
+ import type * as ExitResult from "effect/Exit"
12
9
  import { type Fiber } from "effect/Fiber"
13
- import { computed, type ComputedRef, onBeforeUnmount, type Ref, ref, watch, type WatchSource } from "vue"
14
- import { reportMessage } from "./errorReporter.js"
15
- import { type Commander, CommanderStatic } from "./experimental/commander.js"
16
- import { I18n } from "./experimental/intl.js"
17
- import { type CommanderResolved, makeUseCommand } from "./experimental/makeUseCommand.js"
18
- import { Toast } from "./experimental/toast.js"
19
- import { buildFieldInfoFromFieldsRoot } from "./form.js"
20
- import { reportRuntimeError } from "./lib.js"
21
- import { asResult, makeMutation, type MutationOptions, type MutationOptionsBase, mutationResultToVue, type Res, useMakeMutation } from "./mutate.js"
22
- import { type CustomUndefinedInitialQueryOptions, makeQuery } from "./query.js"
23
-
24
- const mapHandler = <A, E, R, I = void, A2 = A, E2 = E, R2 = R>(
25
- handler: Effect.Effect<A, E, R> | ((i: I) => Effect.Effect<A, E, R>),
26
- map: (self: Effect.Effect<A, E, R>, i: I) => Effect.Effect<A2, E2, R2>
27
- ) => Effect.isEffect(handler) ? map(handler, undefined as any) : (i: I) => map(handler(i), i)
28
-
29
- export interface RequestExtensions<RT, Id extends string, I, A, E, R> {
10
+ import type * as Stream from "effect/Stream"
11
+ import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
12
+ import { type ComputedRef, onBeforeUnmount, ref, type WatchSource } from "vue"
13
+ import { type Commander, CommanderStatic, type Progress } from "./commander.js"
14
+ import { type I18n } from "./intl.js"
15
+ import { type CommanderResolved, makeUseCommand } from "./makeUseCommand.js"
16
+ import { makeMutation, makeStreamMutation2, type MutationOptionsBase, useMakeMutation } from "./mutate.js"
17
+ import { type CustomUndefinedInitialQueryOptions, makeQuery, makeStreamQuery } from "./query.js"
18
+ import { makeRunPromise } from "./runtime.js"
19
+ import { type Toast } from "./toast.js"
20
+
21
+ export type { Progress }
22
+
23
+ // TODO: optimize - work from encoded shape directly
24
+ const projectHandler = (
25
+ handler: (i: any) => Effect.Effect<any, any, any>,
26
+ successSchema: S.Top,
27
+ projectionSchema: S.Top
28
+ ) => {
29
+ const encode = S.encodeEffect(successSchema)
30
+ const decode = S.decodeEffectConcurrently(projectionSchema)
31
+ return (i: any) => handler(i).pipe(Effect.flatMap(encode), Effect.flatMap(decode))
32
+ }
33
+
34
+ const projectionSchemaHash = (schema: S.Top) => String(Hash.hash(schema.ast))
35
+
36
+ export interface CommandRequestExtensions<RT, Id extends string, I, A, E, R> {
30
37
  /** Defines a Command based on this call, taking the `id` of the call as the `id` of the Command.
31
38
  * The Request function will be taken as the first member of the Command, the Command required input will be the Request input.
32
39
  * see Command.wrap for details */
33
- wrap: Commander.CommanderWrap<RT, Id, Id, undefined, I, A, E, R>
40
+ wrap: <I18nKey extends string = Id, State extends Commander.IntlRecord | undefined = undefined>(
41
+ options?: Commander.FnOptions<Id, I18nKey, State>
42
+ ) => Commander.CommanderWrap<RT, Id, I18nKey, State, I, A, E, R>
34
43
  /** Defines a Command based on this call, taking the `id` of the call as the `id` of the Command.
35
44
  * see Command.fn for details */
36
- fn: Commander.CommanderFn<RT, Id, Id, undefined>
45
+ fn: <I18nKey extends string = Id, State extends Commander.IntlRecord | undefined = undefined>(
46
+ options?: Commander.FnOptions<Id, I18nKey, State>
47
+ ) => Commander.CommanderFn<RT, Id, I18nKey, State>
37
48
  }
38
49
 
39
50
  /** my other doc */
40
- export interface RequestExtWithInput<
51
+ export interface RequestExt<
41
52
  RT,
42
53
  Id extends string,
43
54
  I,
44
55
  A,
45
56
  E,
46
57
  R
47
- > extends Commander.CommandContextLocal<Id, Id>, RequestExtensions<RT, Id, I, A, E, R> {
58
+ > extends
59
+ Commander.CommandContextLocal<Id, Id>,
60
+ Commander.CommanderWrap<RT, Id, Id, undefined, I, A, E, R>,
61
+ CommandRequestExtensions<RT, Id, I, A, E, R>
62
+ {
48
63
  /**
49
- * Request the endpoint with input
64
+ * Send the request to the endpoint and return the raw Effect response.
65
+ * This does not perform query cache invalidation.
50
66
  */
51
- (i: I): Effect.Effect<A, E, R>
67
+ request: (i: I) => Effect.Effect<A, E, R>
52
68
  }
53
69
 
54
- /**
55
- * Request the endpoint
56
- */
57
- export interface RequestExt<
58
- RT,
59
- Id extends string,
60
- A,
61
- E,
62
- R
63
- > extends
64
- Commander.CommandContextLocal<Id, Id>,
65
- Commander.CommanderWrap<RT, Id, Id, undefined, void, A, E, R>,
66
- RequestExtensions<RT, Id, void, A, E, R>,
67
- Effect.Effect<A, E, R>
68
- {
70
+ export type CommandRequestWithExtensions<RT, Req> = Req extends
71
+ RequestHandlerWithInput<infer I, infer A, infer E, infer R, infer _Request, infer Id> ? RequestExt<RT, Id, I, A, E, R>
72
+ : never
73
+
74
+ export interface QueryExtensions<I, A, E, R> {
75
+ /**
76
+ * Send the request to the endpoint and return the raw Effect response.
77
+ * This does not set up query state tracking.
78
+ */
79
+ request: (i: I) => Effect.Effect<A, E, R>
69
80
  }
70
81
 
71
- export type RequestWithExtensions<RT, Req> = Req extends
72
- RequestHandlerWithInput<infer I, infer A, infer E, infer R, infer _Request, infer Id>
73
- ? RequestExtWithInput<RT, Id, I, A, E, R>
74
- : Req extends RequestHandler<infer A, infer E, infer R, infer _Request, infer Id> ? RequestExt<RT, Id, A, E, R>
82
+ export type QueryRequestWithExtensions<Req> = Req extends
83
+ RequestHandlerWithInput<infer I, infer A, infer E, infer R, infer _Request, infer _Id> ? QueryExtensions<I, A, E, R>
84
+ : never
85
+
86
+ type QueryHandler<Req> = Req extends
87
+ RequestHandlerWithInput<infer I, infer A, infer E, infer R, infer Request, infer Id>
88
+ ? Request["type"] extends "query" ? RequestHandlerWithInput<I, A, E, R, Request, Id> : never
89
+ : never
90
+
91
+ type CommandHandler<Req> = Req extends
92
+ RequestHandlerWithInput<infer I, infer A, infer E, infer R, infer Request, infer Id>
93
+ ? Request["type"] extends "command" ? RequestHandlerWithInput<I, A, E, R, Request, Id> : never
94
+ : never
95
+
96
+ type QueryStreamHandler<Req> = Req extends
97
+ RequestStreamHandlerWithInput<infer I, infer A, infer E, infer R, infer Request, infer Id, infer Final>
98
+ ? [Request["stream"], Request["type"]] extends [true, "query"]
99
+ ? RequestStreamHandlerWithInput<I, A, E, R, Request, Id, Final>
100
+ : never
101
+ : never
102
+
103
+ type CommandStreamHandler<Req> = Req extends
104
+ RequestStreamHandlerWithInput<infer I, infer A, infer E, infer R, infer Request, infer Id, infer Final>
105
+ ? [Request["stream"], Request["type"]] extends [true, "command"]
106
+ ? RequestStreamHandlerWithInput<I, A, E, R, Request, Id, Final>
107
+ : never
75
108
  : never
76
109
 
77
110
  export interface MutationExtensions<RT, Id extends string, I, A, E, R> {
78
111
  /** Defines a Command based on this mutation, taking the `id` of the mutation as the `id` of the Command.
79
112
  * The Mutation function will be taken as the first member of the Command, the Command required input will be the Mutation input.
80
113
  * see Command.wrap for details */
81
- wrap: Commander.CommanderWrap<RT, Id, Id, undefined, I, A, E, R>
82
- /** Defines a Command based on this mutation, taking the `id` of the mutation as the `id` of the Command.
114
+ wrap: <I18nKey extends string = Id, State extends Commander.IntlRecord | undefined = undefined>(
115
+ options?: Commander.FnOptions<Id, I18nKey, State>
116
+ ) => Commander.CommanderWrap<RT, Id, I18nKey, State, I, A, E, R>
117
+ /** Defines a Command based on this call, taking the `id` of the mutation as the `id` of the Command.
83
118
  * see Command.fn for details */
84
- fn: Commander.CommanderFn<RT, Id, Id, undefined>
85
- }
86
-
87
- /** my other doc */
88
- export interface MutationExtWithInput<
89
- RT,
90
- Id extends string,
91
- I,
92
- A,
93
- E,
94
- R
95
- > extends Commander.CommandContextLocal<Id, Id>, MutationExtensions<RT, Id, I, A, E, R> {
96
- /**
97
- * Call the endpoint with input
98
- * Invalidate queries based on namespace of this mutation.
99
- * Do not use for queries.
100
- */
101
- (i: I): Effect.Effect<A, E, R>
119
+ fn: <I18nKey extends string = Id, State extends Commander.IntlRecord | undefined = undefined>(
120
+ options?: Commander.FnOptions<Id, I18nKey, State>
121
+ ) => Commander.CommanderFn<RT, Id, I18nKey, State>
102
122
  }
103
123
 
104
124
  /**
105
- * Call the endpoint
106
- * Invalidate queries based on namespace of this mutation.
107
- * Do not use for queries.
125
+ * Send the request to the endpoint and return the raw Effect response.
126
+ * Also invalidates query caches using the request namespace by default.
127
+ * Namespace invalidation targets parent namespace keys
128
+ * (for example `$project/$configuration.get` invalidates `$project`).
129
+ * Override invalidation in client options via `queryInvalidation`.
130
+ *
131
+ * Pass `options` to attach a `select` Effect that runs after the mutation
132
+ * succeeds (its output is returned to the caller) and/or override the default
133
+ * `queryInvalidation`.
134
+ *
135
+ * When `I = void` the input argument may be omitted.
108
136
  */
109
137
  export interface MutationExt<
110
138
  RT,
111
139
  Id extends string,
140
+ I,
112
141
  A,
113
142
  E,
114
- R
115
- > extends
116
- Commander.CommandContextLocal<Id, Id>,
117
- Commander.CommanderWrap<RT, Id, Id, undefined, void, A, E, R>,
118
- MutationExtensions<RT, Id, void, A, E, R>,
119
- Effect.Effect<A, E, R>
120
- {
143
+ R,
144
+ EA = unknown
145
+ > extends MutationExtensions<RT, Id, I, A, E, R> {
146
+ <B = A, E2 = never, R2 = never>(
147
+ input: I,
148
+ options?: MutationOptionsBase<A, B, E2, R2>
149
+ ): Effect.Effect<B, E | E2, R | R2>
150
+
151
+ project: <ProjSchema extends S.Top>(
152
+ schema: EA extends ProjSchema["Encoded"] ? ProjSchema : never
153
+ ) => MutationExt<
154
+ RT,
155
+ Id,
156
+ I,
157
+ S.Schema.Type<ProjSchema>,
158
+ E | S.SchemaError,
159
+ R | S.Codec.DecodingServices<ProjSchema>,
160
+ S.Codec.Encoded<ProjSchema>
161
+ >
121
162
  }
122
163
 
123
164
  export type MutationWithExtensions<RT, Req> = Req extends
124
- RequestHandlerWithInput<infer I, infer A, infer E, infer R, infer _Request, infer Id>
125
- ? MutationExtWithInput<RT, Id, I, A, E, R>
126
- : Req extends RequestHandler<infer A, infer E, infer R, infer _Request, infer Id> ? MutationExt<RT, Id, A, E, R>
165
+ RequestHandlerWithInput<infer I, infer A, infer E, infer R, infer Request, infer Id>
166
+ ? MutationExt<RT, Id, I, A, E, R, S.Codec.Encoded<Request["success"]>>
167
+ : never
168
+
169
+ /**
170
+ * The `streamFn` builder for a stream-type request handler, using the stream-specific overloads.
171
+ */
172
+ export type StreamFnStreamExtension<RT, Req> = Req extends
173
+ RequestStreamHandlerWithInput<infer _I, infer _A, infer _E, infer _R, infer _Request, infer Id, infer _Final>
174
+ ? <I18nKey extends string = Id, State extends Commander.IntlRecord | undefined = undefined>(
175
+ options?: Commander.FnOptions<Id, I18nKey, State>
176
+ ) => Commander.StreamGen<RT, Id, I18nKey, State> & Commander.NonGenStream<RT, Id, I18nKey, State>
177
+ : never
178
+
179
+ /**
180
+ * `mutate` factory — wraps per-invocation invalidation scaffolding
181
+ * into the stream itself (via `Stream.unwrap`) for use with `streamFn` combinators.
182
+ */
183
+ export type StreamMutation2WithExtensions<RT, Req> = Req extends
184
+ RequestStreamHandlerWithInput<infer I, infer A, infer E, infer R, infer _Request, infer Id, infer _Final> ?
185
+ & ((input: I) => Stream.Stream<A, E, R>)
186
+ & {
187
+ readonly id: Id
188
+ readonly wrap: <I18nKey extends string = Id, State extends Commander.IntlRecord | undefined = undefined>(
189
+ options?: Commander.FnOptions<Id, I18nKey, State>
190
+ ) => Commander.StreamerWrap<RT, Id, I18nKey, State, I, A, E, R>
191
+ }
127
192
  : never
128
193
 
129
194
  // we don't really care about the RT, as we are in charge of ensuring runtime safety anyway
@@ -131,33 +196,50 @@ export type MutationWithExtensions<RT, Req> = Req extends
131
196
  declare const useQuery_: QueryImpl<any>["useQuery"]
132
197
  // eslint-disable-next-line unused-imports/no-unused-vars
133
198
  declare const useSuspenseQuery_: QueryImpl<any>["useSuspenseQuery"]
199
+ // eslint-disable-next-line unused-imports/no-unused-vars
200
+ declare const useStreamQuery_: QueryImpl<any>["useStreamQuery"]
201
+
202
+ export interface ProjectResult<RT, I, B, E, R, Request extends Req, Id extends string> {
203
+ request: (i: I) => Effect.Effect<B, E, R>
204
+ query: Exclude<R, RT> extends never ? ReturnType<typeof useQuery_<I, E, B, Request, Id>>
205
+ : MissingDependencies<RT, R> & {}
206
+ suspense: Exclude<R, RT> extends never ? ReturnType<typeof useSuspenseQuery_<I, E, B, Request, Id>>
207
+ : MissingDependencies<RT, R> & {}
208
+ }
134
209
 
135
- export interface QueriesWithInput<Request extends Req, Id extends string, I, A, E> {
210
+ export type QueryProjection<RT, HandlerReq> = HandlerReq extends
211
+ RequestHandlerWithInput<infer I, infer _A, infer E, infer R, infer Request, infer Id>
212
+ ? Request["type"] extends "query" ? {
213
+ project: <ProjSchema extends S.Top>(
214
+ schema: S.Codec.Encoded<Request["success"]> extends ProjSchema["Encoded"] ? ProjSchema : never
215
+ ) => ProjectResult<
216
+ RT,
217
+ I,
218
+ S.Schema.Type<ProjSchema>,
219
+ E | S.SchemaError,
220
+ R | S.Codec.DecodingServices<ProjSchema>,
221
+ Request,
222
+ Id
223
+ >
224
+ }
225
+ : {}
226
+ : {}
227
+
228
+ export interface QueryResultExtensions<Request extends Req, Id extends string, I, A, E> {
136
229
  /**
137
- * Effect results are passed to the caller, including errors.
230
+ * Read helper for query requests.
231
+ * Runs as a tracked Vue Query and returns reactive state.
232
+ * Queries read state and should not be used to mutate it.
233
+ * When `I = void` the input argument may be omitted.
138
234
  */
139
235
  query: ReturnType<typeof useQuery_<I, E, A, Request, Id>>
140
236
  // TODO or suspense as Option?
141
237
  /**
142
- * The difference with useQuery is that this function will return a Promise you can await in the Setup,
143
- * which ensures that either there always is a latest value, or an error occurs on load.
144
- * So that Suspense and error boundaries can be used.
238
+ * Like `.query`, but returns a Promise for setup-time awaiting.
239
+ * Use this when integrating with Vue Suspense / error boundaries.
145
240
  */
146
241
  suspense: ReturnType<typeof useSuspenseQuery_<I, E, A, Request, Id>>
147
242
  }
148
- export interface QueriesWithoutInput<Request extends Req, Id extends string, A, E> {
149
- /**
150
- * Effect results are passed to the caller, including errors.
151
- */
152
- query: ReturnType<typeof useQuery_<E, A, Request, Id>>
153
- // TODO or suspense as Option?
154
- /**
155
- * The difference with useQuery is that this function will return a Promise you can await in the Setup,
156
- * which ensures that either there always is a latest value, or an error occurs on load.
157
- * So that Suspense and error boundaries can be used.
158
- */
159
- suspense: ReturnType<typeof useSuspenseQuery_<E, A, Request, Id>>
160
- }
161
243
 
162
244
  export type MissingDependencies<RT, R> = {
163
245
  message: "Dependencies required that are not provided by the runtime"
@@ -166,184 +248,40 @@ export type MissingDependencies<RT, R> = {
166
248
 
167
249
  export type Queries<RT, Req> = Req extends
168
250
  RequestHandlerWithInput<infer I, infer A, infer E, infer R, infer Request, infer Id>
169
- ? Exclude<R, RT> extends never ? QueriesWithInput<Request, Id, I, A, E>
170
- : {
171
- query: MissingDependencies<RT, R> & {}
172
- suspense: MissingDependencies<RT, R> & {}
173
- }
174
- : Req extends RequestHandler<infer A, infer E, infer R, infer Request, infer Id>
175
- ? Exclude<R, RT> extends never ? QueriesWithoutInput<Request, Id, A, E>
251
+ ? Request["type"] extends "query" ? Exclude<R, RT> extends never ? QueryResultExtensions<Request, Id, I, A, E>
176
252
  : { query: MissingDependencies<RT, R> & {}; suspense: MissingDependencies<RT, R> & {} }
177
253
  : never
254
+ : never
178
255
 
179
- /**
180
- * Use this after handling an error yourself, still continueing on the Error track, but the error will not be reported.
181
- */
182
- export class SuppressErrors extends Data.TaggedError("SuppressErrors")<{}> {
183
- readonly [ErrorSilenced] = true as const
184
- }
185
-
186
- export type ResponseErrors = S.SchemaError | SupportedErrors | SuppressErrors | OperationFailure
187
-
188
- export interface Opts<
189
- A,
190
- E,
191
- R,
192
- I = void,
193
- A2 = A,
194
- E2 = E,
195
- R2 = R,
196
- ESuccess = never,
197
- RSuccess = never,
198
- EError = never,
199
- RError = never,
200
- EDefect = never,
201
- RDefect = never
202
- > extends MutationOptions<A, E, R, A2, E2, R2, I> {
203
- /** set to `undefined` to use default message */
204
- successMessage?: ((a: A2, i: I) => Effect.Effect<string | undefined, ESuccess, RSuccess>) | undefined
205
- /** set to `undefined` to use default message */
206
- failMessage?: ((e: E2, i: I) => Effect.Effect<string | undefined, EError, RError>) | undefined
207
- /** set to `undefined` to use default message */
208
- defectMessage?: ((e: Cause.Cause<E2>, i: I) => Effect.Effect<string | undefined, EDefect, RDefect>) | undefined
209
- }
210
-
211
- export interface LowOpts<
212
- A,
213
- E,
214
- I = void,
215
- ESuccess = never,
216
- RSuccess = never,
217
- EError = never,
218
- RError = never,
219
- EDefect = never,
220
- RDefect = never
221
- > {
222
- onSuccess: (a: A, i: I) => Effect.Effect<void, ESuccess, RSuccess>
223
- onFail: (e: E, i: I) => Effect.Effect<void, EError, RError>
224
- onDefect: (e: Cause.Cause<E>, i: I) => Effect.Effect<void, EDefect, RDefect>
225
- }
226
-
227
- export interface LowOptsOptional<
228
- A,
229
- E,
230
- R,
231
- I = void,
232
- A2 = A,
233
- E2 = E,
234
- R2 = R,
235
- ESuccess = never,
236
- RSuccess = never,
237
- EError = never,
238
- RError = never,
239
- EDefect = never,
240
- RDefect = never
241
- > extends MutationOptions<A, E, R, A2, E2, R2, I> {
242
- onSuccess?: (a: A, i: I) => Effect.Effect<void, ESuccess, RSuccess>
243
- onFail?: (e: E, i: I) => Effect.Effect<void, EError, RError>
244
- onDefect?: (e: Cause.Cause<E>, i: I) => Effect.Effect<void, EDefect, RDefect>
245
- }
246
-
247
- type WithAction<A> = A & {
248
- action: string
256
+ export interface StreamQueryExtensions<Request extends Req, Id extends string, I, A, E> {
257
+ /**
258
+ * Stream helper for query-stream requests.
259
+ * Runs as a tracked Vue Query and returns reactive state with accumulated chunks.
260
+ * Data is an array of all chunks received so far.
261
+ * When `I = void` the input argument may be omitted.
262
+ */
263
+ query: ReturnType<typeof useStreamQuery_<I, E, A, Request, Id>>
249
264
  }
265
+ export type StreamQueries<RT, HandlerReq> = HandlerReq extends
266
+ RequestStreamHandlerWithInput<infer I, infer A, infer E, infer R, infer Request, infer Id, infer _Final>
267
+ ? Exclude<R, RT> extends never ? StreamQueryExtensions<Request, Id, I, A, E>
268
+ : { query: MissingDependencies<RT, R> & {} }
269
+ : never
250
270
 
251
- // computed() takes a getter function and returns a readonly reactive ref
252
- // object for the returned value from the getter.
253
-
254
- type Resp<I, A, E, R, V = ComputedRef<Res<A, E>>> = readonly [
255
- V,
256
- WithAction<(I: I) => Effect.Effect<Exit.Exit<A, E>, never, R>>
257
- ]
258
-
259
- type ActResp<A, E, R, V = ComputedRef<Res<A, E>>> = readonly [
260
- V,
261
- WithAction<Effect.Effect<Exit.Exit<A, E>, never, R>>
262
- ]
263
-
264
- export const suppressToast = constant(Effect.succeed(undefined))
265
-
266
- /** handles errors as specified and reports defects */
267
- function handleRequest<
268
- E extends ResponseErrors,
269
- A,
270
- R,
271
- I = void,
272
- ESuccess = never,
273
- RSuccess = never,
274
- EError = never,
275
- RError = never,
276
- EDefect = never,
277
- RDefect = never
278
- >(
279
- f: Effect.Effect<Exit.Exit<A, E>, never, R> | ((i: I) => Effect.Effect<Exit.Exit<A, E>, never, R>),
280
- id: string,
281
- action: string,
282
- options: {
283
- onSuccess: (a: A, i: I) => Effect.Effect<void, ESuccess, RSuccess>
284
- onFail: (e: E, i: I) => Effect.Effect<void, EError, RError>
285
- onDefect: (e: Cause.Cause<E>, i: I) => Effect.Effect<void, EDefect, RDefect>
286
- }
287
- ) {
288
- const handleEffect = (i: any) => (self: Effect.Effect<Exit.Exit<A, E>, never, R>) =>
289
- self.pipe(
290
- Effect.tap(
291
- Effect.matchCauseEffect({
292
- onSuccess: (r) => options.onSuccess(r, i),
293
- onFailure: (cause) =>
294
- Effect.gen(function*() {
295
- if (Cause.hasInterruptsOnly(cause)) {
296
- console.info(`Interrupted while trying to ${action}`)
297
- return
298
- }
299
-
300
- const fail = Cause.findErrorOption(cause)
301
- if (Option.isSome(fail)) {
302
- if (fail.value._tag === "SuppressErrors") {
303
- console.info(`Suppressed error trying to ${action}`, fail.value)
304
- return
305
- }
306
- const message = `Failure trying to ${action}`
307
- yield* reportMessage(message, { action, error: fail.value })
308
- yield* options.onFail(fail.value, i)
309
- return
310
- }
311
-
312
- const extra = {
313
- action,
314
- message: `Unexpected Error trying to ${action}`
315
- }
316
- yield* reportRuntimeError(cause, extra)
271
+ const _useMutation = makeMutation()
317
272
 
318
- yield* options.onDefect(cause, i)
319
- })
320
- })
321
- ),
322
- Effect.withSpan(`mutation ${id}`, {}, { captureStackTrace: false })
323
- )
324
- return Object.assign(
325
- Effect.isEffect(f)
326
- ? pipe(
327
- f,
328
- handleEffect(void 0)
329
- )
330
- : (i: I) =>
331
- pipe(
332
- f(i),
333
- handleEffect(i)
334
- ),
335
- { action }
336
- )
273
+ const wrapWithSpan = (self: { id: string }, mut: any) => {
274
+ const span = (eff: Effect.Effect<any, any, any>) =>
275
+ Effect.withSpan(`mutation ${self.id}`, {}, { captureStackTrace: false })(eff)
276
+ return (input: any, options?: MutationOptionsBase) => span(mut(input, options))
337
277
  }
338
278
 
339
- const _useMutation = makeMutation()
340
-
341
279
  /**
342
280
  * Pass an Effect or a function that returns an Effect, e.g from a client action
343
281
  * Executes query cache invalidation based on default rules or provided option.
344
282
  * adds a span with the mutation id
345
283
  */
346
- export const useMutation: typeof _useMutation = <
284
+ export const useMutation: typeof _useMutation = (<
347
285
  I,
348
286
  E,
349
287
  A,
@@ -351,16 +289,12 @@ export const useMutation: typeof _useMutation = <
351
289
  Request extends Req,
352
290
  Name extends string
353
291
  >(
354
- self: RequestHandlerWithInput<I, A, E, R, Request, Name> | RequestHandler<A, E, R, Request, Name>,
355
- options?: MutationOptionsBase
292
+ self: RequestHandlerWithInput<I, A, E, R, Request, Name>
356
293
  ) =>
357
294
  Object.assign(
358
- mapHandler(
359
- _useMutation(self as any, options),
360
- Effect.withSpan(`mutation ${self.id}`, {}, { captureStackTrace: false })
361
- ) as any,
295
+ wrapWithSpan(self, _useMutation(self as any)),
362
296
  { id: self.id }
363
- )
297
+ )) as any
364
298
 
365
299
  /**
366
300
  * Pass an Effect or a function that returns an Effect, e.g from a client action
@@ -369,7 +303,7 @@ export const useMutation: typeof _useMutation = <
369
303
  */
370
304
  export const useMutationInt = (): typeof _useMutation => {
371
305
  const _useMutation = useMakeMutation()
372
- return <
306
+ return (<
373
307
  I,
374
308
  E,
375
309
  A,
@@ -377,715 +311,20 @@ export const useMutationInt = (): typeof _useMutation => {
377
311
  Request extends Req,
378
312
  Name extends string
379
313
  >(
380
- self: RequestHandlerWithInput<I, A, E, R, Request, Name> | RequestHandler<A, E, R, Request, Name>,
381
- options?: MutationOptionsBase
314
+ self: RequestHandlerWithInput<I, A, E, R, Request, Name>
382
315
  ) =>
383
316
  Object.assign(
384
- mapHandler(
385
- _useMutation(self as any, options),
386
- Effect.withSpan(`mutation ${self.id}`, {}, { captureStackTrace: false })
387
- ) as any,
317
+ wrapWithSpan(self, _useMutation(self as any)),
388
318
  { id: self.id }
389
- )
390
- }
391
-
392
- export class LegacyMutationImpl<RT> {
393
- constructor(
394
- private readonly getRuntime: () => ServiceMap.ServiceMap<RT>,
395
- private readonly toast: Toast,
396
- private readonly intl: I18n
397
- ) {}
398
-
399
- /**
400
- * Effect results are converted to Exit, so errors are ignored by default.
401
- * you should use the result ref to render errors!
402
- * @deprecated use `Command.fn` and friends instead
403
- */
404
- readonly useSafeMutation: {
405
- /**
406
- * Effect results are converted to Exit, so errors are ignored by default.
407
- * you should use the result ref to render errors!
408
- * @deprecated use `Command.fn` and friends instead
409
- */
410
- <I, E, A, R, Request extends Req, Name extends string, A2 = A, E2 = E, R2 = R>(
411
- self: RequestHandlerWithInput<I, A, E, R, Request, Name>,
412
- options?: MutationOptions<A, E, R, A2, E2, R2, I>
413
- ): readonly [
414
- ComputedRef<AsyncResult.AsyncResult<A2, E2>>,
415
- (i: I) => Effect.Effect<Exit.Exit<A2, E2>, never, R2>
416
- ]
417
- /**
418
- * Effect results are converted to Exit, so errors are ignored by default.
419
- * you should use the result ref to render errors!
420
- * @deprecated use `Command.fn` and friends instead
421
- */
422
- <E, A, R, Request extends Req, Name extends string, A2 = A, E2 = E, R2 = R>(
423
- self: RequestHandler<A, E, R, Request, Name>,
424
- options?: MutationOptions<A, E, R, A2, E2, R2>
425
- ): readonly [
426
- ComputedRef<AsyncResult.AsyncResult<A2, E2>>,
427
- Effect.Effect<Exit.Exit<A2, E2>, never, R2>
428
- ]
429
- } = <I, E, A, R, Request extends Req, Name extends string, A2 = A, E2 = E, R2 = R>(
430
- self: RequestHandlerWithInput<I, A, E, R, Request, Name> | RequestHandler<A, E, R, Request, Name>,
431
- options?: MutationOptions<A, E, R, A2, E2, R2, I>
432
- ) => {
433
- const unsafe = _useMutation(self as any, options)
434
-
435
- type MH = NonNullable<NonNullable<typeof options>["mapHandler"]>
436
- const mh = options?.mapHandler ?? identity as MH
437
-
438
- const [a, b] = asResult(
439
- mapHandler(
440
- mapHandler(unsafe as any, mh),
441
- Effect.tapCauseIf(Cause.hasDies, (cause) => reportRuntimeError(cause))
442
- ) as any
443
- )
444
- return [
445
- a,
446
- mapHandler(
447
- b,
448
- Effect.withSpan(`mutation ${self.id}`, {}, { captureStackTrace: false })
449
- )
450
- ] as const as any
451
- }
452
-
453
- /** handles errors as toasts and reports defects
454
- * @deprecated use `Command.fn` and friends instead
455
- */
456
- readonly useHandleRequestWithToast = () => {
457
- // eslint-disable-next-line @typescript-eslint/no-this-alias
458
- const self = this
459
- return handleRequestWithToast
460
- /**
461
- * Pass a function that returns a Promise.
462
- * Returns an execution function which reports errors as Toast.
463
- */
464
- function handleRequestWithToast<
465
- A,
466
- E extends ResponseErrors,
467
- R,
468
- I = void,
469
- A2 = A,
470
- E2 extends ResponseErrors = E,
471
- R2 = R,
472
- ESuccess = never,
473
- RSuccess = never,
474
- EError = never,
475
- RError = never,
476
- EDefect = never,
477
- RDefect = never
478
- >(
479
- f: Effect.Effect<Exit.Exit<A2, E2>, never, R2> | ((i: I) => Effect.Effect<Exit.Exit<A2, E2>, never, R2>),
480
- id: string,
481
- action: string,
482
- options: Opts<A, E, R, I, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect> = {}
483
- ) {
484
- const actionMessage = self.intl.formatMessage({ id: `action.${action}`, defaultMessage: action })
485
- const defaultWarnMessage = self.intl.formatMessage(
486
- { id: "handle.with_warnings" },
487
- { action: actionMessage }
488
- )
489
- const defaultSuccessMessage = self.intl.formatMessage(
490
- { id: "handle.success" },
491
- { action: actionMessage }
492
- )
493
- const defaultErrorMessage = self.intl.formatMessage(
494
- { id: "handle.with_errors" },
495
- { action: actionMessage }
496
- )
497
-
498
- return handleRequest<E2, A2, R2, any, ESuccess, RSuccess, EError, RError, EDefect, RDefect>(f, id, action, {
499
- onSuccess: Effect.fnUntraced(function*(a, i) {
500
- const message = options.successMessage ? yield* options.successMessage(a, i) : defaultSuccessMessage
501
- + (S.is(OperationSuccess)(a) && a.message
502
- ? "\n" + a.message
503
- : "")
504
- if (message) {
505
- yield* self.toast.success(message)
506
- }
507
- }),
508
- onFail: Effect.fnUntraced(function*(e, i) {
509
- if (!options.failMessage && e._tag === "OperationFailure") {
510
- yield* self.toast.warning(
511
- defaultWarnMessage + e.message
512
- ? "\n" + e.message
513
- : ""
514
- )
515
- return
516
- }
517
-
518
- const message = options.failMessage
519
- ? yield* options.failMessage(e, i)
520
- : `${defaultErrorMessage}:\n` + renderError(e)
521
- if (message) {
522
- yield* self.toast.error(message)
523
- }
524
- }),
525
- onDefect: Effect.fnUntraced(function*(cause, i) {
526
- const message = options.defectMessage
527
- ? yield* options.defectMessage(cause, i)
528
- : self.intl.formatMessage(
529
- { id: "handle.unexpected_error" },
530
- {
531
- action: actionMessage,
532
- error: Cause.pretty(cause)
533
- }
534
- )
535
- if (message) {
536
- yield* self.toast.error(message)
537
- }
538
- })
539
- })
540
- }
541
-
542
- function renderError(e: ResponseErrors): string {
543
- return Match.value(e as any).pipe(
544
- Match.tags({
545
- // HttpErrorRequest: e =>
546
- // this.intl.value.formatMessage(
547
- // { id: "handle.request_error" },
548
- // { error: `${e.error}` },
549
- // ),
550
- // HttpErrorResponse: e =>
551
- // e.response.status >= 500 ||
552
- // e.response.body._tag !== "Some" ||
553
- // !e.response.body.value
554
- // ? this.intl.value.formatMessage(
555
- // { id: "handle.error_response" },
556
- // {
557
- // error: `${
558
- // e.response.body._tag === "Some" && e.response.body.value
559
- // ? parseError(e.response.body.value)
560
- // : "Unknown"
561
- // } (${e.response.status})`,
562
- // },
563
- // )
564
- // : this.intl.value.formatMessage(
565
- // { id: "handle.unexpected_error" },
566
- // {
567
- // error:
568
- // JSON.stringify(e.response.body, undefined, 2) +
569
- // "( " +
570
- // e.response.status +
571
- // ")",
572
- // },
573
- // ),
574
- // ResponseError: e =>
575
- // this.intl.value.formatMessage(
576
- // { id: "handle.response_error" },
577
- // { error: `${e.error}` },
578
- // ),
579
- SchemaError: (e: any) => {
580
- console.warn(e.toString())
581
- return self.intl.formatMessage({ id: "validation.failed" })
582
- }
583
- }),
584
- Match.orElse((e: any) => `${e.message ?? e._tag ?? e}`)
585
- )
586
- }
587
- }
588
-
589
- /**
590
- * Pass a function that returns an Effect, e.g from a client action, give it a name.
591
- * Returns a tuple with raw Result and execution function which reports success and errors as Toast.
592
- * @deprecated use `Command.fn` and friends instead
593
- */
594
- readonly useAndHandleMutationResult: {
595
- /**
596
- * Pass a function that returns an Effect, e.g from a client action, give it a name.
597
- * Returns a tuple with raw Result and execution function which reports success and errors as Toast.
598
- * @deprecated use `Command.fn` and friends instead
599
- */
600
- <
601
- I,
602
- E extends ResponseErrors,
603
- A,
604
- R,
605
- Request extends Req,
606
- Name extends string,
607
- A2 = A,
608
- E2 extends ResponseErrors = E,
609
- R2 = R,
610
- ESuccess = never,
611
- RSuccess = never,
612
- EError = never,
613
- RError = never,
614
- EDefect = never,
615
- RDefect = never
616
- >(
617
- self: RequestHandlerWithInput<I, A, E, R, Request, Name>,
618
- action: string,
619
- options?: Opts<A, E, R, I, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
620
- ): Resp<I, A2, E2, R2, ComputedRef<AsyncResult.AsyncResult<A2, E2>>>
621
- /**
622
- * Pass a function that returns an Effect, e.g from a client action, give it a name.
623
- * Returns a tuple with raw Result and execution function which reports success and errors as Toast.
624
- * @deprecated use `Command.fn` and friends instead
625
- */
626
- <
627
- E extends ResponseErrors,
628
- A,
629
- R,
630
- Request extends Req,
631
- Name extends string,
632
- A2 = A,
633
- E2 extends ResponseErrors = E,
634
- R2 = R,
635
- ESuccess = never,
636
- RSuccess = never,
637
- EError = never,
638
- RError = never,
639
- EDefect = never,
640
- RDefect = never
641
- >(
642
- self: RequestHandler<A, E, R, Request, Name>,
643
- action: string,
644
- options?: Opts<A, E, R, void, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
645
- ): ActResp<A2, E2, R2, ComputedRef<AsyncResult.AsyncResult<A2, E2>>>
646
- } = <E extends ResponseErrors, A, R, Request extends Req, Name extends string, I>(
647
- self: RequestHandlerWithInput<I, A, E, R, Request, Name> | RequestHandler<A, E, R, Request, Name>,
648
- action: any,
649
- options?: Opts<any, any, any, any, any, any, any, any, any, any, any, any, any>
650
- ): any => {
651
- const handleRequestWithToast = this.useHandleRequestWithToast()
652
- const handler = self.handler
653
- const unsafe = _useMutation({
654
- ...self,
655
- handler: Effect.isEffect(handler)
656
- ? (pipe(
657
- Effect.annotateCurrentSpan({ action }),
658
- Effect.andThen(handler)
659
- ) as any)
660
- : (...args: [any]) =>
661
- pipe(
662
- Effect.annotateCurrentSpan({ action }),
663
- Effect.andThen(handler(...args))
664
- )
665
- }, options ? dropUndefinedT(options) : undefined)
666
-
667
- type MH = NonNullable<NonNullable<typeof options>["mapHandler"]>
668
- const mh = options?.mapHandler ?? identity as MH
669
-
670
- // Effect.tapDefect(reportRuntimeError) handled in toast handler,
671
- const [a, b] = asResult(mapHandler(unsafe, mh) as any)
672
-
673
- return tuple(
674
- a,
675
- handleRequestWithToast(b as any, self.id, action, options)
676
- )
677
- }
678
- //
679
-
680
- /**
681
- * Pass a function that returns an Effect, e.g from a client action, give it a name.
682
- * Returns a tuple with state ref and execution function which reports success and errors as Toast.
683
- *
684
- * @deprecated use `Command.fn` and friends instead
685
- */
686
- readonly useAndHandleMutation: {
687
- /**
688
- * Pass a function that returns an Effect, e.g from a client action, give it a name.
689
- * Returns a tuple with state ref and execution function which reports success and errors as Toast.
690
- *
691
- * @deprecated use `Command.fn` and friends instead
692
- */
693
- <
694
- I,
695
- E extends ResponseErrors,
696
- A,
697
- R,
698
- Request extends Req,
699
- Name extends string,
700
- A2 = A,
701
- E2 extends ResponseErrors = E,
702
- R2 = R,
703
- ESuccess = never,
704
- RSuccess = never,
705
- EError = never,
706
- RError = never,
707
- EDefect = never,
708
- RDefect = never
709
- >(
710
- self: RequestHandlerWithInput<I, A, E, R, Request, Name>,
711
- action: string,
712
- options?: Opts<A, E, R, I, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
713
- ): Resp<I, A2, E2, R2>
714
- /**
715
- * Pass a function that returns an Effect, e.g from a client action, give it a name.
716
- * Returns a tuple with state ref and execution function which reports success and errors as Toast.
717
- *
718
- * @deprecated use `Command.fn` and friends instead
719
- */
720
- <
721
- E extends ResponseErrors,
722
- A,
723
- R,
724
- Request extends Req,
725
- Name extends string,
726
- A2 = A,
727
- E2 extends ResponseErrors = E,
728
- R2 = R,
729
- ESuccess = never,
730
- RSuccess = never,
731
- EError = never,
732
- RError = never,
733
- EDefect = never,
734
- RDefect = never
735
- >(
736
- self: RequestHandler<A, E, R, Request, Name>,
737
- action: string,
738
- options?: Opts<A, E, R, void, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
739
- ): ActResp<A2, E2, R2>
740
- } = (
741
- self: any,
742
- action: any,
743
- options?: Opts<any, any, any, any, any, any, any, any, any, any, any, any, any>
744
- ): any => {
745
- const [a, b] = this.useAndHandleMutationResult(self, action, options)
746
-
747
- return tuple(
748
- computed(() => mutationResultToVue(a.value)),
749
- b
750
- )
751
- }
752
-
753
- /** @deprecated use `Command.fn` and friends instead */
754
- readonly makeUseAndHandleMutation = (
755
- defaultOptions?: Opts<any, any, any, any, any, any, any, any, any>
756
- ) =>
757
- ((self: any, action: any, options: any) => {
758
- return this.useAndHandleMutation(
759
- self,
760
- action,
761
- { ...defaultOptions, ...options }
762
- )
763
- }) as unknown as {
764
- <
765
- I,
766
- E extends ResponseErrors,
767
- A,
768
- R,
769
- Request extends Req,
770
- Name extends string,
771
- A2 = A,
772
- E2 extends ResponseErrors = E,
773
- R2 = R,
774
- ESuccess = never,
775
- RSuccess = never,
776
- EError = never,
777
- RError = never,
778
- EDefect = never,
779
- RDefect = never
780
- >(
781
- self: RequestHandlerWithInput<I, A, E, R, Request, Name>,
782
- action: string,
783
- options?: Opts<A, E, R, I, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
784
- ): Resp<I, A2, E2, R2>
785
- <
786
- E extends ResponseErrors,
787
- A,
788
- R,
789
- Request extends Req,
790
- Name extends string,
791
- A2 = A,
792
- E2 extends ResponseErrors = E,
793
- R2 = R,
794
- ESuccess = never,
795
- RSuccess = never,
796
- EError = never,
797
- RError = never,
798
- EDefect = never,
799
- RDefect = never
800
- >(
801
- self: RequestHandler<A, E, R, Request, Name>,
802
- action: string,
803
- options?: Opts<A, E, R, void, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
804
- ): ActResp<A2, E2, R2>
805
- }
806
-
807
- /**
808
- * The same as @see useAndHandleMutation, but does not display any toasts by default.
809
- * Messages for success, error and defect toasts can be provided in the Options.
810
- * @deprecated use `Command.fn` and friends instead
811
- */
812
- readonly useAndHandleMutationSilently: {
813
- /**
814
- * The same as @see useAndHandleMutation, but does not display any toasts by default.
815
- * Messages for success, error and defect toasts can be provided in the Options.
816
- * @deprecated use `Command.fn` and friends instead
817
- */
818
- <
819
- I,
820
- E extends ResponseErrors,
821
- A,
822
- R,
823
- Request extends Req,
824
- Name extends string,
825
- A2 = A,
826
- E2 extends ResponseErrors = E,
827
- R2 = R,
828
- ESuccess = never,
829
- RSuccess = never,
830
- EError = never,
831
- RError = never,
832
- EDefect = never,
833
- RDefect = never
834
- >(
835
- self: RequestHandlerWithInput<I, A, E, R, Request, Name>,
836
- action: string,
837
- options?: Opts<A, E, R, I, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
838
- ): Resp<I, A2, E2, R>
839
- /**
840
- * The same as @see useAndHandleMutation, but does not display any toasts by default.
841
- * Messages for success, error and defect toasts can be provided in the Options.
842
- * @deprecated use `Command.fn` and friends instead
843
- */
844
- <
845
- E extends ResponseErrors,
846
- A,
847
- R,
848
- Request extends Req,
849
- Name extends string,
850
- A2 = A,
851
- E2 extends ResponseErrors = E,
852
- R2 = R,
853
- ESuccess = never,
854
- RSuccess = never,
855
- EError = never,
856
- RError = never,
857
- EDefect = never,
858
- RDefect = never
859
- >(
860
- self: RequestHandler<A, E, R, Request, Name>,
861
- action: string,
862
- options?: Opts<A, E, R, void, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
863
- ): ActResp<void, never, R>
864
- } = this.makeUseAndHandleMutation({
865
- successMessage: suppressToast,
866
- failMessage: suppressToast,
867
- defectMessage: suppressToast
868
- }) as any
869
-
870
- /**
871
- * The same as @see useAndHandleMutation, but does not act on success, error or defect by default.
872
- * Actions for success, error and defect can be provided in the Options.
873
- * @deprecated use `Command.fn` and friends instead
874
- */
875
- readonly useAndHandleMutationCustom: {
876
- /**
877
- * The same as @see useAndHandleMutation, but does not act on success, error or defect by default.
878
- * Actions for success, error and defect can be provided in the Options.
879
- * @deprecated use `Command.fn` and friends instead
880
- */
881
- <
882
- I,
883
- E extends ResponseErrors,
884
- A,
885
- R,
886
- Request extends Req,
887
- Name extends string,
888
- A2 = A,
889
- E2 extends ResponseErrors = E,
890
- R2 = R,
891
- ESuccess = never,
892
- RSuccess = never,
893
- EError = never,
894
- RError = never,
895
- EDefect = never,
896
- RDefect = never
897
- >(
898
- self: RequestHandlerWithInput<I, A, E, R, Request, Name>,
899
- action: string,
900
- options?: LowOptsOptional<A, E, R, I, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
901
- ): Resp<I, A2, E2, R2>
902
- /**
903
- * The same as @see useAndHandleMutation, but does not act on success, error or defect by default.
904
- * Actions for success, error and defect can be provided in the Options.
905
- * @deprecated use `Command.fn` and friends instead
906
- */
907
- <
908
- E extends ResponseErrors,
909
- A,
910
- R,
911
- Request extends Req,
912
- Name extends string,
913
- A2 = A,
914
- E2 extends ResponseErrors = E,
915
- R2 = R,
916
- ESuccess = never,
917
- RSuccess = never,
918
- EError = never,
919
- RError = never,
920
- EDefect = never,
921
- RDefect = never
922
- >(
923
- self: RequestHandler<A, E, R, Request, Name>,
924
- action: string,
925
- options?: LowOptsOptional<A, E, R, void, A2, E2, R2, ESuccess, RSuccess, EError, RError, EDefect, RDefect>
926
- ): ActResp<A2, E2, R2>
927
- } = (self: any, action: string, options: any) => {
928
- const unsafe = _useMutation({
929
- ...self,
930
- handler: Effect.isEffect(self.handler)
931
- ? (pipe(
932
- Effect.annotateCurrentSpan({ action }),
933
- Effect.andThen(self.handler)
934
- ) as any)
935
- : (...args: any[]) =>
936
- pipe(
937
- Effect.annotateCurrentSpan({ action }),
938
- Effect.andThen(self.handler(...args))
939
- )
940
- }, options ? dropUndefinedT(options) : undefined)
941
-
942
- type MH = NonNullable<NonNullable<typeof options>["mapHandler"]>
943
- const mh = options?.mapHandler ?? identity as MH
944
-
945
- const [a, b] = asResult(
946
- mapHandler(
947
- mapHandler(unsafe as any, mh),
948
- Effect.tapCauseIf(Cause.hasDies, (cause) => reportRuntimeError(cause))
949
- ) as any
950
- )
951
-
952
- return tuple(
953
- computed(() => mutationResultToVue(a.value)),
954
- handleRequest(b as any, self.id, action, {
955
- onSuccess: suppressToast,
956
- onDefect: suppressToast,
957
- onFail: suppressToast,
958
- ...options
959
- })
960
- ) as any
961
- }
962
-
963
- /**
964
- * Effect results are converted to Exit, so errors are ignored by default.
965
- * you should use the result ref to render errors!
966
- * @deprecated use `Command.fn` and friends instead
967
- */
968
- readonly useSafeMutationWithState: {
969
- /**
970
- * Effect results are converted to Exit, so errors are ignored by default.
971
- * you should use the result ref to render errors!
972
- * @deprecated use `Command.fn` and friends instead
973
- */
974
- <I, E, A, R, Request extends Req, Name extends string, A2 = A, E2 = E, R2 = R>(
975
- self: RequestHandlerWithInput<I, A, E, R, Request, Name>,
976
- options?: MutationOptions<A, E, R, A2, E2, R2, I>
977
- ): readonly [
978
- ComputedRef<Res<A, E>>,
979
- (i: I) => Effect.Effect<Exit.Exit<A2, E2>, never, R2>
980
- ]
981
- /**
982
- * Effect results are converted to Exit, so errors are ignored by default.
983
- * you should use the result ref to render errors!
984
- * @deprecated use `Command.fn` and friends instead
985
- */
986
- <E, A, R, Request extends Req, Name extends string, A2 = A, E2 = E, R2 = R>(
987
- self: RequestHandler<A, E, R, Request, Name>,
988
- options?: MutationOptions<A, E, R, A2, E2, R2>
989
- ): readonly [
990
- ComputedRef<Res<A, E>>,
991
- Effect.Effect<Exit.Exit<A2, E2>, never, R2>
992
- ]
993
- } = <I, E, A, R, Request extends Req, Name extends string, A2 = A, E2 = E, R2 = R>(
994
- self: RequestHandlerWithInput<I, A, E, R, Request, Name> | RequestHandler<A, E, R, Request, Name>,
995
- options?: MutationOptions<A, E, R, A2, E2, R2, I>
996
- ) => {
997
- const [a, b] = this.useSafeMutation(self as any, options)
998
-
999
- return tuple(
1000
- computed(() => mutationResultToVue(a.value)),
1001
- b
1002
- ) as any
1003
- }
1004
-
1005
- /** @deprecated use OmegaForm */
1006
- readonly buildFormFromSchema = <
1007
- From extends Record<PropertyKey, any>,
1008
- To extends Record<PropertyKey, any>,
1009
- C extends Record<PropertyKey, any>,
1010
- OnSubmitA
1011
- >(
1012
- s:
1013
- & S.Codec<To>
1014
- & { new(c: C): any; extend: any; fields: S.Struct.Fields },
1015
- state: Ref<Omit<From, "_tag">>,
1016
- onSubmit: (a: To) => Effect.Effect<OnSubmitA, never, RT>
1017
- ) => {
1018
- const fields = buildFieldInfoFromFieldsRoot(s).fields
1019
- const schema = S.Struct(Struct.omit(s.fields, ["_tag"])) as unknown as S.Codec<any> & {
1020
- readonly DecodingServices: never
1021
- }
1022
- const parse = S.decodeUnknownSync(schema)
1023
- const isDirty = ref(false)
1024
- const isValid = ref(true)
1025
- const isLoading = ref(false)
1026
- const runPromise = Effect.runPromiseWith(this.getRuntime())
1027
-
1028
- const submit1 =
1029
- (onSubmit: (a: To) => Effect.Effect<OnSubmitA, never, never>) =>
1030
- async <T extends Promise<{ valid: boolean }>>(e: T) => {
1031
- isLoading.value = true
1032
- try {
1033
- const r = await e
1034
- if (!r.valid) return
1035
- return await runPromise(onSubmit(new (s as any)(await runPromise(parse(state.value)))) as any)
1036
- } finally {
1037
- isLoading.value = false
1038
- }
1039
- }
1040
- const submit = submit1(onSubmit as any)
1041
-
1042
- watch(
1043
- state,
1044
- (v) => {
1045
- // TODO: do better
1046
- isDirty.value = JSON.stringify(v) !== JSON.stringify(state.value)
1047
- },
1048
- { deep: true }
1049
- )
1050
-
1051
- const submitFromState = Effect.gen(function*() {
1052
- return yield* (onSubmit(yield* parse(state.value)) as any)
1053
- })
1054
-
1055
- const submitFromStatePromise = () => runPromise(submitFromState as any)
1056
-
1057
- return {
1058
- fields,
1059
- /** optimized for Vuetify v-form submit callback */
1060
- submit,
1061
- /** optimized for Native form submit callback or general use */
1062
- submitFromState,
1063
- submitFromStatePromise,
1064
- isDirty,
1065
- isValid,
1066
- isLoading
1067
- }
1068
- }
319
+ )) as any
1069
320
  }
1070
321
 
1071
- // @effect-diagnostics-next-line missingEffectServiceDependency:off
1072
- export class LegacyMutation extends ServiceMap.Service<LegacyMutation>()("LegacyMutation", {
1073
- make: Effect.gen(function*() {
1074
- const intl = yield* I18n
1075
- const toast = yield* Toast
1076
-
1077
- return <R>(getRuntime: () => ServiceMap.ServiceMap<R>) => new LegacyMutationImpl(getRuntime, toast, intl)
1078
- })
1079
- }) {
1080
- static readonly DefaultWithoutDependencies = Layer.effect(this, this.make)
1081
- static readonly Default = this.DefaultWithoutDependencies
1082
- }
1083
-
1084
- export type ClientFrom<M extends Requests> = RequestHandlers<never, never, M, M["meta"]["moduleName"]>
322
+ export type ClientFrom<M extends RequestsAny> = RequestHandlers<never, never, M, ExtractModuleName<M>>
1085
323
 
1086
324
  export class QueryImpl<R> {
1087
- constructor(readonly getRuntime: () => ServiceMap.ServiceMap<R>) {
325
+ constructor(readonly getRuntime: () => Context.Context<R>) {
1088
326
  this.useQuery = makeQuery(this.getRuntime)
327
+ this.useStreamQuery = makeStreamQuery(this.getRuntime)
1089
328
  }
1090
329
  /**
1091
330
  * Effect results are passed to the caller, including errors.
@@ -1093,6 +332,12 @@ export class QueryImpl<R> {
1093
332
  */
1094
333
  readonly useQuery: ReturnType<typeof makeQuery<R>>
1095
334
 
335
+ /**
336
+ * Stream results are accumulated as an array of chunks and returned as reactive state.
337
+ * @deprecated use client helpers instead (.query())
338
+ */
339
+ readonly useStreamQuery: ReturnType<typeof makeStreamQuery<R>>
340
+
1096
341
  /**
1097
342
  * The difference with useQuery is that this function will return a Promise you can await in the Setup,
1098
343
  * which ensures that either there always is a latest value, or an error occurs on load.
@@ -1104,52 +349,18 @@ export class QueryImpl<R> {
1104
349
  * The difference with useQuery is that this function will return a Promise you can await in the Setup,
1105
350
  * which ensures that either there always is a latest value, or an error occurs on load.
1106
351
  * So that Suspense and error boundaries can be used.
1107
- * @deprecated use client helpers instead (.suspense())
352
+ * When `I = void` the input argument may be omitted.
1108
353
  */
1109
354
  <
355
+ I,
1110
356
  E,
1111
357
  A,
1112
358
  Request extends Req,
1113
359
  Name extends string
1114
360
  >(
1115
- self: RequestHandler<A, E, R, Request, Name>
1116
- ): {
1117
- /**
1118
- * The difference with useQuery is that this function will return a Promise you can await in the Setup,
1119
- * which ensures that either there always is a latest value, or an error occurs on load.
1120
- * So that Suspense and error boundaries can be used.
1121
- */
1122
- <TData = A>(options?: CustomUndefinedInitialQueryOptions<A, E, TData>): Promise<
1123
- readonly [
1124
- ComputedRef<AsyncResult.AsyncResult<TData, E>>,
1125
- ComputedRef<TData>,
1126
- (
1127
- options?: RefetchOptions
1128
- ) => Effect.Effect<QueryObserverResult<TData, E>>,
1129
- UseQueryReturnType<any, any>
1130
- ]
1131
- >
1132
- }
1133
- /**
1134
- * The difference with useQuery is that this function will return a Promise you can await in the Setup,
1135
- * which ensures that either there always is a latest value, or an error occurs on load.
1136
- * So that Suspense and error boundaries can be used.
1137
- */
1138
- <
1139
- Arg,
1140
- E,
1141
- A,
1142
- Request extends Req,
1143
- Name extends string
1144
- >(
1145
- self: RequestHandlerWithInput<Arg, A, E, R, Request, Name>
361
+ self: RequestHandlerWithInput<I, A, E, R, Request, Name>
1146
362
  ): {
1147
- /**
1148
- * The difference with useQuery is that this function will return a Promise you can await in the Setup,
1149
- * which ensures that either there always is a latest value, or an error occurs on load.
1150
- * So that Suspense and error boundaries can be used.
1151
- */
1152
- <TData = A>(arg: Arg | WatchSource<Arg>, options?: CustomUndefinedInitialQueryOptions<A, E, TData>): Promise<
363
+ <TData = A>(arg: I | WatchSource<I>, options?: CustomUndefinedInitialQueryOptions<A, E, TData>): Promise<
1153
364
  readonly [
1154
365
  ComputedRef<AsyncResult.AsyncResult<TData, E>>,
1155
366
  ComputedRef<TData>,
@@ -1160,10 +371,10 @@ export class QueryImpl<R> {
1160
371
  ]
1161
372
  >
1162
373
  }
1163
- } = <Arg, E, A, Request extends Req, Name extends string>(
1164
- self: RequestHandlerWithInput<Arg, A, E, R, Request, Name> | RequestHandler<A, E, R, Request, Name>
374
+ } = <I, E, A, Request extends Req, Name extends string>(
375
+ self: RequestHandlerWithInput<I, A, E, R, Request, Name>
1165
376
  ) => {
1166
- const runPromise = Effect.runPromiseWith(this.getRuntime())
377
+ const runPromise = makeRunPromise(this.getRuntime())
1167
378
  const q = this.useQuery(self as any) as any
1168
379
  return (argOrOptions?: any, options?: any) => {
1169
380
  const [resultRef, latestRef, fetch, uqrt] = q(argOrOptions, { ...options, suspense: true } // experimental_prefetchInRender: true }
@@ -1214,10 +425,64 @@ export class QueryImpl<R> {
1214
425
  }
1215
426
 
1216
427
  // somehow mrt.runtimeEffect doesnt work sync, but this workaround works fine? not sure why though as the layers are generally only sync
1217
- const managedRuntimeRt = <A, E>(mrt: ManagedRuntime.ManagedRuntime<A, E>) => mrt.runSync(Effect.services<A>())
428
+ const managedRuntimeRt = <A, E>(mrt: ManagedRuntime.ManagedRuntime<A, E>) => mrt.runSync(Effect.context<A>())
1218
429
 
1219
430
  type Base = I18n | Toast
1220
- type Mix = ApiClientFactory | Commander | LegacyMutation | Base
431
+ type Mix = ApiClientFactory | Commander | Base
432
+
433
+ type InvalidationResources = Record<string, Record<string, unknown>>
434
+ type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends ((arg: infer I) => void) ? I
435
+ : never
436
+
437
+ type CommandInvalidationResources<Req> = Req extends {
438
+ readonly type: "command"
439
+ readonly "~invalidationResources"?: infer Resources
440
+ } ? NonNullable<Resources> extends InvalidationResources ? NonNullable<Resources> : never
441
+ : Req extends {
442
+ readonly type: "command"
443
+ readonly config?: infer Config
444
+ } ? Config extends {
445
+ readonly invalidationResources?: infer LegacyResources
446
+ } ? NonNullable<LegacyResources> extends InvalidationResources ? NonNullable<LegacyResources> : never
447
+ : Config extends {
448
+ readonly invalidatesQueries?: InvalidationCallback<infer LegacyResources, any, any, any>
449
+ } ? NonNullable<LegacyResources> extends InvalidationResources ? NonNullable<LegacyResources> : never
450
+ : never
451
+ : never
452
+
453
+ type InvalidationResourcesForUnion<M extends RequestsAny> = {
454
+ [K in keyof M]: CommandInvalidationResources<M[K]>
455
+ }[keyof M]
456
+
457
+ type InvalidationResourcesFor<M extends RequestsAny> = [InvalidationResourcesForUnion<M>] extends [never] ? never
458
+ : UnionToIntersection<InvalidationResourcesForUnion<M>> extends infer R ? R extends InvalidationResources ? R
459
+ : never
460
+ : never
461
+
462
+ type QueryInvalidationFactory<M extends RequestsAny> = (client: ClientFrom<M>) => QueryInvalidation<M>
463
+
464
+ type StrictResourcesArg<Shape, Actual extends Shape = Shape> =
465
+ & Actual
466
+ & Record<Exclude<keyof Actual, keyof Shape>, never>
467
+
468
+ type ClientForArgs<
469
+ M extends RequestsAny,
470
+ Resources extends InvalidationResourcesFor<M> = InvalidationResourcesFor<M>
471
+ > = [InvalidationResourcesFor<M>] extends [never] ? [
472
+ queryInvalidation?: QueryInvalidationFactory<M>,
473
+ invalidationResources?: StrictResourcesArg<
474
+ InvalidationResourcesFor<M>,
475
+ Resources
476
+ >
477
+ ]
478
+ : [
479
+ queryInvalidation: QueryInvalidationFactory<M> | undefined,
480
+ invalidationResources: StrictResourcesArg<
481
+ InvalidationResourcesFor<M>,
482
+ Resources
483
+ >
484
+ ]
485
+
1221
486
  export const makeClient = <RT_, RTHooks>(
1222
487
  // global, but only accessible after startup has completed
1223
488
  getBaseMrt: () => ManagedRuntime.ManagedRuntime<RT_ | Mix, never>,
@@ -1225,126 +490,188 @@ export const makeClient = <RT_, RTHooks>(
1225
490
  rtHooks: Layer.Layer<RTHooks, never, Mix>
1226
491
  ) => {
1227
492
  type RT = RT_ | Mix
1228
- const getRt = Effect.services<RT>()
1229
493
  const getBaseRt = () => managedRuntimeRt(getBaseMrt())
1230
494
  const makeCommand = makeUseCommand<RT, RTHooks>(rtHooks)
1231
- const makeMutation = Effect.gen(function*() {
1232
- const mut = yield* LegacyMutation
1233
-
1234
- return mut(() => getBaseMrt().runSync(getRt))
1235
- })
1236
495
  let cmd: Effect.Success<typeof makeCommand>
1237
496
  const useCommand = () => cmd ??= getBaseMrt().runSync(makeCommand)
1238
- let mut: Effect.Success<typeof makeMutation>
1239
- const getMutation = () => mut ??= getBaseMrt().runSync(makeMutation)
1240
497
 
1241
498
  let m: ReturnType<typeof useMutationInt>
1242
499
  const useMutation = () => m ??= useMutationInt()
1243
500
 
1244
- const keys = [
1245
- "useSafeMutationWithState",
1246
- "useAndHandleMutation",
1247
- "useAndHandleMutationResult",
1248
- "useAndHandleMutationSilently",
1249
- "useAndHandleMutationCustom",
1250
- "makeUseAndHandleMutation",
1251
- "useHandleRequestWithToast",
1252
- "buildFormFromSchema",
1253
- "useSafeMutation"
1254
- ] as const satisfies readonly (keyof ReturnType<typeof getMutation>)[]
1255
- type mut = Pick<LegacyMutationImpl<RT>, typeof keys[number]>
1256
-
1257
- const mutations = keys.reduce(
1258
- (prev, cur) => {
1259
- ;(prev as any)[cur] = ((...args: [any]) => {
1260
- return (getMutation() as any)[cur](...args)
1261
- }) as any
1262
- return prev
1263
- },
1264
- {} as Pick<LegacyMutationImpl<RT>, typeof keys[number]>
1265
- )
501
+ let sm2: ReturnType<typeof makeStreamMutation2>
502
+ const useStreamMutation2 = () => sm2 ??= makeStreamMutation2()
1266
503
 
1267
504
  const query = new QueryImpl(getBaseRt)
1268
505
  const useQuery = query.useQuery
1269
506
  const useSuspenseQuery = query.useSuspenseQuery
507
+ const useStreamQuery = query.useStreamQuery
508
+
509
+ const mergeInvalidation = (
510
+ a?: MutationOptionsBase["queryInvalidation"],
511
+ b?: MutationOptionsBase["queryInvalidation"]
512
+ ): MutationOptionsBase["queryInvalidation"] | undefined => {
513
+ if (!a && !b) {
514
+ return undefined
515
+ }
516
+ return (defaultKey, name, input, output) => [
517
+ ...(a?.(defaultKey, name, input, output) ?? []),
518
+ ...(b?.(defaultKey, name, input, output) ?? [])
519
+ ]
520
+ }
521
+
522
+ const withDefaultInvalidation = (
523
+ mut: any,
524
+ defaultInvalidation?: MutationOptionsBase["queryInvalidation"]
525
+ ) => {
526
+ if (!defaultInvalidation) return mut
527
+ const apply = (callerOpts?: MutationOptionsBase) => ({
528
+ ...callerOpts,
529
+ queryInvalidation: callerOpts?.queryInvalidation
530
+ ? mergeInvalidation(defaultInvalidation, callerOpts.queryInvalidation)
531
+ : defaultInvalidation
532
+ })
533
+ return (input: any, callerOpts?: MutationOptionsBase) => mut(input, apply(callerOpts))
534
+ }
535
+
536
+ const makeQueryResources = <Resources extends InvalidationResources>(resources: Resources | undefined) => {
537
+ if (!resources) {
538
+ return {} as Record<string, Record<string, unknown>>
539
+ }
540
+ return resources as Record<string, Record<string, unknown>>
541
+ }
1270
542
 
1271
- const mapQuery = <M extends Requests>(
543
+ const mapQuery = <M extends RequestsAny>(
1272
544
  client: ClientFrom<M>
1273
545
  ) => {
1274
546
  const queries = Struct.keys(client).reduce(
1275
547
  (acc, key) => {
1276
- ;(acc as any)[camelCase(key) + "Query"] = Object.assign(useQuery(client[key] as any), {
1277
- id: client[key].id
1278
- })
1279
- ;(acc as any)[camelCase(key) + "SuspenseQuery"] = Object.assign(useSuspenseQuery(client[key] as any), {
1280
- id: client[key].id
1281
- })
548
+ const requestType = client[key].Request.type
549
+ const isStream = client[key].Request.stream
550
+ if (requestType === "query" && !isStream) {
551
+ ;(acc as any)[camelCase(key) + "Query"] = Object.assign(useQuery(client[key] as any), {
552
+ id: client[key].id
553
+ })
554
+ ;(acc as any)[camelCase(key) + "SuspenseQuery"] = Object.assign(useSuspenseQuery(client[key] as any), {
555
+ id: client[key].id
556
+ })
557
+ } else if (requestType === "query" && isStream) {
558
+ ;(acc as any)[camelCase(key) + "Query"] = Object.assign(useStreamQuery(client[key] as any), {
559
+ id: client[key].id
560
+ })
561
+ }
1282
562
  return acc
1283
563
  },
1284
564
  {} as
1285
565
  & {
1286
566
  // apparently can't get JSDoc in here..
1287
- [Key in keyof typeof client as `${ToCamel<string & Key>}Query`]: Queries<RT, typeof client[Key]>["query"]
567
+ [
568
+ Key in keyof typeof client as QueryHandler<typeof client[Key]> extends never ? never
569
+ : `${ToCamel<string & Key>}Query`
570
+ ]: Queries<RT, QueryHandler<typeof client[Key]>>["query"]
1288
571
  }
1289
572
  // todo: or suspense as an Option?
1290
573
  & {
1291
574
  // apparently can't get JSDoc in here..
1292
- [Key in keyof typeof client as `${ToCamel<string & Key>}SuspenseQuery`]: Queries<
575
+ [
576
+ Key in keyof typeof client as QueryHandler<typeof client[Key]> extends never ? never
577
+ : `${ToCamel<string & Key>}SuspenseQuery`
578
+ ]: Queries<
1293
579
  RT,
1294
- typeof client[Key]
580
+ QueryHandler<typeof client[Key]>
1295
581
  >["suspense"]
1296
582
  }
583
+ & {
584
+ [
585
+ Key in keyof typeof client as QueryStreamHandler<typeof client[Key]> extends never ? never
586
+ : `${ToCamel<string & Key>}Query`
587
+ ]: StreamQueries<RT, QueryStreamHandler<typeof client[Key]>>["query"]
588
+ }
1297
589
  )
1298
590
  return queries
1299
591
  }
1300
592
 
1301
- const mapRequest = <M extends Requests>(
593
+ const mapRequest = <M extends RequestsAny>(
1302
594
  client: ClientFrom<M>
1303
595
  ) => {
1304
596
  const Command = useCommand()
1305
597
  const mutations = Struct.keys(client).reduce(
1306
598
  (acc, key) => {
599
+ if (!(client[key].Request.type === "command" && !client[key].Request.stream)) {
600
+ return acc
601
+ }
1307
602
  const mut = client[key].handler
1308
- const fn = Command.fn(client[key].id)
1309
- const wrap = Command.wrap({ mutate: Effect.isEffect(mut) ? () => mut : mut, id: client[key].id })
603
+ const request = mut
604
+ const fn = (options?: any) => Command.fn(client[key].id, options)
605
+ const wrap = (options?: any) => Command.wrap({ mutate: request, id: client[key].id }, options)
1310
606
  ;(acc as any)[camelCase(key) + "Request"] = Object.assign(
1311
607
  mut,
1312
- fn, // to get the i18n key etc.
1313
- { wrap, fn }
608
+ Command.fn(client[key].id), // to get the i18n key etc.
609
+ { wrap, fn, request }
1314
610
  )
1315
611
  return acc
1316
612
  },
1317
613
  {} as {
1318
- [Key in keyof typeof client as `${ToCamel<string & Key>}Request`]: RequestWithExtensions<
614
+ [
615
+ Key in keyof typeof client as CommandHandler<typeof client[Key]> extends never ? never
616
+ : `${ToCamel<string & Key>}Request`
617
+ ]: CommandRequestWithExtensions<
1319
618
  RT | RTHooks,
1320
- typeof client[Key]
619
+ CommandHandler<typeof client[Key]>
1321
620
  >
1322
621
  }
1323
622
  )
1324
623
  return mutations
1325
624
  }
1326
625
 
1327
- const mapMutation = <M extends Requests>(
1328
- client: ClientFrom<M>
626
+ const mapMutation = <M extends RequestsAny>(
627
+ client: ClientFrom<M>,
628
+ queryInvalidation?: (client: ClientFrom<M>) => QueryInvalidation<M>,
629
+ invalidationResources?: InvalidationResourcesFor<M>
1329
630
  ) => {
1330
631
  const Command = useCommand()
1331
632
  const mutation = useMutation()
633
+ const invalidation = queryInvalidation?.(client)
634
+ const queryResources = makeQueryResources(invalidationResources)
1332
635
  const mutations = Struct.keys(client).reduce(
1333
636
  (acc, key) => {
1334
- const mut: any = mutation(client[key] as any)
1335
- const fn = Command.fn(client[key].id)
1336
- const wrap = Command.wrap({ mutate: Effect.isEffect(mut) ? () => mut : mut, id: client[key].id })
1337
- ;(acc as any)[camelCase(key) + "Mutation"] = Object.assign(
1338
- mut,
1339
- fn, // to get the i18n key etc.
1340
- { wrap, fn }
1341
- )
637
+ if (!(client[key].Request.type === "command" && !client[key].Request.stream)) {
638
+ return acc
639
+ }
640
+ const fromRequestConfig = client[key].Request.config?.["invalidatesQueries"] as
641
+ | InvalidationCallback<InvalidationResourcesFor<M>>
642
+ | undefined
643
+ const fromRequest = fromRequestConfig
644
+ ? ((defaultKey: string[], _name: string, input?: unknown, output?: unknown) =>
645
+ fromRequestConfig(defaultKey, queryResources as never, input as never, output as never).map((entry) => ({
646
+ filters: entry.filters,
647
+ options: entry.options
648
+ })))
649
+ : undefined
650
+ const mergedInvalidation = mergeInvalidation(fromRequest, invalidation?.[key])
651
+ const makeProjectedMutation = (handler: any): any => {
652
+ const mut: any = withDefaultInvalidation(mutation(handler), mergedInvalidation)
653
+ return Object.assign(mut, {
654
+ wrap: (options?: any) => Command.wrap({ mutate: mut, id: client[key].id }, options),
655
+ fn: (options?: any) => Command.fn(client[key].id, options),
656
+ project: (projectionSchema: any) => {
657
+ const projected = {
658
+ ...handler,
659
+ handler: projectHandler(handler.handler, client[key].Request.success, projectionSchema)
660
+ }
661
+ return makeProjectedMutation(projected)
662
+ }
663
+ })
664
+ }
665
+ ;(acc as any)[camelCase(key) + "Mutation"] = makeProjectedMutation(client[key] as any)
1342
666
  return acc
1343
667
  },
1344
668
  {} as {
1345
- [Key in keyof typeof client as `${ToCamel<string & Key>}Mutation`]: MutationWithExtensions<
669
+ [
670
+ Key in keyof typeof client as CommandHandler<typeof client[Key]> extends never ? never
671
+ : `${ToCamel<string & Key>}Mutation`
672
+ ]: MutationWithExtensions<
1346
673
  RT | RTHooks,
1347
- typeof client[Key]
674
+ CommandHandler<typeof client[Key]>
1348
675
  >
1349
676
  }
1350
677
  )
@@ -1353,8 +680,9 @@ export const makeClient = <RT_, RTHooks>(
1353
680
 
1354
681
  // make available .query, .suspense and .mutate for each operation
1355
682
  // and a .helpers with all mutations and queries
1356
- const mapClient = <M extends Requests>(
1357
- queryInvalidation?: (client: ClientFrom<M>) => QueryInvalidation<M>
683
+ const mapClient = <M extends RequestsAny>(
684
+ queryInvalidation?: (client: ClientFrom<M>) => QueryInvalidation<M>,
685
+ invalidationResources?: InvalidationResourcesFor<M>
1358
686
  ) =>
1359
687
  (
1360
688
  client: ClientFrom<M>
@@ -1362,71 +690,179 @@ export const makeClient = <RT_, RTHooks>(
1362
690
  const Command = useCommand()
1363
691
  const mutation = useMutation()
1364
692
  const invalidation = queryInvalidation?.(client)
693
+ const queryResources = makeQueryResources(invalidationResources)
1365
694
  const extended = Struct.keys(client).reduce(
1366
695
  (acc, key) => {
696
+ const requestType = client[key].Request.type
697
+ const isStream = client[key].Request.stream
1367
698
  const fn = Command.fn(client[key].id)
1368
- const mutate = extendM(
1369
- mutation(
1370
- client[key] as any,
1371
- invalidation?.[key] ? { queryInvalidation: invalidation[key] } : undefined
1372
- ),
1373
- (mutate) =>
1374
- Object.assign(
1375
- mutate,
1376
- fn, // to get the i18n key etc.
1377
- {
1378
- wrap: Command.wrap({ mutate: Effect.isEffect(mutate) ? () => mutate : mutate, id: client[key].id }),
1379
- fn
1380
- }
1381
- )
1382
- )
1383
-
1384
699
  const h_ = client[key].handler
1385
- const h = Effect.isEffect(h_)
1386
- ? () => h_
1387
- : (...args: [any]) => h_(...args)
700
+ const request = h_
1388
701
  ;(acc as any)[key] = Object.assign(
1389
- h,
1390
- client[key],
1391
- fn, // to get the i18n key etc.
1392
- {
1393
- mutate,
1394
- query: useQuery(client[key] as any),
1395
- suspense: useSuspenseQuery(client[key] as any),
1396
- wrap: Command.wrap({ mutate: h, id: client[key].id }),
1397
- fn
1398
- }
702
+ requestType === "query" && !isStream
703
+ ? {
704
+ ...client[key],
705
+ request,
706
+ query: useQuery(client[key] as any),
707
+ suspense: useSuspenseQuery(client[key] as any),
708
+ project: (projectionSchema: any) => {
709
+ const successSchema = client[key].Request.success
710
+ const projectionHash = projectionSchemaHash(projectionSchema)
711
+ const projected = projectHandler(h_ as any, successSchema, projectionSchema)
712
+ const fakeHandler = {
713
+ handler: projected,
714
+ id: client[key].id,
715
+ Request: client[key].Request,
716
+ options: client[key].options,
717
+ queryKeyProjectionHash: projectionHash
718
+ }
719
+ return {
720
+ request: projected,
721
+ query: useQuery(fakeHandler as any),
722
+ suspense: useSuspenseQuery(fakeHandler as any)
723
+ }
724
+ }
725
+ }
726
+ : requestType === "query" && isStream
727
+ ? {
728
+ ...client[key],
729
+ request,
730
+ query: useStreamQuery(client[key] as any)
731
+ }
732
+ : requestType === "command" && isStream
733
+ ? (() => {
734
+ const fromRequestConfig = client[key].Request.config?.["invalidatesQueries"] as
735
+ | InvalidationCallback<InvalidationResourcesFor<M>>
736
+ | undefined
737
+ const fromRequest = fromRequestConfig
738
+ ? ((defaultKey: string[], _name: string, input?: unknown, output?: unknown) =>
739
+ fromRequestConfig(defaultKey, queryResources as never, input as never, output as never).map((
740
+ entry
741
+ ) => ({
742
+ filters: entry.filters,
743
+ options: entry.options
744
+ })))
745
+ : undefined
746
+ const mergedInvalidation = mergeInvalidation(fromRequest, invalidation?.[key])
747
+ const streamCmd = useCommand()
748
+ return {
749
+ ...client[key],
750
+ request,
751
+ query: useStreamQuery(client[key] as any),
752
+ fn: (options?: any) => streamCmd.streamFn(client[key].id as any, options),
753
+ mutate: (() => {
754
+ const sm2Act = useStreamMutation2()(client[key] as any, mergedInvalidation)
755
+ const sm2Handler = (input: any, _ctx: any) => (sm2Act as (i: any) => any)(input)
756
+ return Object.assign(sm2Act, {
757
+ id: client[key].id,
758
+ wrap: (options?: any) => streamCmd.streamWrap(sm2Handler, client[key].id as any, options)
759
+ })
760
+ })()
761
+ }
762
+ })()
763
+ : {
764
+ mutate: ((handler: any) => {
765
+ const fromRequestConfig = client[key].Request.config?.["invalidatesQueries"] as
766
+ | InvalidationCallback<InvalidationResourcesFor<M>>
767
+ | undefined
768
+ const fromRequest = fromRequestConfig
769
+ ? ((defaultKey: string[], _name: string, input?: unknown, output?: unknown) =>
770
+ fromRequestConfig(defaultKey, queryResources as never, input as never, output as never).map((
771
+ entry
772
+ ) => ({
773
+ filters: entry.filters,
774
+ options: entry.options
775
+ })))
776
+ : undefined
777
+ const mergedInvalidation = mergeInvalidation(fromRequest, invalidation?.[key])
778
+ const makeProjectedMutation = (h: any): any => {
779
+ const mutate = withDefaultInvalidation(mutation(h), mergedInvalidation)
780
+ return Object.assign(
781
+ mutate,
782
+ {
783
+ wrap: (options?: any) =>
784
+ Command.wrap({
785
+ mutate,
786
+ id: client[key].id
787
+ }, options),
788
+ fn: (options?: any) => Command.fn(client[key].id, options),
789
+ project: (projectionSchema: any) => {
790
+ const projected = {
791
+ ...h,
792
+ handler: projectHandler(h.handler, client[key].Request.success, projectionSchema)
793
+ }
794
+ return makeProjectedMutation(projected)
795
+ }
796
+ }
797
+ )
798
+ }
799
+ return makeProjectedMutation(handler)
800
+ })(client[key] as any),
801
+ ...client[key],
802
+ ...fn, // to get the i18n key etc.
803
+ request,
804
+ fn: (options?: any) => Command.fn(client[key].id, options),
805
+ wrap: (options?: any) => Command.wrap({ mutate: h_, id: client[key].id }, options)
806
+ }
1399
807
  )
1400
808
  return acc
1401
809
  },
1402
810
  {} as {
1403
811
  [Key in keyof typeof client]:
1404
812
  & typeof client[Key]
1405
- & RequestWithExtensions<RT | RTHooks, typeof client[Key]>
1406
- & { mutate: MutationWithExtensions<RT | RTHooks, typeof client[Key]> }
1407
- & Queries<RT, typeof client[Key]>
813
+ & (QueryHandler<typeof client[Key]> extends never ? {}
814
+ :
815
+ & QueryRequestWithExtensions<QueryHandler<typeof client[Key]>>
816
+ & Queries<RT, QueryHandler<typeof client[Key]>>
817
+ & QueryProjection<RT, QueryHandler<typeof client[Key]>>)
818
+ & (QueryStreamHandler<typeof client[Key]> extends never ? {}
819
+ : StreamQueries<RT, QueryStreamHandler<typeof client[Key]>>)
820
+ & (CommandHandler<typeof client[Key]> extends never ? {}
821
+ : CommandRequestWithExtensions<RT | RTHooks, CommandHandler<typeof client[Key]>>)
822
+ & (CommandHandler<typeof client[Key]> extends never ? {}
823
+ : { mutate: MutationWithExtensions<RT | RTHooks, CommandHandler<typeof client[Key]>> })
824
+ & (CommandStreamHandler<typeof client[Key]> extends never ? {}
825
+ : {
826
+ fn: StreamFnStreamExtension<RT | RTHooks, CommandStreamHandler<typeof client[Key]>>
827
+ mutate: StreamMutation2WithExtensions<RT | RTHooks, CommandStreamHandler<typeof client[Key]>>
828
+ })
829
+ & { Input: typeof client[Key] extends RequestHandlerWithInput<infer I, any, any, any, any, any> ? I : never }
1408
830
  }
1409
831
  )
1410
- return Object.assign(extended, { helpers: { ...mapRequest(client), ...mapMutation(client), ...mapQuery(client) } })
832
+ return Object.assign(extended, {
833
+ helpers: {
834
+ ...mapRequest(client),
835
+ ...mapMutation(client, queryInvalidation, invalidationResources),
836
+ ...mapQuery(client)
837
+ }
838
+ })
1411
839
  }
1412
840
 
1413
841
  // TODO: Clean up this delay initialisation messs
1414
842
  // TODO; invalidateQueries should perhaps be configured in the Request impl themselves?
1415
- const clientFor__ = <M extends Requests>(
843
+ const clientFor__ = <M extends RequestsAny>(
1416
844
  m: M,
1417
- queryInvalidation?: (client: ClientFrom<M>) => QueryInvalidation<M>
1418
- ) => getBaseMrt().runSync(clientFor_(m).pipe(Effect.map(mapClient(queryInvalidation))))
845
+ queryInvalidation?: QueryInvalidationFactory<M>,
846
+ invalidationResources?: InvalidationResourcesFor<M>
847
+ ) => getBaseMrt().runSync(clientFor_(m).pipe(Effect.map(mapClient(queryInvalidation, invalidationResources))))
1419
848
 
1420
849
  // delay client creation until first access
1421
850
  // the idea is that we don't need the useNuxtApp().$runtime (only available at later initialisation stage)
1422
851
  // until we are at a place where it is available..
1423
- const clientFor = <M extends Requests>(
852
+ const clientFor = <
853
+ M extends RequestsAny,
854
+ Resources extends InvalidationResourcesFor<M> = InvalidationResourcesFor<M>
855
+ >(
1424
856
  m: M,
1425
- queryInvalidation?: (client: ClientFrom<M>) => QueryInvalidation<M>
857
+ ...args: ClientForArgs<M, Resources>
1426
858
  ) => {
859
+ const [queryInvalidation, invalidationResources] = args as [
860
+ QueryInvalidationFactory<M> | undefined,
861
+ InvalidationResourcesFor<M> | undefined
862
+ ]
1427
863
  type Client = ReturnType<typeof clientFor__<M>>
1428
864
  let client: Client | undefined = undefined
1429
- const getOrMakeClient = () => (client ??= clientFor__(m, queryInvalidation))
865
+ const getOrMakeClient = () => (client ??= clientFor__(m, queryInvalidation, invalidationResources))
1430
866
 
1431
867
  // initialize on first use..
1432
868
  const proxy = Struct.keys(m).concat(["helpers"]).reduce((acc, key) => {
@@ -1444,16 +880,12 @@ export const makeClient = <RT_, RTHooks>(
1444
880
  return proxy
1445
881
  }
1446
882
 
1447
- const legacy: Legacy<RT> = {
1448
- ...mutations,
1449
- ...query
1450
- }
1451
-
1452
883
  const Command: CommanderResolved<RT, RTHooks> = {
1453
884
  ...{
1454
885
  // delay initialisation until first use...
1455
886
  fn: (...args: [any]) => useCommand().fn(...args),
1456
887
  wrap: (...args: [any]) => useCommand().wrap(...args),
888
+ streamFn: (...args: [any]) => useCommand().streamFn(...args),
1457
889
  alt: (...args: [any]) => useCommand().alt(...args),
1458
890
  alt2: (...args: [any]) => useCommand().alt2(...args)
1459
891
  } as ReturnType<typeof useCommand>,
@@ -1463,19 +895,17 @@ export const makeClient = <RT_, RTHooks>(
1463
895
  return {
1464
896
  Command,
1465
897
  useCommand,
1466
- clientFor,
1467
- legacy
898
+ clientFor
1468
899
  }
1469
900
  }
1470
901
 
1471
- export interface Legacy<R>
1472
- extends
1473
- Pick<QueryImpl<R>, "useQuery" | "useSuspenseQuery">,
1474
- Omit<LegacyMutationImpl<R>, "getRuntime" | "toast" | "intl">
1475
- {}
1476
-
1477
902
  export type QueryInvalidation<M> = {
1478
- [K in keyof M]?: (defaultKey: string[], name: string) => {
903
+ [K in keyof M]?: (
904
+ defaultKey: string[],
905
+ name: string,
906
+ input?: unknown,
907
+ output?: ExitResult.Exit<unknown, unknown>
908
+ ) => {
1479
909
  filters?: InvalidateQueryFilters | undefined
1480
910
  options?: InvalidateOptions | undefined
1481
911
  }[]
@@ -1486,17 +916,21 @@ export type ToCamel<S extends string | number | symbol> = S extends string
1486
916
  : Uncapitalize<S>
1487
917
  : never
1488
918
 
1489
- export interface CommandBase<I = void, A = void> {
919
+ export interface CommandBase<I = void, A = void, RA = unknown, RE = unknown> {
1490
920
  handle: (input: I) => A
1491
921
  waiting: boolean
1492
922
  blocked: boolean
1493
923
  allowed: boolean
1494
924
  action: string
1495
925
  label: string
926
+ /** formatted progress info for current `running` state, when `progress` was supplied */
927
+ progress?: Progress | undefined
928
+ /** reactive result state, available on stream-backed commands */
929
+ result?: AsyncResult.AsyncResult<RA, RE>
1496
930
  }
1497
931
 
1498
- export interface EffectCommand<I = void, A = unknown, E = unknown> extends CommandBase<I, Fiber<A, E>> {}
932
+ export interface EffectCommand<I = void, A = unknown, E = unknown> extends CommandBase<I, Fiber<A, E>, A, E> {}
1499
933
 
1500
- export interface CommandFromRequest<I extends abstract new(...args: any) => any, A = unknown, E = unknown>
1501
- extends EffectCommand<ConstructorParameters<I>[0], A, E>
934
+ export interface CommandFromRequest<I extends { readonly make: (...args: any[]) => any }, A = unknown, E = unknown>
935
+ extends EffectCommand<HandlerInput<I>, A, E>
1502
936
  {}