@effect-app/vue 4.0.0-beta.28 → 4.0.0-beta.280

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