@pixotope/query 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,61 +1,266 @@
1
1
  import * as _pixotope_zmq_client from '@pixotope/zmq-client';
2
2
  import { ZMQClient, TSocketServerCallOptions, ZMQProxyWSClient } from '@pixotope/zmq-client';
3
3
 
4
+ /**
5
+ * Configuration options for {@link useQuery}.
6
+ *
7
+ * @typeParam TData - The raw data type returned by `queryFn`.
8
+ * @typeParam TError - The error type reported to `onError`/`onSettled` and exposed via `error`.
9
+ * @typeParam TParams - The type of the parameters passed to `refetch`/`queryFn`.
10
+ * @typeParam TSelectData - The type of the data after `select` has been applied. Defaults to `TData`.
11
+ * @typeParam Stateless - When `true`, the hook does not keep fetched data in state (see {@link QueryOptions.stateless}).
12
+ */
4
13
  interface QueryOptions<TData = unknown, TError = unknown, TParams = void, TSelectData = TData, Stateless extends true | undefined = undefined> {
14
+ /**
15
+ * Function that fetches the data for this query. Called automatically on mount, whenever
16
+ * `key` changes, and whenever `refetch` is invoked.
17
+ * @param params - The params passed to `refetch`, or `undefined`/`void` for an automatic fetch.
18
+ * @param queryInfo - Contextual info about the current query: `key` is the normalized query
19
+ * key currently in use, and `lastFetchedAt` is the timestamp (ms) of the last successful fetch,
20
+ * or `undefined` if the query has never succeeded.
21
+ * @returns A promise that resolves with the fetched data.
22
+ */
5
23
  queryFn: (params: TParams | undefined | void, queryInfo: {
6
24
  key: TQueryKey | undefined;
7
25
  lastFetchedAt: number | undefined;
8
26
  }) => Promise<TData>;
27
+ /** Called after `queryFn` resolves successfully, with the raw (pre-`select`) data. */
9
28
  onSuccess?: (data: TData) => Promise<void> | void;
29
+ /** Called after `queryFn` rejects, or after `compareOrThrow` reports a failed comparison. */
10
30
  onError?: (error: TQueryError<TError>) => Promise<void> | void;
31
+ /**
32
+ * Called after every fetch attempt settles, whether it succeeded or failed. Exactly one of
33
+ * `data`/`error` will be defined.
34
+ */
11
35
  onSettled?: (data: TData | undefined, error: TQueryError<TError> | undefined) => Promise<void> | void;
36
+ /**
37
+ * Maximum time, in milliseconds, to wait for `queryFn` to resolve before the query is
38
+ * considered failed with a `timeout` error. When omitted, the query never times out.
39
+ */
12
40
  timeout?: number;
41
+ /**
42
+ * Whether the query is allowed to fetch. When `false`, `queryFn` is not called on mount,
43
+ * on `key` changes, or on an interval/focus refetch.
44
+ * @default true
45
+ */
13
46
  enabled?: boolean;
47
+ /**
48
+ * Data (or a function returning data) to seed `data` with before the first fetch resolves.
49
+ */
14
50
  initialData?: TData | Functionize<TData>;
51
+ /**
52
+ * Transforms the raw fetched data into the shape consumers should receive via `data`. Applied
53
+ * on every render, not just on fetch, so it should be cheap and side-effect free.
54
+ */
15
55
  select?: (data: TData) => TSelectData;
56
+ /**
57
+ * Whether to automatically refetch when the browser window regains focus.
58
+ * @default false
59
+ */
16
60
  refetchOnWindowFocus?: boolean;
61
+ /**
62
+ * When greater than `0`, automatically refetches on this interval (in milliseconds), as long
63
+ * as at least this much time has passed since the last successful fetch.
64
+ * @default 0
65
+ */
17
66
  refetchInterval?: number;
67
+ /**
68
+ * Function that will be called with the freshly fetched data before it is stored. Returning
69
+ * `true` causes the fetch to be treated as a failure (status becomes `"error"`, `onError`/
70
+ * `onSettled` are called) instead of a success.
71
+ */
18
72
  compareOrThrow?: (data: TData) => boolean;
73
+ /**
74
+ * Whether the query is stateless. When `true`, fetched data is not stored by the hook and the
75
+ * returned object will not include a `data` field.
76
+ * @default false
77
+ */
19
78
  stateless?: Stateless;
79
+ /**
80
+ * The query key. Whenever this array's serialized value changes, the query automatically
81
+ * refetches. Pass a stable/memoized array to avoid unintended refetches.
82
+ */
20
83
  key?: TQueryKey;
21
84
  }
85
+ /** A value, or a function returning it. Used to type {@link QueryOptions.initialData}. */
22
86
  type Functionize<T> = () => T;
87
+ /** The status of a {@link useQuery} call, as exposed via {@link UseQueryResult}'s `status`. */
23
88
  type QueryStatus = "idle" | "loading" | "success" | "error" | "timeout";
24
- type WithData$1<TData> = {
89
+ /** Adds the `data` field to {@link UseQueryResult} when the query is not {@link QueryOptions.stateless}. */
90
+ type WithQueryData<TData> = {
25
91
  data: TData | undefined;
26
92
  };
93
+ /** The type of {@link QueryOptions.key}: an array whose serialized value determines when the query refetches. */
27
94
  type TQueryKey = readonly any[];
95
+ /** The error type exposed via {@link UseQueryResult}'s `error` and passed to `onError`/`onSettled`. */
28
96
  type TQueryError<TError> = TError | Error | null;
97
+ /**
98
+ * The value returned by {@link useQuery}.
99
+ *
100
+ * @typeParam TData - The (post-`select`) data type exposed via `data`.
101
+ * @typeParam TError - The error type exposed via `error`.
102
+ * @typeParam TParams - The type of the parameters accepted by `refetch`.
103
+ * @typeParam TSelectData - The type of the data after `select` has been applied.
104
+ * @typeParam Stateless - When `true`, the `data` field is omitted from the result.
105
+ */
29
106
  type UseQueryResult<TData = unknown, TError = unknown, TParams = void, TSelectData = TData, Stateless extends true | undefined = undefined> = {
107
+ /** The error from the most recent failed fetch, or `null` if the last fetch succeeded (or none has happened yet). */
30
108
  error: TQueryError<TError>;
109
+ /** The current status of the query: `"idle"`, `"loading"`, `"success"`, `"error"`, or `"timeout"`. */
31
110
  status: QueryStatus;
111
+ /**
112
+ * Manually triggers a fetch, bypassing `enabled`'s effect on automatic fetches (it still
113
+ * respects the current `enabled` value at call time).
114
+ * @param params - Params to pass to `queryFn` for this fetch.
115
+ * @returns A promise that resolves once the fetch has settled.
116
+ */
32
117
  refetch: (params: TParams | void | undefined) => Promise<void>;
118
+ /** Clears `data`, `error` and `status` back to their initial values, then triggers a refetch. */
33
119
  reset: () => void;
34
- } & (Stateless extends true ? {} : WithData$1<TSelectData>);
120
+ } & (Stateless extends true ? {} : WithQueryData<TSelectData>);
121
+ /**
122
+ * React hook for fetching, caching (per-render, in component state) and refetching async data.
123
+ *
124
+ * `queryFn` runs automatically on mount, whenever `key` changes, and whenever `refetch` is
125
+ * called. It races against `timeout` (when provided), and its result is exposed via `data`
126
+ * (after `select`, if provided), `status`, and `error`.
127
+ *
128
+ * @typeParam TData - The raw data type returned by `queryFn`.
129
+ * @typeParam TError - The error type surfaced via `error` and `onError`.
130
+ * @typeParam TParams - The type of the parameters accepted by `refetch`.
131
+ * @typeParam TSelected - The type of the data after `select` has been applied. Defaults to `TData`.
132
+ * @typeParam Stateless - When `true`, the hook does not keep fetched data in state.
133
+ * @param options - See {@link QueryOptions}.
134
+ * @returns See {@link UseQueryResult}.
135
+ * @example
136
+ * ```tsx
137
+ * const { data, status, error, refetch } = useQuery({
138
+ * key: ["user", userId],
139
+ * queryFn: () => fetchUser(userId),
140
+ * });
141
+ * ```
142
+ */
35
143
  declare const useQuery: <TData = unknown, TError = unknown, TParams = void, TSelected = TData, Stateless extends true | undefined = undefined>({ queryFn, ...options }: QueryOptions<TData, TError, TParams, TSelected, Stateless>) => UseQueryResult<TSelected, TError, TParams, TSelected, Stateless>;
36
144
 
145
+ /**
146
+ * The async function a mutation invokes to perform its side effect.
147
+ * @typeParam TData - The type of data the mutation resolves with.
148
+ * @typeParam TParams - The type of the variables passed in to trigger the mutation.
149
+ * @typeParam TMetadata - The type of the optional, per-call metadata.
150
+ * @param params - The variables for this mutation call.
151
+ * @param meta - Optional per-call metadata, passed through unchanged from `mutate`/`mutateAsync`.
152
+ * @returns A promise that resolves with the mutation's result.
153
+ */
37
154
  type MutationFunction<TData = unknown, TParams = unknown, TMetadata = unknown> = (params: TParams, meta?: TMetadata) => Promise<TData>;
155
+ /**
156
+ * Configuration options for {@link useMutation}.
157
+ *
158
+ * @typeParam TData - The type of data `mutationFn` resolves with.
159
+ * @typeParam TError - The error type reported to `onError`/`onSettled` and exposed via `error`.
160
+ * @typeParam TParams - The type of the variables passed in to trigger the mutation.
161
+ * @typeParam TMetadata - The type of the optional, per-call metadata.
162
+ */
38
163
  interface MutationOptions<TData = unknown, TError = unknown, TParams = void, TMetadata = unknown> {
164
+ /** The async function invoked by `mutate`/`mutateAsync` to perform the mutation. */
39
165
  mutationFn: MutationFunction<TData, TParams, TMetadata>;
166
+ /** Default variables passed to `prepareParams` (as its `defaults` argument) for every call. */
40
167
  params?: TParams;
168
+ /** Called after `mutationFn` resolves successfully. */
41
169
  onSuccess?: (data: TData, variables: TParams, meta?: TMetadata) => Promise<unknown> | unknown;
170
+ /** Called after `mutationFn` rejects, or after `compareOrThrow` reports a failed comparison. */
42
171
  onError?: (error: TMutationError<TError>, variables: TParams, meta?: TMetadata) => Promise<unknown> | unknown;
172
+ /**
173
+ * Called after every mutation attempt settles, whether it succeeded or failed. Exactly one of
174
+ * `data`/`error` will be defined.
175
+ */
43
176
  onSettled?: (data: TData | undefined, error: TMutationError<TError> | null, variables: TParams, meta?: TMetadata) => Promise<unknown> | unknown;
177
+ /**
178
+ * Function that will be called with the result of `mutationFn` before it is stored. Returning
179
+ * `true` causes the call to fail with a {@link ComparisonFailError} instead of succeeding.
180
+ */
44
181
  compareOrThrow?: (result: TData | TError) => boolean;
182
+ /**
183
+ * Maximum time, in milliseconds, to wait for `mutationFn` to resolve before the call is
184
+ * considered failed with a `timeout` error. When omitted, the call never times out.
185
+ */
45
186
  timeout?: number;
187
+ /**
188
+ * Transforms the variables passed to `mutate`/`mutateAsync` before they reach `mutationFn`.
189
+ * @param variables - The variables passed to this call.
190
+ * @param defaults - The `params` configured on the hook, if any.
191
+ * @param meta - The per-call metadata, if any.
192
+ * @returns The variables to actually pass to `mutationFn`.
193
+ */
46
194
  prepareParams?: (variables: TParams, defaults?: TParams, meta?: TMetadata) => TParams;
47
195
  }
196
+ /** The error type exposed via `error`/`onError`/`onSettled` on {@link MutationOptions}, {@link MutateOptions}, and {@link useMutation}'s return value. */
48
197
  type TMutationError<TError> = TError | Error | null;
198
+ /**
199
+ * Per-call callback overrides accepted as the second argument to `mutate` (see
200
+ * {@link useMutation}'s return value). Called in addition to the callbacks configured via
201
+ * {@link MutationOptions}.
202
+ *
203
+ * @typeParam TData - The type of data the mutation resolves with.
204
+ * @typeParam TError - The error type reported to `onError`/`onSettled`.
205
+ * @typeParam TParams - The type of the variables passed in to trigger the mutation.
206
+ * @typeParam TMetadata - The type of the optional, per-call metadata.
207
+ */
49
208
  interface MutateOptions<TData = unknown, TError = unknown, TParams = void, TMetadata = unknown> {
209
+ /** Called after `mutationFn` resolves successfully. */
50
210
  onSuccess?: (data: TData, variables: TParams, meta?: TMetadata) => void;
211
+ /** Called after `mutationFn` rejects, or after `compareOrThrow` reports a failed comparison. */
51
212
  onError?: (error: TMutationError<TError>, variables: TParams, meta?: TMetadata) => void;
213
+ /**
214
+ * Called after every mutation attempt settles, whether it succeeded or failed. Exactly one of
215
+ * `data`/`error` will be defined.
216
+ */
52
217
  onSettled?: (data: TData | undefined, error: TMutationError<TError> | null, variables: TParams, meta?: TMetadata) => void;
53
218
  }
219
+ /** The status of a {@link useMutation} call, as exposed via its return value's `status`. */
54
220
  type MutationStatus = "idle" | "loading" | "success" | "error";
221
+ /**
222
+ * Error thrown (and stored as the mutation's `error`) when a mutation's `compareOrThrow` option
223
+ * returns `true` for a successfully resolved result, i.e. the call is treated as a failure
224
+ * despite `mutationFn` not rejecting.
225
+ *
226
+ * @typeParam TPayload - The type of the offending result, available via `payload`.
227
+ */
55
228
  declare class ComparisonFailError<TPayload = unknown> extends Error {
229
+ /** The result that `compareOrThrow` rejected. */
56
230
  readonly payload: TPayload;
231
+ /**
232
+ * @param message - The error message.
233
+ * @param payload - The result that `compareOrThrow` rejected, preserved on the error.
234
+ */
57
235
  constructor(message: string, payload: TPayload);
58
236
  }
237
+ /**
238
+ * React hook for triggering an async side effect (a "mutation") and tracking its status, result
239
+ * and error, without fetching automatically the way {@link useQuery} does.
240
+ *
241
+ * @typeParam TData - The type of data `mutationFn` resolves with.
242
+ * @typeParam TError - The error type surfaced via `error` and `onError`.
243
+ * @typeParam TParams - The type of the variables passed in to trigger the mutation.
244
+ * @typeParam TMetadata - The type of the optional, per-call metadata.
245
+ * @param options - See {@link MutationOptions}.
246
+ * @returns An object with:
247
+ * - `status` - the current status: `"idle"`, `"loading"`, `"success"`, or `"error"`.
248
+ * - `result` - the data from the most recently successful call, if any.
249
+ * - `error` - the error from the most recently failed call, if any.
250
+ * - `mutate` - fire-and-forget trigger; accepts per-call `variables` and, optionally,
251
+ * {@link MutateOptions} plus `meta`.
252
+ * - `mutateAsync` - same as `mutate`, but returns the promise from `mutationFn` (rejects on
253
+ * failure) so callers can `await` it.
254
+ * - `reset` - resets `status`, `result` and `error` back to their initial values.
255
+ * @example
256
+ * ```tsx
257
+ * const { mutate, status } = useMutation({
258
+ * mutationFn: (vars: { name: string }) => createUser(vars),
259
+ * });
260
+ *
261
+ * mutate({ name: "Ada" }, { onSuccess: (user) => console.log(user.id) });
262
+ * ```
263
+ */
59
264
  declare const useMutation: <TData = unknown, TError = unknown, TParams = void, TMetadata = unknown>(options: MutationOptions<TData, TError, TParams, TMetadata>) => {
60
265
  mutateAsync: (params: TParams, meta?: TMetadata) => Promise<TData>;
61
266
  status: MutationStatus;
@@ -67,12 +272,36 @@ declare const useMutation: <TData = unknown, TError = unknown, TParams = void, T
67
272
  error: TMutationError<TError>;
68
273
  };
69
274
 
275
+ /**
276
+ * Describes the data/error/params types for a single remote function, keyed by function name in
277
+ * a `TFnToParams` map. Used with {@link buildMutationHook} and {@link buildQueryHook} to give the
278
+ * hooks they build full type inference for `func`, its params and its result, based on the
279
+ * function name passed in.
280
+ *
281
+ * @example
282
+ * ```ts
283
+ * type MyFunctions = {
284
+ * createUser: MutationInfo<User, ApiError, { name: string }>;
285
+ * };
286
+ * ```
287
+ */
70
288
  type MutationInfo<TData, TError, TParams> = {
71
289
  data: TData;
72
290
  error: TError;
73
291
  params: TParams;
74
292
  };
293
+ /** The constraint a `TFnToParams` map must satisfy for {@link buildMutationHook}/{@link buildQueryHook}: a record of function name to its {@link MutationInfo}. */
75
294
  type FnToParamsBase = Record<string, MutationInfo<unknown, unknown, unknown>>;
295
+ /**
296
+ * The shape of a ZMQ remote-call function, as bound by {@link bindPromiseFunction}. Given a
297
+ * service/function/parameters triple, it performs the call and resolves with the response.
298
+ *
299
+ * @typeParam TResponse - The type of data the call resolves with.
300
+ * @typeParam TParams - The type of the `parameters` sent with the call.
301
+ * @typeParam TExtraParams - The type of the optional `meta` passed alongside the call.
302
+ * @param args - The service and function to call, its parameters, and call options/metadata.
303
+ * @returns A promise that resolves with the call's result.
304
+ */
76
305
  type TPromiseFunction<TResponse, TParams, TExtraParams> = (args: Omit<ZMQClient.Call<TResponse, {
77
306
  functionName: string;
78
307
  parameters: TParams;
@@ -80,123 +309,217 @@ type TPromiseFunction<TResponse, TParams, TExtraParams> = (args: Omit<ZMQClient.
80
309
  }>, "id"> & {
81
310
  meta?: TExtraParams;
82
311
  }) => Promise<TResponse>;
312
+ /**
313
+ * Internal helper backing the hook returned by {@link buildMutationHook}. Wraps a ZMQ
314
+ * `promiseFunc` call for a single remote function name into a {@link useMutation} instance.
315
+ */
83
316
  declare const useCallMutationBase: <TFnToParams extends FnToParamsBase, TData = unknown, TError = unknown, TParams = unknown, TMetadata = unknown>(promiseFunc: TPromiseFunction<TData, TParams, TMetadata>, functionName: keyof TFnToParams, service: (meta?: TMetadata) => string, options?: Omit<MutationOptions<TData, TError, TParams, TMetadata>, "mutationFn">) => {
84
317
  mutateAsync: (params: TParams, meta?: TMetadata | undefined) => Promise<TData>;
85
- status: "idle" | "loading" | "success" | "error";
318
+ status: MutationStatus;
86
319
  result: TData | undefined;
87
320
  mutate: (variables: TParams, options?: (MutateOptions<TData, TError, TParams, TMetadata> & {
88
321
  meta?: TMetadata | undefined;
89
322
  }) | undefined) => void;
90
323
  reset: () => void;
91
- error: Error | TError | null;
324
+ error: TMutationError<TError>;
92
325
  };
326
+ /**
327
+ * Builds a `useMutation`-like hook for calling remote ZMQ functions by name, with full type
328
+ * inference of `data`/`error`/`params` from the `TFnToParams` map.
329
+ *
330
+ * This is the recommended way to expose a typed mutation hook for a service: call this once
331
+ * with a bound {@link TPromiseFunction} (see {@link bindPromiseFunction}) and a function that
332
+ * resolves the target service name, then export the resulting hook for consumers.
333
+ *
334
+ * @typeParam TFnToParams - A map from remote function name to its {@link MutationInfo}
335
+ * (data/error/params types).
336
+ * @typeParam TMetadata - The type of the optional metadata forwarded to `genTargetService` and `promiseFunc`.
337
+ * @param promiseFunc - The transport function that performs the actual remote call.
338
+ * @param genTargetService - Resolves the target service name for a call, given its metadata.
339
+ * @returns A `useCallMutationBuilder` hook: call it with a function name (a key of
340
+ * `TFnToParams`) and the same options as {@link useMutation} (minus `mutationFn`) to get a
341
+ * mutation scoped to that remote function.
342
+ * @example
343
+ * ```ts
344
+ * const useCreateUser = buildMutationHook<MyFunctions>(
345
+ * bindPromiseFunction(proxyClient),
346
+ * () => "UserService"
347
+ * );
348
+ * ```
349
+ */
93
350
  declare function buildMutationHook<TFnToParams extends FnToParamsBase, TMetadata = unknown>(promiseFunc: TPromiseFunction<unknown, unknown, unknown>, genTargetService: (meta?: TMetadata) => string): <TFn extends keyof TFnToParams>(func: TFn, options?: Parameters<typeof useCallMutationBase<TFnToParams, TFnToParams[TFn]["data"], TFnToParams[TFn]["error"], TFnToParams[TFn]["params"], TMetadata>>[3]) => {
94
351
  mutateAsync: (params: TFnToParams[TFn]["params"], meta?: TMetadata | undefined) => Promise<TFnToParams[TFn]["data"]>;
95
- status: "idle" | "loading" | "success" | "error";
352
+ status: MutationStatus;
96
353
  result: TFnToParams[TFn]["data"] | undefined;
97
354
  mutate: (variables: TFnToParams[TFn]["params"], options?: (MutateOptions<TFnToParams[TFn]["data"], TFnToParams[TFn]["error"], TFnToParams[TFn]["params"], TMetadata> & {
98
355
  meta?: TMetadata | undefined;
99
356
  }) | undefined) => void;
100
357
  reset: () => void;
101
- error: Error | TFnToParams[TFn]["error"] | null;
358
+ error: TMutationError<TFnToParams[TFn]["error"]>;
102
359
  };
103
- declare const useCallQueryBase: <TFnToParams extends FnToParamsBase, TData = unknown, TError = unknown, TParams = unknown, TSelect = TData, TMetadata = unknown>(promiseFunction: TPromiseFunction<TData, TParams, TMetadata>, functionName: keyof TFnToParams, params: TParams, service: (meta?: TMetadata) => string, options?: Omit<QueryOptions<TData, TError, TParams, TSelect>, "queryFn"> & {
360
+ /**
361
+ * Internal helper backing the hook returned by {@link buildQueryHook}. Wraps a ZMQ
362
+ * `promiseFunction` call for a single remote function name into a {@link useQuery} instance.
363
+ */
364
+ declare const useCallQueryBase: <TFnToParams extends FnToParamsBase, TData = unknown, TError = unknown, TParams = unknown, TSelect = TData, TMetadata = unknown, TStateless extends true | undefined = undefined>(promiseFunction: TPromiseFunction<TData, TParams, TMetadata>, functionName: keyof TFnToParams, params: TParams, service: (meta?: TMetadata) => string, options?: Omit<QueryOptions<TData, TError, TParams, TSelect, TStateless>, "queryFn"> & {
104
365
  meta?: TMetadata;
105
- }) => UseQueryResult<TSelect, TError, TParams, TSelect, undefined>;
106
- declare function buildQueryHook<TFnToParams extends FnToParamsBase, TMetadata = unknown>(promiseFunction: TPromiseFunction<unknown, unknown, unknown>, getTargetService: (meta?: TMetadata) => string): <TFn extends keyof TFnToParams, TSelect = TFnToParams[TFn]["data"]>(func: TFn, params: TFnToParams[TFn]["params"], options?: Parameters<typeof useCallQueryBase<TFnToParams, TFnToParams[TFn]["data"], TFnToParams[TFn]["error"], TFnToParams[TFn]["params"], TSelect, TMetadata>>[4] & {
366
+ }) => UseQueryResult<TSelect, TError, TParams, TSelect, TStateless>;
367
+ /**
368
+ * Builds a `useQuery`-like hook for calling remote ZMQ functions by name, with full type
369
+ * inference of `data`/`error`/`params` from the `TFnToParams` map.
370
+ *
371
+ * This is the recommended way to expose a typed query hook for a service: call this once with a
372
+ * bound {@link TPromiseFunction} (see {@link bindPromiseFunction}) and a function that resolves
373
+ * the target service name, then export the resulting hook for consumers.
374
+ *
375
+ * @typeParam TFnToParams - A map from remote function name to its {@link MutationInfo}
376
+ * (data/error/params types).
377
+ * @typeParam TMetadata - The type of the optional metadata forwarded to `getTargetService` and `promiseFunction`.
378
+ * @param promiseFunction - The transport function that performs the actual remote call.
379
+ * @param getTargetService - Resolves the target service name for a call, given its metadata.
380
+ * @returns A `useCallQueryBuilder` hook: call it with a function name (a key of `TFnToParams`),
381
+ * the params for that call, and the same options as {@link useQuery} (minus `queryFn`) to get a
382
+ * query scoped to that remote function.
383
+ * @example
384
+ * ```ts
385
+ * const useGetUser = buildQueryHook<MyFunctions>(
386
+ * bindPromiseFunction(proxyClient),
387
+ * () => "UserService"
388
+ * );
389
+ *
390
+ * const { data } = useGetUser("getUser", { id: userId });
391
+ * ```
392
+ */
393
+ declare function buildQueryHook<TFnToParams extends FnToParamsBase, TMetadata = unknown>(promiseFunction: TPromiseFunction<unknown, unknown, unknown>, getTargetService: (meta?: TMetadata) => string): <TFn extends keyof TFnToParams, TSelect = TFnToParams[TFn]["data"], TStateless extends true | undefined = undefined>(func: TFn, params: TFnToParams[TFn]["params"], options?: Parameters<typeof useCallQueryBase<TFnToParams, TFnToParams[TFn]["data"], TFnToParams[TFn]["error"], TFnToParams[TFn]["params"], TSelect, TMetadata, TStateless>>[4] & {
107
394
  meta?: TMetadata;
108
- }) => UseQueryResult<TSelect, TFnToParams[TFn]["error"], TFnToParams[TFn]["params"], TSelect, undefined>;
395
+ }) => UseQueryResult<TSelect, TFnToParams[TFn]["error"], TFnToParams[TFn]["params"], TSelect, TStateless>;
109
396
 
110
397
  /**
111
- * @fileoverview useSubscriptionCore
112
- * @name useSubscriptionCore.ts
113
- * @description useSubscriptionCore | This hook handle core subscription logic
114
- * and provides a way to subscribe and unsubscribe to a topic via any callback
398
+ * Core subscription logic: subscribe and unsubscribe to a topic via any
399
+ * callback-based transport. See {@link useSubscriptionCore}.
115
400
  */
401
+ /** The status of a {@link useSubscriptionCore} subscription, as exposed via {@link WithStatus.status}. */
116
402
  type SubscriptionState = "idle" | "subscribed" | "subscribing" | "error";
403
+ /** A function invoked with each message received on the subscription. */
117
404
  type MessageHandler<TMessage> = (message: TMessage) => void;
405
+ /**
406
+ * Handle passed to a {@link SubscriptionCoreOptions.subscriberFn} implementation so it can report
407
+ * subscription lifecycle events back into the hook.
408
+ */
118
409
  type Connection = {
410
+ /** Marks the subscription as `"subscribed"`. Call this once the subscription is confirmed active. */
119
411
  acknowledge: () => void;
120
412
  };
413
+ /**
414
+ * Configuration options for {@link useSubscriptionCore}.
415
+ *
416
+ * @typeParam TData - The data type exposed via `data`, after `select` (if provided).
417
+ * @typeParam TMessage - The raw message type passed to `subscriberFn`'s handler.
418
+ * @typeParam Stateless - When `true`, the hook does not keep the latest message in state.
419
+ */
121
420
  type SubscriptionCoreOptions<TData, TMessage = TData, Stateless extends true | undefined = undefined> = {
122
- /**
123
- * @description Function that will be called when the message is received.
124
- */
421
+ /** Function that will be called when the message is received. */
125
422
  onMessage?: (message: TMessage) => void;
126
- /**
127
- * @description Function that will be called when the subscription is created.
128
- */
423
+ /** Function that will be called when the subscription is created. */
129
424
  onSubscribed?: (message: TMessage) => void;
130
- /**
131
- * @description Function that will be called when the subscription is created.
132
- */
425
+ /** Function that will be called when the subscription errors. */
133
426
  onError?: (error: TMessage) => void;
134
427
  /**
135
- * @description Whether the subscription is enabled.
428
+ * Whether the subscription is enabled.
136
429
  * @default true
137
430
  */
138
431
  enabled?: boolean;
139
432
  /**
140
- * @description Function that will be called before the message is processed.
433
+ * Function that will be called before the message is processed.
141
434
  * Returning `true` will cause the message to not be set to state and call {@link onError} if provided.
142
435
  * Status will be set to `error`.
143
436
  */
144
437
  compareOrThrow?: (data: TMessage) => boolean;
145
- /**
146
- * @description Function that will be called to select the data from the message.
147
- */
438
+ /** Function that will be called to select the data from the message. */
148
439
  select?: (data: TMessage) => TData;
149
440
  /**
150
- * @description Initial state of the subscription.
441
+ * Initial state of the subscription.
151
442
  * @default undefined
152
443
  */
153
444
  initialState?: TData;
154
- /**
155
- * @description Function that will be called when the subscription is created.
156
- */
445
+ /** Function that will be called when the subscription is created. */
157
446
  subscriberFn: (handler: MessageHandler<TMessage>, connection: Connection) => () => void /** unsubscribe Fn */;
158
447
  /**
159
- * @description Whether the subscription is stateless. Data will not be
448
+ * Whether the subscription is stateless. Data will not be
160
449
  * stored by the hook internally.
161
450
  * @default false
162
451
  */
163
452
  stateless?: Stateless;
164
453
  /**
165
- * @description Custom equality function for comparing data.
454
+ * Custom equality function for comparing data.
166
455
  * @default shallowEqual
167
456
  */
168
457
  isEqual?: <T = TData>(a: T, b: T) => boolean;
169
458
  };
459
+ /** Adds the `status` field to {@link SubscriptionCoreReturnType}. */
170
460
  type WithStatus = {
171
461
  status: SubscriptionState;
172
462
  };
173
- type WithData<TData> = {
463
+ /** Adds the `data` field to {@link SubscriptionCoreReturnType}. */
464
+ type WithSubscriptionData<TData> = {
174
465
  data: TData;
175
466
  };
467
+ /**
468
+ * The value returned by {@link useSubscriptionCore}.
469
+ *
470
+ * @typeParam TData - The data type exposed via `data`.
471
+ * @typeParam Stateless - When `true`, `status` and `data` are omitted from the result.
472
+ */
176
473
  type SubscriptionCoreReturnType<TData, Stateless extends true | undefined> = {
474
+ /** Unsubscribes (if currently subscribed) and immediately subscribes again. */
177
475
  reSubscribe: () => void;
178
- } & (Stateless extends true ? {} : WithStatus & WithData<TData>);
476
+ } & (Stateless extends true ? {} : WithStatus & WithSubscriptionData<TData>);
179
477
  /**
180
- * @description `useSubscriptionCore` | This hook handle core subscription logic
181
- * and provides a way to subscribe and unsubscribe to a topic via any callback.
182
- * The hook expose a handler function. All the consumer code need to do is to
183
- * call this handler function with the message received from the topic or pass
184
- * it directly to the callback function that is passed to the subscriberFn.
478
+ * `useSubscriptionCore` handles core subscription logic and provides a way to
479
+ * subscribe and unsubscribe to a topic via any callback. The hook exposes a
480
+ * handler function - all the consumer code needs to do is call this handler
481
+ * function with the message received from the topic, or pass it directly to
482
+ * the callback function that is passed to `subscriberFn`.
185
483
  * - `status` - current status of the subscription
186
484
  * - `data` - the data after the select function is applied to the message
187
485
  * - `reSubscribe` - function that can be called to re-subscribe to the topic
188
486
  *
189
- * An example how this hook works can be found in {@link ./useSubscription.ts}
487
+ * See {@link useSubscription} for an example of how this hook is used.
190
488
  */
191
489
  declare function useSubscriptionCore<TData = unknown, TMessage = TData, Stateless extends true | undefined = undefined>(options: SubscriptionCoreOptions<TData, TMessage, Stateless>): SubscriptionCoreReturnType<TData, Stateless>;
192
490
 
491
+ /**
492
+ * Configuration options for {@link useSubscription}. Extends {@link SubscriptionCoreOptions}
493
+ * (minus `subscriberFn`, which `useSubscription` builds internally) with the service/topic pair
494
+ * that identifies what to subscribe to.
495
+ *
496
+ * @typeParam TData - The data type exposed via `data`, after `select` (if provided).
497
+ * @typeParam TMessage - The raw message type received from the topic.
498
+ * @typeParam Stateless - When `true`, the hook does not keep the latest message in state.
499
+ * @typeParam TMetadata - The type of the optional metadata forwarded to `subscriptionHandler`.
500
+ */
193
501
  type SubscriptionOptions<TData, TMessage = unknown, Stateless extends true | undefined = undefined, TMetadata extends {} = {}> = Omit<SubscriptionCoreOptions<TData, TMessage, Stateless>, "subscriberFn"> & {
502
+ /** The name of the service/machine that owns the topic being subscribed to. */
194
503
  service: string;
504
+ /** The name of the topic to subscribe to. */
195
505
  topic: string;
506
+ /** How many levels deep to mirror nested updates. Forwarded as-is to `subscriptionHandler`. */
196
507
  maxDownwardDepth?: number;
197
508
  } & {
509
+ /** Optional metadata forwarded to `subscriptionHandler` alongside the subscription request. */
198
510
  meta?: TMetadata;
199
511
  };
512
+ /**
513
+ * The shape of a low-level subscription transport function, e.g. one bound to a ZMQ proxy client
514
+ * via {@link bindClientSocketProxy}. Given subscription details, it starts the subscription and
515
+ * returns an unsubscribe function.
516
+ *
517
+ * @typeParam TMessage - The raw message type delivered to `callback`.
518
+ * @typeParam TMetadata - The type of the optional metadata passed through `opts.meta`.
519
+ * @param opts - The service/topic to subscribe to, the callback to invoke per message, and any
520
+ * transport-specific options.
521
+ * @returns A function that unsubscribes from the topic.
522
+ */
200
523
  type TSubscriptionHandlerFunction<TMessage, TMetadata extends {} = {}> = (opts: {
201
524
  service: string;
202
525
  name: string;
@@ -205,13 +528,87 @@ type TSubscriptionHandlerFunction<TMessage, TMetadata extends {} = {}> = (opts:
205
528
  } & {
206
529
  meta?: TMetadata;
207
530
  }) => () => void;
531
+ /**
532
+ * React hook that subscribes to a `service`/`topic` pair via a transport-specific
533
+ * `subscriptionHandler` (see {@link TSubscriptionHandlerFunction}), managing subscribe/unsubscribe
534
+ * across the component's lifecycle. Built on top of {@link useSubscriptionCore} — see that hook
535
+ * for the mechanics of status tracking, `select`, `compareOrThrow`, etc.
536
+ *
537
+ * @typeParam TData - The data type exposed via `data`, after `select` (if provided).
538
+ * @typeParam TMessage - The raw message type received from the topic.
539
+ * @typeParam Stateless - When `true`, the hook does not keep the latest message in state.
540
+ * @typeParam TMetadata - The type of the optional metadata forwarded to `subscriptionHandler`.
541
+ * @param subscriptionHandler - The transport function that performs the actual subscribe/unsubscribe.
542
+ * @param options - See {@link SubscriptionOptions}.
543
+ * @returns See {@link SubscriptionCoreReturnType}: `status`, `data` and `reSubscribe`
544
+ * (`data`/`status` are omitted when `Stateless` is `true`).
545
+ * @example
546
+ * ```tsx
547
+ * const { data, status } = useSubscription(bindClientSocketProxy(proxyClient), {
548
+ * service: "MyService",
549
+ * topic: "MyTopic",
550
+ * });
551
+ * ```
552
+ */
208
553
  declare function useSubscription<TData = unknown, TMessage = TData, Stateless extends true | undefined = undefined, TMetadata extends {} = {}>(subscriptionHandler: TSubscriptionHandlerFunction<TMessage, TMetadata>, options: SubscriptionOptions<TData, TMessage, Stateless, TMetadata>): SubscriptionCoreReturnType<TData, Stateless>;
554
+ /**
555
+ * Builds a `useSubscription`-like hook that is pre-bound to a specific transport
556
+ * (`subscriptionHandler`) and a way of resolving the target service/machine name, so calling code
557
+ * only needs to supply the `topic` (and, optionally, override the `machine`).
558
+ *
559
+ * This is the building block behind per-domain subscription hooks: a package can call this once
560
+ * with its own transport binder and machine-resolution logic, and export the resulting hook for
561
+ * consumers to use without having to know about services/transports at all.
562
+ *
563
+ * @typeParam TMetadata - The type of the optional metadata forwarded to `subscriptionHandler`.
564
+ * @param subscriptionHandler - The transport function that performs the actual subscribe/unsubscribe.
565
+ * @param targetMachine - Resolves the service name to subscribe on, given an optional `machine`
566
+ * override supplied by the caller of the built hook.
567
+ * @returns A `useSubscriptionBuilder` hook with the same options as {@link useSubscription} minus
568
+ * `service`, plus an optional `machine` override.
569
+ */
209
570
  declare function buildServiceSubscriptionHook<TMetadata extends {} = {}>(subscriptionHandler: TSubscriptionHandlerFunction<unknown, TMetadata>, targetMachine: (machine: string | undefined) => string): <TData, TMessage = TData, Stateless extends true | undefined = undefined>(options: Omit<SubscriptionOptions<TData, TMessage, Stateless, TMetadata>, "service"> & {
210
571
  machine?: string;
211
572
  }) => SubscriptionCoreReturnType<TData, Stateless>;
212
573
 
574
+ /**
575
+ * The parameters a {@link TSubscriptionHandlerFunction} receives, as consumed by
576
+ * {@link bindClientSocketProxy}.
577
+ * @typeParam TMetadata - The type of the optional metadata carried on `opts.meta`.
578
+ */
213
579
  type TProxySubscriptionHandlerParams<TMetadata extends {} = {}> = Parameters<Parameters<typeof buildServiceSubscriptionHook<TMetadata>>[0]>[0];
580
+ /**
581
+ * Adapts a {@link @pixotope/zmq-client!ZMQProxyWSClient}'s `mirror` method into a
582
+ * {@link TSubscriptionHandlerFunction}, so it can be passed to {@link useSubscription} or
583
+ * {@link buildServiceSubscriptionHook}.
584
+ *
585
+ * @param socketClientProxy - The ZMQ proxy WebSocket client to subscribe through.
586
+ * @returns A subscription handler function that mirrors the requested service/topic and
587
+ * unwraps each message's `.message` payload before invoking the caller's callback.
588
+ * @example
589
+ * ```ts
590
+ * const useMySubscription = buildServiceSubscriptionHook(
591
+ * bindClientSocketProxy(proxyClient),
592
+ * (machine) => machine ?? "DefaultMachine"
593
+ * );
594
+ * ```
595
+ */
214
596
  declare function bindClientSocketProxy(socketClientProxy: ZMQProxyWSClient): (args: TProxySubscriptionHandlerParams) => () => void;
597
+ /**
598
+ * Adapts a {@link @pixotope/zmq-client!ZMQProxyWSClient}'s `callAsync` method into a {@link TPromiseFunction}, so it
599
+ * can be passed to {@link buildMutationHook} or {@link buildQueryHook}.
600
+ *
601
+ * @param clientSocketProxy - The ZMQ proxy WebSocket client to call through.
602
+ * @returns A promise function that performs the remote call and resolves with the unwrapped
603
+ * `.message.Result` payload (rejecting if the call times out or fails).
604
+ * @example
605
+ * ```ts
606
+ * const useCreateUser = buildMutationHook<MyFunctions>(
607
+ * bindPromiseFunction(proxyClient),
608
+ * () => "UserService"
609
+ * );
610
+ * ```
611
+ */
215
612
  declare function bindPromiseFunction(clientSocketProxy: ZMQProxyWSClient): (args: Omit<_pixotope_zmq_client.ZMQClient.Call<unknown, {
216
613
  functionName: string;
217
614
  parameters: unknown;
@@ -220,4 +617,4 @@ declare function bindPromiseFunction(clientSocketProxy: ZMQProxyWSClient): (args
220
617
  meta?: unknown;
221
618
  }) => Promise<unknown>;
222
619
 
223
- export { ComparisonFailError, type Connection, type MessageHandler, type MutateOptions, type MutationFunction, type MutationInfo, type MutationOptions, type QueryOptions, type SubscriptionCoreOptions, type SubscriptionCoreReturnType, type SubscriptionOptions, type TPromiseFunction, type TProxySubscriptionHandlerParams, type TSubscriptionHandlerFunction, type UseQueryResult, bindClientSocketProxy, bindPromiseFunction, buildMutationHook, buildQueryHook, buildServiceSubscriptionHook, useMutation, useQuery, useSubscription, useSubscriptionCore };
620
+ export { ComparisonFailError, type Connection, type FnToParamsBase, type Functionize, type MessageHandler, type MutateOptions, type MutationFunction, type MutationInfo, type MutationOptions, type MutationStatus, type QueryOptions, type QueryStatus, type SubscriptionCoreOptions, type SubscriptionCoreReturnType, type SubscriptionOptions, type SubscriptionState, type TMutationError, type TPromiseFunction, type TProxySubscriptionHandlerParams, type TQueryError, type TQueryKey, type TSubscriptionHandlerFunction, type UseQueryResult, type WithQueryData, type WithStatus, type WithSubscriptionData, bindClientSocketProxy, bindPromiseFunction, buildMutationHook, buildQueryHook, buildServiceSubscriptionHook, useMutation, useQuery, useSubscription, useSubscriptionCore };