orpc-fn 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +146 -5
  2. package/dist/client.d.ts +29 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +49 -0
  5. package/dist/client.js.map +1 -1
  6. package/dist/create-fn.d.ts.map +1 -1
  7. package/dist/create-fn.js +2 -8
  8. package/dist/create-fn.js.map +1 -1
  9. package/dist/hono.d.ts +12 -1
  10. package/dist/hono.d.ts.map +1 -1
  11. package/dist/hono.js +15 -1
  12. package/dist/hono.js.map +1 -1
  13. package/dist/live/fn-live.d.ts +1 -6
  14. package/dist/live/fn-live.d.ts.map +1 -1
  15. package/dist/live/fn-live.js +2 -18
  16. package/dist/live/fn-live.js.map +1 -1
  17. package/dist/live/index.d.ts +3 -1
  18. package/dist/live/index.d.ts.map +1 -1
  19. package/dist/live/index.js +2 -0
  20. package/dist/live/index.js.map +1 -1
  21. package/dist/live/invalidation-stream.d.ts +52 -0
  22. package/dist/live/invalidation-stream.d.ts.map +1 -0
  23. package/dist/live/invalidation-stream.js +98 -0
  24. package/dist/live/invalidation-stream.js.map +1 -0
  25. package/dist/live/ioredis.d.ts +1 -0
  26. package/dist/live/ioredis.d.ts.map +1 -1
  27. package/dist/live/ioredis.js +1 -0
  28. package/dist/live/ioredis.js.map +1 -1
  29. package/dist/live/memory.d.ts +2 -1
  30. package/dist/live/memory.d.ts.map +1 -1
  31. package/dist/live/memory.js +6 -1
  32. package/dist/live/memory.js.map +1 -1
  33. package/dist/live/pub-sub.d.ts +5 -0
  34. package/dist/live/pub-sub.d.ts.map +1 -1
  35. package/dist/live/pub-sub.js +36 -15
  36. package/dist/live/pub-sub.js.map +1 -1
  37. package/dist/live/redis-bun.d.ts +3 -0
  38. package/dist/live/redis-bun.d.ts.map +1 -1
  39. package/dist/live/redis-bun.js +1 -0
  40. package/dist/live/redis-bun.js.map +1 -1
  41. package/dist/live/redis.d.ts +4 -1
  42. package/dist/live/redis.d.ts.map +1 -1
  43. package/dist/live/redis.js +14 -2
  44. package/dist/live/redis.js.map +1 -1
  45. package/dist/live/scoped-change-bus.d.ts +45 -0
  46. package/dist/live/scoped-change-bus.d.ts.map +1 -0
  47. package/dist/live/scoped-change-bus.js +38 -0
  48. package/dist/live/scoped-change-bus.js.map +1 -0
  49. package/dist/live/transport.d.ts +11 -0
  50. package/dist/live/transport.d.ts.map +1 -1
  51. package/dist/live/transport.js.map +1 -1
  52. package/dist/otel.d.ts +5 -0
  53. package/dist/otel.d.ts.map +1 -1
  54. package/dist/otel.js +7 -0
  55. package/dist/otel.js.map +1 -1
  56. package/dist/procedure-cli.d.ts +25 -0
  57. package/dist/procedure-cli.d.ts.map +1 -0
  58. package/dist/procedure-cli.js +67 -0
  59. package/dist/procedure-cli.js.map +1 -0
  60. package/dist/react.d.ts +116 -0
  61. package/dist/react.d.ts.map +1 -0
  62. package/dist/react.js +156 -0
  63. package/dist/react.js.map +1 -0
  64. package/dist/realtime.d.ts +114 -0
  65. package/dist/realtime.d.ts.map +1 -0
  66. package/dist/realtime.js +316 -0
  67. package/dist/realtime.js.map +1 -0
  68. package/dist/vue/testing.d.ts +67 -0
  69. package/dist/vue/testing.d.ts.map +1 -0
  70. package/dist/vue/testing.js +225 -0
  71. package/dist/vue/testing.js.map +1 -0
  72. package/dist/vue.d.ts +211 -0
  73. package/dist/vue.d.ts.map +1 -0
  74. package/dist/vue.js +312 -0
  75. package/dist/vue.js.map +1 -0
  76. package/package.json +51 -4
  77. package/src/client.ts +57 -0
  78. package/src/create-fn.ts +2 -7
  79. package/src/hono.ts +22 -2
  80. package/src/live/fn-live.ts +3 -22
  81. package/src/live/index.ts +12 -1
  82. package/src/live/invalidation-stream.ts +142 -0
  83. package/src/live/ioredis.ts +2 -0
  84. package/src/live/memory.ts +11 -2
  85. package/src/live/pub-sub.ts +48 -17
  86. package/src/live/redis-bun.ts +3 -0
  87. package/src/live/redis.ts +33 -6
  88. package/src/live/scoped-change-bus.ts +98 -0
  89. package/src/live/transport.ts +12 -0
  90. package/src/otel.ts +8 -0
  91. package/src/procedure-cli.ts +99 -0
  92. package/src/react.ts +355 -0
  93. package/src/realtime.ts +416 -0
  94. package/src/vue/testing.ts +296 -0
  95. package/src/vue.ts +783 -0
@@ -0,0 +1,116 @@
1
+ import { type QueryKey, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';
2
+ import { type InvalidationStreamOptions, type LiveConnectionStatus } from './realtime.js';
3
+ export type { InvalidationDomain, LiveConnectionStatus } from './realtime.js';
4
+ /** An oRPC client procedure fits: `client.order.watch`. */
5
+ export type SubscribeFn<TInput, TEvent> = (input: TInput, options: {
6
+ signal: AbortSignal;
7
+ }) => Promise<AsyncIterable<TEvent>>;
8
+ export type UseOrpcSubscriptionOptions<TInput, TEvent> = {
9
+ /** Run the stream (default: true). */
10
+ enabled?: boolean | undefined;
11
+ onEvent?: (event: TEvent, meta: {
12
+ connectionId: number;
13
+ input: TInput;
14
+ }) => void;
15
+ /** Every successful connect; `connectionId > 1` is a reconnect. */
16
+ onConnect?: (connectionId: number) => void;
17
+ onError?: ((error: Error) => void) | undefined;
18
+ onClose?: () => void;
19
+ /**
20
+ * Close the stream while the app is not focused (default: true). Focus is
21
+ * TanStack's `focusManager`: on React Native, wire it to `AppState` once.
22
+ */
23
+ pauseWhenUnfocused?: boolean | undefined;
24
+ };
25
+ /**
26
+ * An oRPC event iterator with backoff reconnects that closes while the app is
27
+ * backgrounded. A changed input (compared as JSON) reconnects with a fresh
28
+ * retry budget.
29
+ */
30
+ export declare function useOrpcSubscription<TInput, TEvent>(input: TInput, subscribe: SubscribeFn<TInput, TEvent>, options?: UseOrpcSubscriptionOptions<TInput, TEvent>): {
31
+ status: LiveConnectionStatus;
32
+ };
33
+ type ApplyEvent<TStreamEvent, TData> = (event: TStreamEvent, previous: TData | undefined) => TData | undefined;
34
+ type LiveQueryOptions<TInput, TRouteData, TStreamEvent, TData, TSubscriptionInput> = {
35
+ /** Run the query and its stream (default: true). */
36
+ enabled?: boolean | undefined;
37
+ /** Input for the stream when it differs from the query's. */
38
+ subscriptionInput?: TSubscriptionInput | undefined;
39
+ /**
40
+ * Convert the route output once at fetch time into a differently typed
41
+ * cache; `applyEvent` then reduces stream events into that cache.
42
+ */
43
+ select?: (data: TRouteData) => TData;
44
+ /** The raw route output of a seed, before `select` drops fields. */
45
+ onSeed?: (data: TRouteData, input: TInput) => void;
46
+ /**
47
+ * Fold a stream event into the cached data. Required when the stream sends
48
+ * something other than the cached type (an `fnLive` patch route, or a
49
+ * `select`ed cache). Return `undefined` to skip the write.
50
+ */
51
+ applyEvent?: ApplyEvent<TStreamEvent, NoInfer<TData>>;
52
+ onEvent?: (event: TStreamEvent, meta: {
53
+ connectionId: number;
54
+ }) => void;
55
+ onError?: ((error: Error) => void) | undefined;
56
+ /**
57
+ * Reconcile a fetched seed with what the stream already wrote. The HTTP
58
+ * request can resolve last, so a plain overwrite would drop events that
59
+ * arrived while it was in flight. Default: take the fetched value.
60
+ */
61
+ mergeSeed?: (fetched: NoInfer<TData>, cached: NoInfer<TData> | undefined) => NoInfer<TData>;
62
+ /** Show the previous key's data while a new key loads (default: true). */
63
+ keepPreviousData?: boolean;
64
+ /** Close the stream while the app is not focused (default: true). */
65
+ pauseWhenUnfocused?: boolean | undefined;
66
+ };
67
+ type LiveQueryOptionsFn<TInput, TData, TError> = (input: TInput) => UseQueryOptions<TData, TError, TData, QueryKey>;
68
+ type LiveQueryResult<TData, TError> = UseQueryResult<TData, TError> & {
69
+ liveStatus: LiveConnectionStatus;
70
+ };
71
+ /**
72
+ * The client half of `fnLive`: the HTTP query seeds the cache, and the live
73
+ * route's stream writes each snapshot into the same cache entry. Marked
74
+ * `meta.live`, so invalidation streams leave it alone.
75
+ *
76
+ * ```tsx
77
+ * const order = useLiveQuery({ id }, (input) => orpc.order.get.queryOptions({ input }), client.order.watch)
78
+ * ```
79
+ *
80
+ * One signature, not overloads: TypeScript fixes an untyped callback's
81
+ * parameters at the first overload it tries, which made valid calls fail.
82
+ */
83
+ export declare function useLiveQuery<TInput, TRouteData, TStreamEvent, TData = TRouteData, TError = Error, TSubscriptionInput = TInput>(input: TInput, queryOptionsFn: LiveQueryOptionsFn<TInput, TRouteData, TError>, subscribe: SubscribeFn<NoInfer<TSubscriptionInput>, TStreamEvent>, ...options: [TStreamEvent] extends [TData] ? [
84
+ options?: LiveQueryOptions<TInput, TRouteData, TStreamEvent, TData, TSubscriptionInput>
85
+ ] : [
86
+ options: LiveQueryOptions<TInput, TRouteData, TStreamEvent, TData, TSubscriptionInput> & {
87
+ applyEvent: ApplyEvent<TStreamEvent, NoInfer<TData>>;
88
+ }
89
+ ]): LiveQueryResult<TData, TError>;
90
+ /**
91
+ * One app-wide stream of `{ domain }` change events that keeps list and count
92
+ * queries fresh: each event invalidates its domain's query keys (debounced),
93
+ * and a reconnect that proves healthy invalidates every domain to cover
94
+ * events lost while it was down. Mount once, in the signed-in shell.
95
+ *
96
+ * ```ts
97
+ * useInvalidationStream({}, client.realtime.subscribeChanges, {
98
+ * enabled: signedIn,
99
+ * domains: { order: { debounceMs: 100, queryKeys: [orpc.order.key()] } }
100
+ * })
101
+ * ```
102
+ */
103
+ export declare function useInvalidationStream<TInput, TEvent extends {
104
+ domain: string;
105
+ }>(input: TInput, subscribe: SubscribeFn<TInput, TEvent>, options: InvalidationStreamOptions<TEvent> & Pick<UseOrpcSubscriptionOptions<TInput, TEvent>, 'enabled' | 'pauseWhenUnfocused'>): {
106
+ status: LiveConnectionStatus;
107
+ };
108
+ /**
109
+ * Clear the query cache when the signed-in owner of the cached data changes
110
+ * (another user, another organization), so the next one never sees it.
111
+ * `null` means signed out: signing in starts from the cache sign-out emptied.
112
+ * Pass the same owner as the persister's `buster` so a saved cache from
113
+ * someone else is discarded on the next launch too.
114
+ */
115
+ export declare function useQueryCacheOwner(owner: string | null): void;
116
+ //# sourceMappingURL=react.d.ts.map
@@ -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,EACtC,OAAO,EAAE,yBAAyB,CAAC,MAAM,CAAC,GACzC,IAAI,CACH,0BAA0B,CAAC,MAAM,EAAE,MAAM,CAAC,EAC1C,SAAS,GAAG,oBAAoB,CAChC,GACA;IAAE,MAAM,EAAE,oBAAoB,CAAA;CAAE,CAqBlC;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAQ7D"}
package/dist/react.js ADDED
@@ -0,0 +1,156 @@
1
+ import { focusManager, hashKey, keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query';
2
+ import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
3
+ import { createInvalidationCoordinator, createStreamScope, createSubscriptionRunner, seedQueryFn } from './realtime.js';
4
+ const subscribeFocus = (listener) => focusManager.subscribe(listener);
5
+ const getFocus = () => focusManager.isFocused();
6
+ /** Whether the app is focused, from TanStack's `focusManager`. */
7
+ function useIsFocused() {
8
+ return useSyncExternalStore(subscribeFocus, getFocus, getFocus);
9
+ }
10
+ /**
11
+ * An oRPC event iterator with backoff reconnects that closes while the app is
12
+ * backgrounded. A changed input (compared as JSON) reconnects with a fresh
13
+ * retry budget.
14
+ */
15
+ export function useOrpcSubscription(input, subscribe, options = {}) {
16
+ const { enabled = true, pauseWhenUnfocused = true } = options;
17
+ const focused = useIsFocused();
18
+ const shouldRun = enabled && (!pauseWhenUnfocused || focused);
19
+ const [status, setStatus] = useState('idle');
20
+ const latest = useRef({ input, subscribe, options, shouldRun });
21
+ latest.current = { input, subscribe, options, shouldRun };
22
+ const runnerRef = useRef(null);
23
+ if (!runnerRef.current) {
24
+ let openedInput = input;
25
+ runnerRef.current = createSubscriptionRunner({
26
+ open: (signal) => {
27
+ openedInput = latest.current.input;
28
+ return latest.current.subscribe(openedInput, { signal });
29
+ },
30
+ canConnect: () => latest.current.shouldRun,
31
+ shouldReconnect: () => latest.current.shouldRun,
32
+ onStatus: setStatus,
33
+ onEvent: (event, connectionId) => latest.current.options.onEvent?.(event, {
34
+ connectionId,
35
+ input: openedInput
36
+ }),
37
+ onConnect: (id) => latest.current.options.onConnect?.(id),
38
+ onError: (error) => latest.current.options.onError?.(error),
39
+ onClose: () => latest.current.options.onClose?.()
40
+ });
41
+ }
42
+ const runner = runnerRef.current;
43
+ const serializedInput = JSON.stringify(input);
44
+ // biome-ignore lint/correctness/useExhaustiveDependencies: a changed input resubscribes
45
+ useEffect(() => {
46
+ if (!shouldRun)
47
+ return;
48
+ void runner.start();
49
+ return () => void runner.disconnect();
50
+ }, [runner, shouldRun, serializedInput]);
51
+ return { status };
52
+ }
53
+ export function useLiveQuery(input, queryOptionsFn, subscribe, options = {}) {
54
+ const queryClient = useQueryClient();
55
+ const focused = useIsFocused();
56
+ const [scope] = useState(createStreamScope);
57
+ // oRPC query options are plain objects; `queryFn` is read through one shape.
58
+ const raw = queryOptionsFn(input);
59
+ const keyHash = hashKey(raw.queryKey);
60
+ const latest = useRef({ raw, keyHash, options });
61
+ latest.current = { raw, keyHash, options };
62
+ const { status } = useOrpcSubscription((options.subscriptionInput === undefined
63
+ ? input
64
+ : options.subscriptionInput), subscribe, {
65
+ enabled: options.enabled,
66
+ pauseWhenUnfocused: options.pauseWhenUnfocused,
67
+ onError: options.onError,
68
+ onConnect: (connectionId) => scope.open(connectionId, latest.current.keyHash),
69
+ onEvent: (event, { connectionId }) => {
70
+ const current = latest.current;
71
+ // The consumer callback must not see an event for a scope no longer shown.
72
+ if (!scope.owns(connectionId, current.keyHash))
73
+ return;
74
+ // Without `applyEvent` the stream event is the cache type (the first overload).
75
+ const applyEvent = current.options.applyEvent ??
76
+ ((streamEvent) => streamEvent);
77
+ const key = current.raw.queryKey;
78
+ const next = applyEvent(event, queryClient.getQueryData(key));
79
+ if (next !== undefined)
80
+ queryClient.setQueryData(key, next);
81
+ current.options.onEvent?.(event, { connectionId });
82
+ }
83
+ });
84
+ const wrapsSeed = options.select || options.mergeSeed;
85
+ const queryFn = raw.queryFn && wrapsSeed
86
+ ? seedQueryFn(raw.queryFn, {
87
+ input,
88
+ readCache: () => queryClient.getQueryData(raw.queryKey),
89
+ select: options.select,
90
+ onSeed: options.onSeed,
91
+ mergeSeed: options.mergeSeed
92
+ })
93
+ : raw.queryFn;
94
+ const runs = options.enabled !== false && focused;
95
+ const query = useQuery({
96
+ ...raw,
97
+ ...(queryFn ? { queryFn } : {}),
98
+ enabled: runs ? (raw.enabled ?? true) : false,
99
+ ...(options.keepPreviousData === false
100
+ ? {}
101
+ : { placeholderData: keepPreviousData }),
102
+ staleTime: Number.POSITIVE_INFINITY,
103
+ meta: { ...raw.meta, live: true }
104
+ });
105
+ return Object.assign(query, { liveStatus: status });
106
+ }
107
+ /**
108
+ * One app-wide stream of `{ domain }` change events that keeps list and count
109
+ * queries fresh: each event invalidates its domain's query keys (debounced),
110
+ * and a reconnect that proves healthy invalidates every domain to cover
111
+ * events lost while it was down. Mount once, in the signed-in shell.
112
+ *
113
+ * ```ts
114
+ * useInvalidationStream({}, client.realtime.subscribeChanges, {
115
+ * enabled: signedIn,
116
+ * domains: { order: { debounceMs: 100, queryKeys: [orpc.order.key()] } }
117
+ * })
118
+ * ```
119
+ */
120
+ export function useInvalidationStream(input, subscribe, options) {
121
+ const queryClient = useQueryClient();
122
+ const latestOptions = useRef(options);
123
+ latestOptions.current = options;
124
+ // `domains`, `refetchType` and `logger` are read on mount; `onEvent` stays current.
125
+ const [coordinator] = useState(() => createInvalidationCoordinator(queryClient, {
126
+ ...options,
127
+ onEvent: (event) => latestOptions.current.onEvent?.(event)
128
+ }));
129
+ useEffect(() => coordinator.dispose, [coordinator]);
130
+ return useOrpcSubscription(input, subscribe, {
131
+ enabled: options.enabled,
132
+ pauseWhenUnfocused: options.pauseWhenUnfocused,
133
+ onEvent: coordinator.event,
134
+ onConnect: coordinator.connect,
135
+ onError: coordinator.lost,
136
+ onClose: coordinator.lost
137
+ });
138
+ }
139
+ /**
140
+ * Clear the query cache when the signed-in owner of the cached data changes
141
+ * (another user, another organization), so the next one never sees it.
142
+ * `null` means signed out: signing in starts from the cache sign-out emptied.
143
+ * Pass the same owner as the persister's `buster` so a saved cache from
144
+ * someone else is discarded on the next launch too.
145
+ */
146
+ export function useQueryCacheOwner(owner) {
147
+ const queryClient = useQueryClient();
148
+ const previous = useRef(owner);
149
+ useEffect(() => {
150
+ const before = previous.current;
151
+ previous.current = owner;
152
+ if (owner !== before && before !== null)
153
+ queryClient.clear();
154
+ }, [owner, queryClient]);
155
+ }
156
+ //# sourceMappingURL=react.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.js","sourceRoot":"","sources":["../src/react.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,YAAY,EACZ,OAAO,EACP,gBAAgB,EAIhB,QAAQ,EACR,cAAc,EACd,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAA;AACzE,OAAO,EACN,6BAA6B,EAC7B,iBAAiB,EACjB,wBAAwB,EAIxB,WAAW,EACX,MAAM,eAAe,CAAA;AA4BtB,MAAM,cAAc,GAAG,CAAC,QAAoB,EAAE,EAAE,CAC/C,YAAY,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAA;AACjC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,CAAA;AAE/C,kEAAkE;AAClE,SAAS,YAAY;IACpB,OAAO,oBAAoB,CAAC,cAAc,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAA;AAChE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAClC,KAAa,EACb,SAAsC,EACtC,OAAO,GAA+C,EAAE;IAExD,MAAM,EAAE,OAAO,GAAG,IAAI,EAAE,kBAAkB,GAAG,IAAI,EAAE,GAAG,OAAO,CAAA;IAC7D,MAAM,OAAO,GAAG,YAAY,EAAE,CAAA;IAC9B,MAAM,SAAS,GAAG,OAAO,I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,GAAG,EAAE,CACnC,6BAA6B,CAAS,WAAW,EAAE;QAClD,GAAG,OAAO;QACV,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,aAAa,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC;KAC1D,CAAC,CACF,CAAA;IACD,SAAS,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC,WAAW,CAAC,CAAC,CAAA;IAEnD,OAAO,mBAAmB,CAAiB,KAAK,EAAE,SAAS,EAAE;QAC5D,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,kBAAkB,EAAE,OAAO,CAAC,kBAAkB;QAC9C,OAAO,EAAE,WAAW,CAAC,KAAK;QAC1B,SAAS,EAAE,WAAW,CAAC,OAAO;QAC9B,OAAO,EAAE,WAAW,CAAC,IAAI;QACzB,OAAO,EAAE,WAAW,CAAC,IAAI;KACzB,CAAC,CAAA;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAoB;IACtD,MAAM,WAAW,GAAG,cAAc,EAAE,CAAA;IACpC,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA;IAC9B,SAAS,CAAC,GAAG,EAAE;QACd,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAA;QAC/B,QAAQ,CAAC,OAAO,GAAG,KAAK,CAAA;QACxB,IAAI,KAAK,KAAK,MAAM,IAAI,MAAM,KAAK,IAAI;YAAE,WAAW,CAAC,KAAK,EAAE,CAAA;IAC7D,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC,CAAA;AACzB,CAAC","sourcesContent":["import {\n\tfocusManager,\n\thashKey,\n\tkeepPreviousData,\n\ttype QueryKey,\n\ttype UseQueryOptions,\n\ttype UseQueryResult,\n\tuseQuery,\n\tuseQueryClient\n} from '@tanstack/react-query'\nimport { useEffect, useRef, useState, useSyncExternalStore } from 'react'\nimport {\n\tcreateInvalidationCoordinator,\n\tcreateStreamScope,\n\tcreateSubscriptionRunner,\n\ttype InvalidationStreamOptions,\n\ttype LiveConnectionStatus,\n\ttype SubscriptionRunner,\n\tseedQueryFn\n} from './realtime.js'\n\nexport type { InvalidationDomain, LiveConnectionStatus } from './realtime.js'\n\n/** An oRPC client procedure fits: `client.order.watch`. */\nexport type SubscribeFn<TInput, TEvent> = (\n\tinput: TInput,\n\toptions: { signal: AbortSignal }\n) => Promise<AsyncIterable<TEvent>>\n\nexport type UseOrpcSubscriptionOptions<TInput, TEvent> = {\n\t/** Run the stream (default: true). */\n\tenabled?: boolean | undefined\n\tonEvent?: (\n\t\tevent: TEvent,\n\t\tmeta: { connectionId: number; input: TInput }\n\t) => void\n\t/** Every successful connect; `connectionId > 1` is a reconnect. */\n\tonConnect?: (connectionId: number) => void\n\tonError?: ((error: Error) => void) | undefined\n\tonClose?: () => void\n\t/**\n\t * Close the stream while the app is not focused (default: true). Focus is\n\t * TanStack's `focusManager`: on React Native, wire it to `AppState` once.\n\t */\n\tpauseWhenUnfocused?: boolean | undefined\n}\n\nconst subscribeFocus = (listener: () => void) =>\n\tfocusManager.subscribe(listener)\nconst getFocus = () => focusManager.isFocused()\n\n/** Whether the app is focused, from TanStack's `focusManager`. */\nfunction useIsFocused(): boolean {\n\treturn useSyncExternalStore(subscribeFocus, getFocus, getFocus)\n}\n\n/**\n * An oRPC event iterator with backoff reconnects that closes while the app is\n * backgrounded. A changed input (compared as JSON) reconnects with a fresh\n * retry budget.\n */\nexport function useOrpcSubscription<TInput, TEvent>(\n\tinput: TInput,\n\tsubscribe: SubscribeFn<TInput, TEvent>,\n\toptions: UseOrpcSubscriptionOptions<TInput, TEvent> = {}\n): { status: LiveConnectionStatus } {\n\tconst { enabled = true, pauseWhenUnfocused = true } = options\n\tconst focused = useIsFocused()\n\tconst shouldRun = enabled && (!pauseWhenUnfocused || focused)\n\tconst [status, setStatus] = useState<LiveConnectionStatus>('idle')\n\n\tconst latest = useRef({ input, subscribe, options, shouldRun })\n\tlatest.current = { input, subscribe, options, shouldRun }\n\n\tconst runnerRef = useRef<SubscriptionRunner | null>(null)\n\tif (!runnerRef.current) {\n\t\tlet openedInput = input\n\t\trunnerRef.current = createSubscriptionRunner<TEvent>({\n\t\t\topen: (signal) => {\n\t\t\t\topenedInput = latest.current.input\n\t\t\t\treturn latest.current.subscribe(openedInput, { signal })\n\t\t\t},\n\t\t\tcanConnect: () => latest.current.shouldRun,\n\t\t\tshouldReconnect: () => latest.current.shouldRun,\n\t\t\tonStatus: setStatus,\n\t\t\tonEvent: (event, connectionId) =>\n\t\t\t\tlatest.current.options.onEvent?.(event, {\n\t\t\t\t\tconnectionId,\n\t\t\t\t\tinput: openedInput\n\t\t\t\t}),\n\t\t\tonConnect: (id) => latest.current.options.onConnect?.(id),\n\t\t\tonError: (error) => latest.current.options.onError?.(error),\n\t\t\tonClose: () => latest.current.options.onClose?.()\n\t\t})\n\t}\n\tconst runner = runnerRef.current\n\tconst serializedInput = JSON.stringify(input)\n\n\t// biome-ignore lint/correctness/useExhaustiveDependencies: a changed input resubscribes\n\tuseEffect(() => {\n\t\tif (!shouldRun) return\n\t\tvoid runner.start()\n\t\treturn () => void runner.disconnect()\n\t}, [runner, shouldRun, serializedInput])\n\n\treturn { status }\n}\n\ntype ApplyEvent<TStreamEvent, TData> = (\n\tevent: TStreamEvent,\n\tprevious: TData | undefined\n) => TData | undefined\n\ntype LiveQueryOptions<\n\tTInput,\n\tTRouteData,\n\tTStreamEvent,\n\tTData,\n\tTSubscriptionInput\n> = {\n\t/** Run the query and its stream (default: true). */\n\tenabled?: boolean | undefined\n\t/** Input for the stream when it differs from the query's. */\n\tsubscriptionInput?: TSubscriptionInput | undefined\n\t/**\n\t * Convert the route output once at fetch time into a differently typed\n\t * cache; `applyEvent` then reduces stream events into that cache.\n\t */\n\tselect?: (data: TRouteData) => TData\n\t/** The raw route output of a seed, before `select` drops fields. */\n\tonSeed?: (data: TRouteData, input: TInput) => void\n\t/**\n\t * Fold a stream event into the cached data. Required when the stream sends\n\t * something other than the cached type (an `fnLive` patch route, or a\n\t * `select`ed cache). Return `undefined` to skip the write.\n\t */\n\tapplyEvent?: ApplyEvent<TStreamEvent, NoInfer<TData>>\n\tonEvent?: (event: TStreamEvent, meta: { connectionId: number }) => void\n\tonError?: ((error: Error) => void) | undefined\n\t/**\n\t * Reconcile a fetched seed with what the stream already wrote. The HTTP\n\t * request can resolve last, so a plain overwrite would drop events that\n\t * arrived while it was in flight. Default: take the fetched value.\n\t */\n\tmergeSeed?: (\n\t\tfetched: NoInfer<TData>,\n\t\tcached: NoInfer<TData> | undefined\n\t) => NoInfer<TData>\n\t/** Show the previous key's data while a new key loads (default: true). */\n\tkeepPreviousData?: boolean\n\t/** Close the stream while the app is not focused (default: true). */\n\tpauseWhenUnfocused?: boolean | undefined\n}\n\ntype LiveQueryOptionsFn<TInput, TData, TError> = (\n\tinput: TInput\n) => UseQueryOptions<TData, TError, TData, QueryKey>\n\ntype LiveQueryResult<TData, TError> = UseQueryResult<TData, TError> & {\n\tliveStatus: LiveConnectionStatus\n}\n\n/**\n * The client half of `fnLive`: the HTTP query seeds the cache, and the live\n * route's stream writes each snapshot into the same cache entry. Marked\n * `meta.live`, so invalidation streams leave it alone.\n *\n * ```tsx\n * const order = useLiveQuery({ id }, (input) => orpc.order.get.queryOptions({ input }), client.order.watch)\n * ```\n *\n * One signature, not overloads: TypeScript fixes an untyped callback's\n * parameters at the first overload it tries, which made valid calls fail.\n */\nexport function useLiveQuery<\n\tTInput,\n\tTRouteData,\n\tTStreamEvent,\n\tTData = TRouteData,\n\tTError = Error,\n\tTSubscriptionInput = TInput\n>(\n\tinput: TInput,\n\tqueryOptionsFn: LiveQueryOptionsFn<TInput, TRouteData, TError>,\n\tsubscribe: SubscribeFn<NoInfer<TSubscriptionInput>, TStreamEvent>,\n\t...options: [TStreamEvent] extends [TData]\n\t\t? [\n\t\t\t\toptions?: LiveQueryOptions<\n\t\t\t\t\tTInput,\n\t\t\t\t\tTRouteData,\n\t\t\t\t\tTStreamEvent,\n\t\t\t\t\tTData,\n\t\t\t\t\tTSubscriptionInput\n\t\t\t\t>\n\t\t\t]\n\t\t: [\n\t\t\t\toptions: LiveQueryOptions<\n\t\t\t\t\tTInput,\n\t\t\t\t\tTRouteData,\n\t\t\t\t\tTStreamEvent,\n\t\t\t\t\tTData,\n\t\t\t\t\tTSubscriptionInput\n\t\t\t\t> & { applyEvent: ApplyEvent<TStreamEvent, NoInfer<TData>> }\n\t\t\t]\n): LiveQueryResult<TData, TError>\nexport function useLiveQuery<\n\tTInput,\n\tTRouteData,\n\tTStreamEvent,\n\tTData,\n\tTError,\n\tTSubscriptionInput\n>(\n\tinput: TInput,\n\tqueryOptionsFn: LiveQueryOptionsFn<TInput, TRouteData, TError>,\n\tsubscribe: SubscribeFn<TSubscriptionInput, TStreamEvent>,\n\toptions: LiveQueryOptions<\n\t\tTInput,\n\t\tTRouteData,\n\t\tTStreamEvent,\n\t\tTData,\n\t\tTSubscriptionInput\n\t> = {}\n): LiveQueryResult<TData, TError> {\n\tconst queryClient = useQueryClient()\n\tconst focused = useIsFocused()\n\tconst [scope] = useState(createStreamScope)\n\n\t// oRPC query options are plain objects; `queryFn` is read through one shape.\n\tconst raw = queryOptionsFn(input) as unknown as {\n\t\tqueryKey: QueryKey\n\t\tqueryFn?: (context: unknown) => Promise<TRouteData>\n\t\tenabled?: UseQueryOptions['enabled']\n\t\tmeta?: Record<string, unknown>\n\t} & Record<string, unknown>\n\tconst keyHash = hashKey(raw.queryKey)\n\tconst latest = useRef({ raw, keyHash, options })\n\tlatest.current = { raw, keyHash, options }\n\n\tconst { status } = useOrpcSubscription(\n\t\t(options.subscriptionInput === undefined\n\t\t\t? input\n\t\t\t: options.subscriptionInput) as TSubscriptionInput,\n\t\tsubscribe,\n\t\t{\n\t\t\tenabled: options.enabled,\n\t\t\tpauseWhenUnfocused: options.pauseWhenUnfocused,\n\t\t\tonError: options.onError,\n\t\t\tonConnect: (connectionId) =>\n\t\t\t\tscope.open(connectionId, latest.current.keyHash),\n\t\t\tonEvent: (event, { connectionId }) => {\n\t\t\t\tconst current = latest.current\n\t\t\t\t// The consumer callback must not see an event for a scope no longer shown.\n\t\t\t\tif (!scope.owns(connectionId, current.keyHash)) return\n\t\t\t\t// Without `applyEvent` the stream event is the cache type (the first overload).\n\t\t\t\tconst applyEvent =\n\t\t\t\t\tcurrent.options.applyEvent ??\n\t\t\t\t\t((streamEvent: TStreamEvent) => streamEvent as unknown as TData)\n\t\t\t\tconst key = current.raw.queryKey\n\t\t\t\tconst next = applyEvent(event, queryClient.getQueryData<TData>(key))\n\t\t\t\tif (next !== undefined) queryClient.setQueryData(key, next)\n\t\t\t\tcurrent.options.onEvent?.(event, { connectionId })\n\t\t\t}\n\t\t}\n\t)\n\n\tconst wrapsSeed = options.select || options.mergeSeed\n\tconst queryFn =\n\t\traw.queryFn && wrapsSeed\n\t\t\t? seedQueryFn(raw.queryFn, {\n\t\t\t\t\tinput,\n\t\t\t\t\treadCache: () => queryClient.getQueryData<TData>(raw.queryKey),\n\t\t\t\t\tselect: options.select,\n\t\t\t\t\tonSeed: options.onSeed,\n\t\t\t\t\tmergeSeed: options.mergeSeed\n\t\t\t\t})\n\t\t\t: raw.queryFn\n\tconst runs = options.enabled !== false && focused\n\tconst query = useQuery({\n\t\t...raw,\n\t\t...(queryFn ? { queryFn } : {}),\n\t\tenabled: runs ? (raw.enabled ?? true) : false,\n\t\t...(options.keepPreviousData === false\n\t\t\t? {}\n\t\t\t: { placeholderData: keepPreviousData }),\n\t\tstaleTime: Number.POSITIVE_INFINITY,\n\t\tmeta: { ...raw.meta, live: true }\n\t} as UseQueryOptions<TData, TError, TData, QueryKey>)\n\n\treturn Object.assign(query, { liveStatus: status })\n}\n\n/**\n * One app-wide stream of `{ domain }` change events that keeps list and count\n * queries fresh: each event invalidates its domain's query keys (debounced),\n * and a reconnect that proves healthy invalidates every domain to cover\n * events lost while it was down. Mount once, in the signed-in shell.\n *\n * ```ts\n * useInvalidationStream({}, client.realtime.subscribeChanges, {\n * enabled: signedIn,\n * domains: { order: { debounceMs: 100, queryKeys: [orpc.order.key()] } }\n * })\n * ```\n */\nexport function useInvalidationStream<\n\tTInput,\n\tTEvent extends { domain: string }\n>(\n\tinput: TInput,\n\tsubscribe: SubscribeFn<TInput, TEvent>,\n\toptions: InvalidationStreamOptions<TEvent> &\n\t\tPick<\n\t\t\tUseOrpcSubscriptionOptions<TInput, TEvent>,\n\t\t\t'enabled' | 'pauseWhenUnfocused'\n\t\t>\n): { status: LiveConnectionStatus } {\n\tconst queryClient = useQueryClient()\n\tconst latestOptions = useRef(options)\n\tlatestOptions.current = options\n\t// `domains`, `refetchType` and `logger` are read on mount; `onEvent` stays current.\n\tconst [coordinator] = useState(() =>\n\t\tcreateInvalidationCoordinator<TEvent>(queryClient, {\n\t\t\t...options,\n\t\t\tonEvent: (event) => latestOptions.current.onEvent?.(event)\n\t\t})\n\t)\n\tuseEffect(() => coordinator.dispose, [coordinator])\n\n\treturn useOrpcSubscription<TInput, TEvent>(input, subscribe, {\n\t\tenabled: options.enabled,\n\t\tpauseWhenUnfocused: options.pauseWhenUnfocused,\n\t\tonEvent: coordinator.event,\n\t\tonConnect: coordinator.connect,\n\t\tonError: coordinator.lost,\n\t\tonClose: coordinator.lost\n\t})\n}\n\n/**\n * Clear the query cache when the signed-in owner of the cached data changes\n * (another user, another organization), so the next one never sees it.\n * `null` means signed out: signing in starts from the cache sign-out emptied.\n * Pass the same owner as the persister's `buster` so a saved cache from\n * someone else is discarded on the next launch too.\n */\nexport function useQueryCacheOwner(owner: string | null): void {\n\tconst queryClient = useQueryClient()\n\tconst previous = useRef(owner)\n\tuseEffect(() => {\n\t\tconst before = previous.current\n\t\tprevious.current = owner\n\t\tif (owner !== before && before !== null) queryClient.clear()\n\t}, [owner, queryClient])\n}\n"]}
@@ -0,0 +1,114 @@
1
+ import type { FnLogger } from './logger.js';
2
+ export type LiveConnectionStatus = 'idle' | 'connecting' | 'connected' | 'error' | 'closed';
3
+ /**
4
+ * Backoff for attempt N (1-based): exponential from 1s capped at 15s, plus
5
+ * 0-25% jitter so a fleet of clients doesn't thundering-herd a recovering
6
+ * server. The delay is capped, never the attempts: a dead network keeps
7
+ * retrying at the ceiling instead of killing the stream for good.
8
+ */
9
+ export declare function nextReconnectDelayMs(errorCount: number, random?: () => number): number;
10
+ type SubscriptionRunnerOptions<TEvent> = {
11
+ open: (signal: AbortSignal) => Promise<AsyncIterable<TEvent>>;
12
+ onEvent: (event: TEvent, connectionId: number) => void;
13
+ onStatus: (status: LiveConnectionStatus) => void;
14
+ onConnect?: ((connectionId: number) => void) | undefined;
15
+ onError?: ((error: Error) => void) | undefined;
16
+ onClose?: (() => void) | undefined;
17
+ /** May a stream run at all right now (e.g. the app is in the foreground)? */
18
+ canConnect: () => boolean;
19
+ /** Reconnect with backoff after an unexpected end? Checked when scheduling and firing. */
20
+ shouldReconnect: () => boolean;
21
+ };
22
+ export type SubscriptionRunner = ReturnType<typeof createSubscriptionRunner>;
23
+ /**
24
+ * One oRPC event-iterator stream with generation-guarded connects, abortable
25
+ * teardown and backoff reconnects. Every connect claims a new connection id;
26
+ * a superseded attempt closes its own iterator and never reports events.
27
+ */
28
+ export declare function createSubscriptionRunner<TEvent>(options: SubscriptionRunnerOptions<TEvent>): {
29
+ connect: () => Promise<void>;
30
+ disconnect: () => Promise<void>;
31
+ /** Connect with a fresh retry budget (input change, foreground, re-enable). */
32
+ start(): Promise<void>;
33
+ /** Connected, connecting, or waiting to reconnect. */
34
+ isLive: () => boolean;
35
+ getStatus: () => LiveConnectionStatus;
36
+ dispose(): Promise<void>;
37
+ };
38
+ type QueryKeyLike = readonly unknown[];
39
+ /** The part of a TanStack `QueryClient` the coordinator uses. */
40
+ type InvalidatingQueryClient = {
41
+ invalidateQueries(filters: {
42
+ queryKey: QueryKeyLike;
43
+ refetchType?: 'active' | 'inactive' | 'all' | 'none';
44
+ predicate?: (query: {
45
+ meta?: Record<string, unknown> | undefined;
46
+ }) => boolean;
47
+ }): Promise<unknown>;
48
+ };
49
+ export type InvalidationDomain = {
50
+ /**
51
+ * Batch a burst of events into one invalidation (ms). The window runs from
52
+ * the first event, so a steady stream cannot postpone the refresh forever.
53
+ */
54
+ debounceMs?: number;
55
+ queryKeys: readonly QueryKeyLike[];
56
+ };
57
+ export type InvalidationStreamOptions<TEvent extends {
58
+ domain: string;
59
+ }> = {
60
+ /** Query keys to invalidate per event `domain`. Unmapped domains are ignored. */
61
+ domains: {
62
+ [K in TEvent['domain']]?: InvalidationDomain;
63
+ };
64
+ /**
65
+ * Passed to `invalidateQueries`. Default: TanStack's `'active'`, which marks
66
+ * inactive queries stale so they refetch on their next use. `'all'` also
67
+ * refetches every cached query of the domain now, on each event.
68
+ */
69
+ refetchType?: 'active' | 'inactive' | 'all' | 'none';
70
+ /** Every event, after its domain is invalidated (alerts, chimes). */
71
+ onEvent?: (event: TEvent) => void;
72
+ /** Receives one `invalidation_stream.disconnected` warning per minute at most. */
73
+ logger?: Pick<FnLogger, 'warn'>;
74
+ };
75
+ /**
76
+ * Turns a stream of `{ domain }` change events into debounced
77
+ * `invalidateQueries` calls. Live queries (`meta.live`) are skipped: their own
78
+ * stream keeps them current. Events published while the stream was down are
79
+ * lost, so a reconnect that proves healthy invalidates every mapped domain.
80
+ */
81
+ export declare function createInvalidationCoordinator<TEvent extends {
82
+ domain: string;
83
+ }>(queryClient: InvalidatingQueryClient, options: InvalidationStreamOptions<TEvent>): {
84
+ event(event: TEvent): void;
85
+ connect(connectionId: number): void;
86
+ lost(): void;
87
+ dispose(): void;
88
+ };
89
+ /**
90
+ * Which connection and query key the open live stream belongs to. An event
91
+ * counts only while both still match: the input changes synchronously but the
92
+ * stream is torn down asynchronously, so a frame in flight from the previous
93
+ * subscription would otherwise land in the new key (and, with
94
+ * `staleTime: Infinity`, stay there).
95
+ */
96
+ export declare function createStreamScope(): {
97
+ open(connectionId: number, keyHash: string): void;
98
+ owns: (connectionId: number, keyHash: string) => boolean;
99
+ };
100
+ /**
101
+ * Wrap a live query's HTTP `queryFn`: report the raw seed, convert it with
102
+ * `select`, and reconcile it with what the stream already wrote. The cache is
103
+ * read after the request resolves, because stream events can arrive while it
104
+ * is in flight.
105
+ */
106
+ export declare function seedQueryFn<TRouteData, TData, TInput>(queryFn: (context: unknown) => Promise<TRouteData>, options: {
107
+ input: TInput;
108
+ readCache: () => TData | undefined;
109
+ select?: ((data: TRouteData) => TData) | undefined;
110
+ onSeed?: ((data: TRouteData, input: TInput) => void) | undefined;
111
+ mergeSeed?: ((fetched: TData, cached: TData | undefined) => TData) | undefined;
112
+ }): (context: unknown) => Promise<TData>;
113
+ export {};
114
+ //# sourceMappingURL=realtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"realtime.d.ts","sourceRoot":"","sources":["../src/realtime.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE3C,MAAM,MAAM,oBAAoB,GAC7B,MAAM,GACN,YAAY,GACZ,WAAW,GACX,OAAO,GACP,QAAQ,CAAA;AAKX;;;;;GAKG;AACH,wBAAgB,oBAAoB,CACnC,UAAU,EAAE,MAAM,EAClB,MAAM,GAAE,MAAM,MAAoB,GAChC,MAAM,CAOR;AAED,KAAK,yBAAyB,CAAC,MAAM,IAAI;IACxC,IAAI,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAA;IAC7D,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,KAAK,IAAI,CAAA;IACtD,QAAQ,EAAE,CAAC,MAAM,EAAE,oBAAoB,KAAK,IAAI,CAAA;IAChD,SAAS,CAAC,EAAE,CAAC,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAA;IACxD,OAAO,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,C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