@trigger.dev/react-hooks 0.0.0-bun-runtimes-20260909131057

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 (89) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1 -0
  3. package/dist/commonjs/contexts.d.ts +4 -0
  4. package/dist/commonjs/contexts.js +10 -0
  5. package/dist/commonjs/contexts.js.map +1 -0
  6. package/dist/commonjs/hooks/useApiClient.d.ts +47 -0
  7. package/dist/commonjs/hooks/useApiClient.js +57 -0
  8. package/dist/commonjs/hooks/useApiClient.js.map +1 -0
  9. package/dist/commonjs/hooks/useInputStreamSend.d.ts +26 -0
  10. package/dist/commonjs/hooks/useInputStreamSend.js +45 -0
  11. package/dist/commonjs/hooks/useInputStreamSend.js.map +1 -0
  12. package/dist/commonjs/hooks/useRealtime.d.ts +336 -0
  13. package/dist/commonjs/hooks/useRealtime.js +642 -0
  14. package/dist/commonjs/hooks/useRealtime.js.map +1 -0
  15. package/dist/commonjs/hooks/useRun.d.ts +22 -0
  16. package/dist/commonjs/hooks/useRun.js +40 -0
  17. package/dist/commonjs/hooks/useRun.js.map +1 -0
  18. package/dist/commonjs/hooks/useSessionStream.d.ts +131 -0
  19. package/dist/commonjs/hooks/useSessionStream.js +236 -0
  20. package/dist/commonjs/hooks/useSessionStream.js.map +1 -0
  21. package/dist/commonjs/hooks/useSessionStreamChannel.d.ts +86 -0
  22. package/dist/commonjs/hooks/useSessionStreamChannel.js +209 -0
  23. package/dist/commonjs/hooks/useSessionStreamChannel.js.map +1 -0
  24. package/dist/commonjs/hooks/useTaskTrigger.d.ts +107 -0
  25. package/dist/commonjs/hooks/useTaskTrigger.js +139 -0
  26. package/dist/commonjs/hooks/useTaskTrigger.js.map +1 -0
  27. package/dist/commonjs/hooks/useWaitToken.d.ts +35 -0
  28. package/dist/commonjs/hooks/useWaitToken.js +52 -0
  29. package/dist/commonjs/hooks/useWaitToken.js.map +1 -0
  30. package/dist/commonjs/index.d.ts +9 -0
  31. package/dist/commonjs/index.js +26 -0
  32. package/dist/commonjs/index.js.map +1 -0
  33. package/dist/commonjs/package.json +3 -0
  34. package/dist/commonjs/utils/createContextAndHook.d.ts +14 -0
  35. package/dist/commonjs/utils/createContextAndHook.js +38 -0
  36. package/dist/commonjs/utils/createContextAndHook.js.map +1 -0
  37. package/dist/commonjs/utils/throttle.d.ts +6 -0
  38. package/dist/commonjs/utils/throttle.js +50 -0
  39. package/dist/commonjs/utils/throttle.js.map +1 -0
  40. package/dist/commonjs/utils/trigger-swr.d.ts +19 -0
  41. package/dist/commonjs/utils/trigger-swr.js +27 -0
  42. package/dist/commonjs/utils/trigger-swr.js.map +1 -0
  43. package/dist/commonjs/utils/useStableRequestCallback.d.ts +5 -0
  44. package/dist/commonjs/utils/useStableRequestCallback.js +17 -0
  45. package/dist/commonjs/utils/useStableRequestCallback.js.map +1 -0
  46. package/dist/esm/contexts.d.ts +4 -0
  47. package/dist/esm/contexts.js +5 -0
  48. package/dist/esm/contexts.js.map +1 -0
  49. package/dist/esm/hooks/useApiClient.d.ts +47 -0
  50. package/dist/esm/hooks/useApiClient.js +54 -0
  51. package/dist/esm/hooks/useApiClient.js.map +1 -0
  52. package/dist/esm/hooks/useInputStreamSend.d.ts +26 -0
  53. package/dist/esm/hooks/useInputStreamSend.js +39 -0
  54. package/dist/esm/hooks/useInputStreamSend.js.map +1 -0
  55. package/dist/esm/hooks/useRealtime.d.ts +336 -0
  56. package/dist/esm/hooks/useRealtime.js +635 -0
  57. package/dist/esm/hooks/useRealtime.js.map +1 -0
  58. package/dist/esm/hooks/useRun.d.ts +22 -0
  59. package/dist/esm/hooks/useRun.js +37 -0
  60. package/dist/esm/hooks/useRun.js.map +1 -0
  61. package/dist/esm/hooks/useSessionStream.d.ts +131 -0
  62. package/dist/esm/hooks/useSessionStream.js +233 -0
  63. package/dist/esm/hooks/useSessionStream.js.map +1 -0
  64. package/dist/esm/hooks/useSessionStreamChannel.d.ts +86 -0
  65. package/dist/esm/hooks/useSessionStreamChannel.js +206 -0
  66. package/dist/esm/hooks/useSessionStreamChannel.js.map +1 -0
  67. package/dist/esm/hooks/useTaskTrigger.d.ts +107 -0
  68. package/dist/esm/hooks/useTaskTrigger.js +131 -0
  69. package/dist/esm/hooks/useTaskTrigger.js.map +1 -0
  70. package/dist/esm/hooks/useWaitToken.d.ts +35 -0
  71. package/dist/esm/hooks/useWaitToken.js +46 -0
  72. package/dist/esm/hooks/useWaitToken.js.map +1 -0
  73. package/dist/esm/index.d.ts +9 -0
  74. package/dist/esm/index.js +10 -0
  75. package/dist/esm/index.js.map +1 -0
  76. package/dist/esm/package.json +3 -0
  77. package/dist/esm/utils/createContextAndHook.d.ts +14 -0
  78. package/dist/esm/utils/createContextAndHook.js +31 -0
  79. package/dist/esm/utils/createContextAndHook.js.map +1 -0
  80. package/dist/esm/utils/throttle.d.ts +6 -0
  81. package/dist/esm/utils/throttle.js +47 -0
  82. package/dist/esm/utils/throttle.js.map +1 -0
  83. package/dist/esm/utils/trigger-swr.d.ts +19 -0
  84. package/dist/esm/utils/trigger-swr.js +6 -0
  85. package/dist/esm/utils/trigger-swr.js.map +1 -0
  86. package/dist/esm/utils/useStableRequestCallback.d.ts +5 -0
  87. package/dist/esm/utils/useStableRequestCallback.js +14 -0
  88. package/dist/esm/utils/useStableRequestCallback.js.map +1 -0
  89. package/package.json +75 -0
@@ -0,0 +1,642 @@
1
+ "use strict";
2
+ "use client";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useRealtimeRun = useRealtimeRun;
5
+ exports.useRealtimeRunWithStreams = useRealtimeRunWithStreams;
6
+ exports.useRealtimeRunsWithTag = useRealtimeRunsWithTag;
7
+ exports.useRealtimeBatch = useRealtimeBatch;
8
+ exports.useRealtimeStream = useRealtimeStream;
9
+ const react_1 = require("react");
10
+ const trigger_swr_js_1 = require("../utils/trigger-swr.js");
11
+ const useApiClient_js_1 = require("./useApiClient.js");
12
+ const throttle_js_1 = require("../utils/throttle.js");
13
+ const useStableRequestCallback_js_1 = require("../utils/useStableRequestCallback.js");
14
+ /**
15
+ * Hook to subscribe to realtime updates of a task run.
16
+ *
17
+ * @template TTask - The type of the task
18
+ * @param {string} [runId] - The unique identifier of the run to subscribe to
19
+ * @param {UseRealtimeSingleRunOptions} [options] - Configuration options for the subscription
20
+ * @returns {UseRealtimeRunInstance<TTask>} An object containing the current state of the run, error handling, and control methods
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import type { myTask } from './path/to/task';
25
+ * const { run, error } = useRealtimeRun<typeof myTask>('run-id-123');
26
+ * ```
27
+ */
28
+ function useRealtimeRun(runId, options) {
29
+ const hookId = (0, react_1.useId)();
30
+ const idKey = options?.id ?? hookId;
31
+ // Store the streams state in SWR, using the idKey as the key to share states.
32
+ const { data: run, mutate: mutateRun } = (0, trigger_swr_js_1.useSWR)([idKey, "run"], null);
33
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, "error"], null);
34
+ // Add state to track when the subscription is complete
35
+ const { data: isComplete = false, mutate: setIsComplete } = (0, trigger_swr_js_1.useSWR)([idKey, "complete"], null);
36
+ // Abort controller to cancel the current API call.
37
+ const abortControllerRef = (0, react_1.useRef)(null);
38
+ const stop = (0, react_1.useCallback)(() => {
39
+ if (abortControllerRef.current) {
40
+ abortControllerRef.current.abort();
41
+ abortControllerRef.current = null;
42
+ }
43
+ }, []);
44
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
45
+ const onComplete = options?.onComplete;
46
+ const skipColumns = options?.skipColumns;
47
+ const stopOnCompletion = options?.stopOnCompletion;
48
+ const triggerRequest = (0, react_1.useCallback)(async () => {
49
+ try {
50
+ if (!runId || !apiClient) {
51
+ return;
52
+ }
53
+ const abortController = new AbortController();
54
+ abortControllerRef.current = abortController;
55
+ await processRealtimeRun(runId, { skipColumns }, apiClient, mutateRun, setError, abortControllerRef, typeof stopOnCompletion === "boolean" ? stopOnCompletion : true);
56
+ }
57
+ catch (err) {
58
+ // Ignore abort errors as they are expected.
59
+ if (err.name === "AbortError") {
60
+ abortControllerRef.current = null;
61
+ return;
62
+ }
63
+ setError(err);
64
+ }
65
+ finally {
66
+ if (abortControllerRef.current) {
67
+ abortControllerRef.current = null;
68
+ }
69
+ // Mark the subscription as complete
70
+ setIsComplete(true);
71
+ }
72
+ }, [runId, apiClient, mutateRun, setError, setIsComplete, skipColumns, stopOnCompletion]);
73
+ const requestSubscription = (0, useStableRequestCallback_js_1.useStableRequestCallback)(triggerRequest);
74
+ const hasCalledOnCompleteRef = (0, react_1.useRef)(false);
75
+ // Effect to handle onComplete callback
76
+ // Only call onComplete when the run has actually finished (has finishedAt),
77
+ // not just when the subscription stream ends (which can happen due to network issues)
78
+ (0, react_1.useEffect)(() => {
79
+ if (isComplete && run?.finishedAt && onComplete && !hasCalledOnCompleteRef.current) {
80
+ onComplete(run, error);
81
+ hasCalledOnCompleteRef.current = true;
82
+ }
83
+ }, [isComplete, run, error, onComplete]);
84
+ (0, react_1.useEffect)(() => {
85
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
86
+ return;
87
+ }
88
+ if (!runId) {
89
+ return;
90
+ }
91
+ requestSubscription().finally(() => { });
92
+ return () => {
93
+ stop();
94
+ };
95
+ }, [runId, stop, options?.enabled, requestSubscription]);
96
+ (0, react_1.useEffect)(() => {
97
+ if (run?.finishedAt) {
98
+ setIsComplete(true);
99
+ }
100
+ }, [run, setIsComplete]);
101
+ return { run, error, stop };
102
+ }
103
+ /**
104
+ * Hook to subscribe to realtime updates of a task run with associated data streams.
105
+ *
106
+ * @template TTask - The type of the task
107
+ * @template TStreams - The type of the streams data
108
+ * @param {string} [runId] - The unique identifier of the run to subscribe to
109
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
110
+ * @returns {UseRealtimeRunWithStreamsInstance<TTask, TStreams>} An object containing the current state of the run, streams data, and error handling
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * import type { myTask } from './path/to/task';
115
+ * const { run, streams, error } = useRealtimeRunWithStreams<typeof myTask, {
116
+ * output: string;
117
+ * }>('run-id-123');
118
+ * ```
119
+ */
120
+ function useRealtimeRunWithStreams(runId, options) {
121
+ const hookId = (0, react_1.useId)();
122
+ const idKey = options?.id ?? hookId;
123
+ const [initialStreamsFallback] = (0, react_1.useState)({});
124
+ // Store the streams state in SWR, using the idKey as the key to share states.
125
+ const { data: streams, mutate: mutateStreams } = (0, trigger_swr_js_1.useSWR)([idKey, "streams"], null, {
126
+ fallbackData: initialStreamsFallback,
127
+ });
128
+ // Keep the latest streams in a ref.
129
+ const streamsRef = (0, react_1.useRef)(streams ?? {});
130
+ (0, react_1.useEffect)(() => {
131
+ streamsRef.current = streams || {};
132
+ }, [streams]);
133
+ // Store the streams state in SWR, using the idKey as the key to share states.
134
+ const { data: run, mutate: mutateRun } = (0, trigger_swr_js_1.useSWR)([idKey, "run"], null);
135
+ // Add state to track when the subscription is complete
136
+ const { data: isComplete = false, mutate: setIsComplete } = (0, trigger_swr_js_1.useSWR)([idKey, "complete"], null);
137
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, "error"], null);
138
+ // Abort controller to cancel the current API call.
139
+ const abortControllerRef = (0, react_1.useRef)(null);
140
+ const stop = (0, react_1.useCallback)(() => {
141
+ if (abortControllerRef.current) {
142
+ abortControllerRef.current.abort();
143
+ abortControllerRef.current = null;
144
+ }
145
+ }, []);
146
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
147
+ const onComplete = options?.onComplete;
148
+ const skipColumns = options?.skipColumns;
149
+ const stopOnCompletion = options?.stopOnCompletion;
150
+ const throttleInMs = options?.throttleInMs;
151
+ const triggerRequest = (0, react_1.useCallback)(async () => {
152
+ try {
153
+ if (!runId || !apiClient) {
154
+ return;
155
+ }
156
+ const abortController = new AbortController();
157
+ abortControllerRef.current = abortController;
158
+ await processRealtimeRunWithStreams(runId, { skipColumns }, apiClient, mutateRun, mutateStreams, streamsRef, setError, abortControllerRef, typeof stopOnCompletion === "boolean" ? stopOnCompletion : true, throttleInMs ?? 16);
159
+ }
160
+ catch (err) {
161
+ // Ignore abort errors as they are expected.
162
+ if (err.name === "AbortError") {
163
+ abortControllerRef.current = null;
164
+ return;
165
+ }
166
+ setError(err);
167
+ }
168
+ finally {
169
+ if (abortControllerRef.current) {
170
+ abortControllerRef.current = null;
171
+ }
172
+ // Mark the subscription as complete
173
+ setIsComplete(true);
174
+ }
175
+ }, [
176
+ runId,
177
+ apiClient,
178
+ mutateRun,
179
+ mutateStreams,
180
+ setError,
181
+ setIsComplete,
182
+ skipColumns,
183
+ stopOnCompletion,
184
+ throttleInMs,
185
+ ]);
186
+ const requestSubscription = (0, useStableRequestCallback_js_1.useStableRequestCallback)(triggerRequest);
187
+ const hasCalledOnCompleteRef = (0, react_1.useRef)(false);
188
+ // Effect to handle onComplete callback
189
+ // Only call onComplete when the run has actually finished (has finishedAt),
190
+ // not just when the subscription stream ends (which can happen due to network issues)
191
+ (0, react_1.useEffect)(() => {
192
+ if (isComplete && run?.finishedAt && onComplete && !hasCalledOnCompleteRef.current) {
193
+ onComplete(run, error);
194
+ hasCalledOnCompleteRef.current = true;
195
+ }
196
+ }, [isComplete, run, error, onComplete]);
197
+ (0, react_1.useEffect)(() => {
198
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
199
+ return;
200
+ }
201
+ if (!runId) {
202
+ return;
203
+ }
204
+ requestSubscription().finally(() => { });
205
+ return () => {
206
+ stop();
207
+ };
208
+ }, [runId, stop, options?.enabled, requestSubscription]);
209
+ (0, react_1.useEffect)(() => {
210
+ if (run?.finishedAt) {
211
+ setIsComplete(true);
212
+ }
213
+ }, [run, setIsComplete]);
214
+ return { run, streams: streams ?? initialStreamsFallback, error, stop };
215
+ }
216
+ /**
217
+ * Hook to subscribe to realtime updates of task runs filtered by tag(s).
218
+ *
219
+ * @template TTask - The type of the task
220
+ * @param {string | string[]} tag - The tag or array of tags to filter runs by
221
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
222
+ * @returns {UseRealtimeRunsInstance<TTask>} An object containing the current state of the runs and any error encountered
223
+ *
224
+ * @example
225
+ * ```ts
226
+ * import type { myTask } from './path/to/task';
227
+ * const { runs, error } = useRealtimeRunsWithTag<typeof myTask>('my-tag');
228
+ * // Or with multiple tags
229
+ * const { runs, error } = useRealtimeRunsWithTag<typeof myTask>(['tag1', 'tag2']);
230
+ * // Or with a createdAt filter
231
+ * const { runs, error } = useRealtimeRunsWithTag<typeof myTask>('my-tag', { createdAt: '1h' });
232
+ * ```
233
+ */
234
+ function useRealtimeRunsWithTag(tag, options) {
235
+ const normalizedTag = (Array.isArray(tag) ? tag : [tag]).join("-");
236
+ const hookId = (0, react_1.useId)();
237
+ const idKey = options?.id ?? hookId;
238
+ // Store the streams state in SWR, using the idKey as the key to share states.
239
+ const { data: runs, mutate: mutateRuns } = (0, trigger_swr_js_1.useSWR)([idKey, "run"], null, {
240
+ fallbackData: [],
241
+ });
242
+ // Keep the latest streams in a ref.
243
+ const runsRef = (0, react_1.useRef)([]);
244
+ (0, react_1.useEffect)(() => {
245
+ runsRef.current = runs ?? [];
246
+ }, [runs]);
247
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, "error"], null);
248
+ // Abort controller to cancel the current API call.
249
+ const abortControllerRef = (0, react_1.useRef)(null);
250
+ const stop = (0, react_1.useCallback)(() => {
251
+ if (abortControllerRef.current) {
252
+ abortControllerRef.current.abort();
253
+ abortControllerRef.current = null;
254
+ }
255
+ }, []);
256
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
257
+ const createdAt = options?.createdAt;
258
+ const skipColumns = options?.skipColumns;
259
+ const triggerRequest = (0, react_1.useCallback)(async () => {
260
+ try {
261
+ if (!apiClient) {
262
+ return;
263
+ }
264
+ const abortController = new AbortController();
265
+ abortControllerRef.current = abortController;
266
+ await processRealtimeRunsWithTag(tag, { createdAt, skipColumns }, apiClient, mutateRuns, runsRef, setError, abortControllerRef);
267
+ }
268
+ catch (err) {
269
+ // Ignore abort errors as they are expected.
270
+ if (err.name === "AbortError") {
271
+ abortControllerRef.current = null;
272
+ return;
273
+ }
274
+ setError(err);
275
+ }
276
+ finally {
277
+ if (abortControllerRef.current) {
278
+ abortControllerRef.current = null;
279
+ }
280
+ }
281
+ }, [tag, createdAt, skipColumns, apiClient, mutateRuns, setError]);
282
+ const requestSubscription = (0, useStableRequestCallback_js_1.useStableRequestCallback)(triggerRequest);
283
+ (0, react_1.useEffect)(() => {
284
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
285
+ return;
286
+ }
287
+ requestSubscription().finally(() => { });
288
+ return () => {
289
+ stop();
290
+ };
291
+ }, [normalizedTag, stop, options?.enabled, requestSubscription]);
292
+ return { runs: runs ?? [], error, stop };
293
+ }
294
+ /**
295
+ * Hook to subscribe to realtime updates of a batch of task runs.
296
+ *
297
+ * @template TTask - The type of the task
298
+ * @param {string} batchId - The unique identifier of the batch to subscribe to
299
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
300
+ * @returns {UseRealtimeRunsInstance<TTask>} An object containing the current state of the runs, error handling, and control methods
301
+ *
302
+ * @example
303
+ * ```ts
304
+ * import type { myTask } from './path/to/task';
305
+ * const { runs, error } = useRealtimeBatch<typeof myTask>('batch-id-123');
306
+ * ```
307
+ */
308
+ function useRealtimeBatch(batchId, options) {
309
+ const hookId = (0, react_1.useId)();
310
+ const idKey = options?.id ?? hookId;
311
+ // Store the streams state in SWR, using the idKey as the key to share states.
312
+ const { data: runs, mutate: mutateRuns } = (0, trigger_swr_js_1.useSWR)([idKey, "run"], null, {
313
+ fallbackData: [],
314
+ });
315
+ // Keep the latest streams in a ref.
316
+ const runsRef = (0, react_1.useRef)([]);
317
+ (0, react_1.useEffect)(() => {
318
+ runsRef.current = runs ?? [];
319
+ }, [runs]);
320
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, "error"], null);
321
+ // Abort controller to cancel the current API call.
322
+ const abortControllerRef = (0, react_1.useRef)(null);
323
+ const stop = (0, react_1.useCallback)(() => {
324
+ if (abortControllerRef.current) {
325
+ abortControllerRef.current.abort();
326
+ abortControllerRef.current = null;
327
+ }
328
+ }, []);
329
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
330
+ const triggerRequest = (0, react_1.useCallback)(async () => {
331
+ try {
332
+ if (!apiClient) {
333
+ return;
334
+ }
335
+ const abortController = new AbortController();
336
+ abortControllerRef.current = abortController;
337
+ await processRealtimeBatch(batchId, apiClient, mutateRuns, runsRef, setError, abortControllerRef);
338
+ }
339
+ catch (err) {
340
+ // Ignore abort errors as they are expected.
341
+ if (err.name === "AbortError") {
342
+ abortControllerRef.current = null;
343
+ return;
344
+ }
345
+ setError(err);
346
+ }
347
+ finally {
348
+ if (abortControllerRef.current) {
349
+ abortControllerRef.current = null;
350
+ }
351
+ }
352
+ }, [batchId, mutateRuns, runsRef, abortControllerRef, apiClient, setError]);
353
+ const requestSubscription = (0, useStableRequestCallback_js_1.useStableRequestCallback)(triggerRequest);
354
+ (0, react_1.useEffect)(() => {
355
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
356
+ return;
357
+ }
358
+ requestSubscription().finally(() => { });
359
+ return () => {
360
+ stop();
361
+ };
362
+ }, [batchId, stop, options?.enabled, requestSubscription]);
363
+ return { runs: runs ?? [], error, stop };
364
+ }
365
+ function useRealtimeStream(runIdOrDefinedStream, streamKeyOrOptionsOrRunId, options) {
366
+ let runId;
367
+ let streamKey;
368
+ let resolvedOptions;
369
+ if (typeof runIdOrDefinedStream === "string") {
370
+ runId = runIdOrDefinedStream;
371
+ streamKey =
372
+ typeof streamKeyOrOptionsOrRunId === "string" ? streamKeyOrOptionsOrRunId : "default";
373
+ resolvedOptions =
374
+ typeof streamKeyOrOptionsOrRunId === "string" ? options : streamKeyOrOptionsOrRunId;
375
+ }
376
+ else {
377
+ if (typeof streamKeyOrOptionsOrRunId !== "string") {
378
+ throw new Error("Invalid second argument to useRealtimeStream. When using a defined stream instance, the second argument to useRealtimeStream must be a run ID.");
379
+ }
380
+ runId = streamKeyOrOptionsOrRunId;
381
+ streamKey = runIdOrDefinedStream.id;
382
+ resolvedOptions = options;
383
+ }
384
+ return useRealtimeStreamImplementation(runId, streamKey, resolvedOptions);
385
+ }
386
+ function useRealtimeStreamImplementation(runId, streamKey, options) {
387
+ const hookId = (0, react_1.useId)();
388
+ const idKey = options?.id ?? hookId;
389
+ const [initialPartsFallback] = (0, react_1.useState)([]);
390
+ // Store the streams state in SWR, using the idKey as the key to share states.
391
+ const { data: parts, mutate: mutateParts } = (0, trigger_swr_js_1.useSWR)([idKey, runId, streamKey, "parts"], null, {
392
+ fallbackData: initialPartsFallback,
393
+ });
394
+ // Keep the latest streams in a ref.
395
+ const partsRef = (0, react_1.useRef)(parts ?? []);
396
+ (0, react_1.useEffect)(() => {
397
+ partsRef.current = parts || [];
398
+ }, [parts]);
399
+ const { data: persistedLastEventId, mutate: mutateLastEventId } = (0, trigger_swr_js_1.useSWR)([idKey, runId, streamKey, "lastEventId"], null);
400
+ const lastEventIdRef = (0, react_1.useRef)(persistedLastEventId);
401
+ const streamIdentityRef = (0, react_1.useRef)(`${idKey}:${runId}:${streamKey}`);
402
+ (0, react_1.useEffect)(() => {
403
+ const identity = `${idKey}:${runId}:${streamKey}`;
404
+ if (streamIdentityRef.current !== identity) {
405
+ streamIdentityRef.current = identity;
406
+ lastEventIdRef.current = persistedLastEventId;
407
+ }
408
+ }, [idKey, runId, streamKey, persistedLastEventId]);
409
+ // Add state to track when the subscription is complete
410
+ const { data: _isComplete = false, mutate: setIsComplete } = (0, trigger_swr_js_1.useSWR)([idKey, runId, streamKey, "complete"], null);
411
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, runId, streamKey, "error"], null);
412
+ // Abort controller to cancel the current API call.
413
+ const abortControllerRef = (0, react_1.useRef)(null);
414
+ const stop = (0, react_1.useCallback)(() => {
415
+ if (abortControllerRef.current) {
416
+ abortControllerRef.current.abort();
417
+ abortControllerRef.current = null;
418
+ }
419
+ }, []);
420
+ const onDataCallback = options?.onData;
421
+ const onData = (0, react_1.useCallback)((data) => {
422
+ if (onDataCallback) {
423
+ onDataCallback(data);
424
+ }
425
+ }, [onDataCallback]);
426
+ const onPartsCallback = options?.onParts;
427
+ const onParts = (0, react_1.useCallback)((partsBatch) => {
428
+ if (onPartsCallback) {
429
+ onPartsCallback(partsBatch);
430
+ }
431
+ }, [onPartsCallback]);
432
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
433
+ const timeoutInSeconds = options?.timeoutInSeconds;
434
+ const startIndex = options?.startIndex;
435
+ const startEventId = options?.lastEventId;
436
+ const throttleInMs = options?.throttleInMs;
437
+ const from = options?.from;
438
+ const maxParts = options?.maxParts;
439
+ (0, react_1.useEffect)(() => {
440
+ if (maxParts != null && maxParts >= 0) {
441
+ const current = partsRef.current;
442
+ if (current.length > maxParts) {
443
+ mutateParts(current.slice(current.length - maxParts));
444
+ }
445
+ }
446
+ }, [maxParts, mutateParts]);
447
+ const triggerRequest = (0, react_1.useCallback)(async () => {
448
+ try {
449
+ if (!runId || !apiClient) {
450
+ return;
451
+ }
452
+ const abortController = new AbortController();
453
+ abortControllerRef.current = abortController;
454
+ await processRealtimeStream(runId, streamKey, apiClient, mutateParts, partsRef, setError, onData, abortControllerRef, timeoutInSeconds, startIndex, throttleInMs ?? 16, from, maxParts, lastEventIdRef, (id) => mutateLastEventId(id, false), startEventId !== undefined ? String(startEventId) : undefined, onParts);
455
+ }
456
+ catch (err) {
457
+ // Ignore abort errors as they are expected.
458
+ if (err.name === "AbortError") {
459
+ abortControllerRef.current = null;
460
+ return;
461
+ }
462
+ setError(err);
463
+ }
464
+ finally {
465
+ if (abortControllerRef.current) {
466
+ abortControllerRef.current = null;
467
+ }
468
+ // Mark the subscription as complete
469
+ setIsComplete(true);
470
+ }
471
+ }, [
472
+ runId,
473
+ streamKey,
474
+ apiClient,
475
+ mutateParts,
476
+ setError,
477
+ setIsComplete,
478
+ onData,
479
+ onParts,
480
+ timeoutInSeconds,
481
+ startIndex,
482
+ startEventId,
483
+ throttleInMs,
484
+ from,
485
+ maxParts,
486
+ mutateLastEventId,
487
+ ]);
488
+ const requestSubscription = (0, useStableRequestCallback_js_1.useStableRequestCallback)(triggerRequest);
489
+ (0, react_1.useEffect)(() => {
490
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
491
+ return;
492
+ }
493
+ if (!runId) {
494
+ return;
495
+ }
496
+ requestSubscription().finally(() => { });
497
+ return () => {
498
+ stop();
499
+ };
500
+ }, [runId, stop, options?.enabled, requestSubscription]);
501
+ return { parts: parts ?? initialPartsFallback, lastEventId: persistedLastEventId, error, stop };
502
+ }
503
+ async function processRealtimeBatch(batchId, apiClient, mutateRunsData, existingRunsRef, onError, abortControllerRef) {
504
+ const subscription = apiClient.subscribeToBatch(batchId, {
505
+ signal: abortControllerRef.current?.signal,
506
+ onFetchError: onError,
507
+ });
508
+ for await (const part of subscription) {
509
+ mutateRunsData(insertRunShapeInOrder(existingRunsRef.current, part));
510
+ }
511
+ }
512
+ // Inserts and then orders by the run createdAt timestamp, and ensures that the run is not duplicated
513
+ function insertRunShapeInOrder(previousRuns, run) {
514
+ const existingRun = previousRuns.find((r) => r.id === run.id);
515
+ if (existingRun) {
516
+ return previousRuns.map((r) => (r.id === run.id ? run : r));
517
+ }
518
+ const runCreatedAt = run.createdAt;
519
+ const index = previousRuns.findIndex((r) => r.createdAt > runCreatedAt);
520
+ if (index === -1) {
521
+ return [...previousRuns, run];
522
+ }
523
+ return [...previousRuns.slice(0, index), run, ...previousRuns.slice(index)];
524
+ }
525
+ async function processRealtimeRunsWithTag(tag, filters, apiClient, mutateRunsData, existingRunsRef, onError, abortControllerRef) {
526
+ const subscription = apiClient.subscribeToRunsWithTag(tag, filters, {
527
+ signal: abortControllerRef.current?.signal,
528
+ onFetchError: onError,
529
+ });
530
+ for await (const part of subscription) {
531
+ mutateRunsData(insertRunShape(existingRunsRef.current, part));
532
+ }
533
+ }
534
+ // Replaces or inserts a run shape, ordered by the createdAt timestamp
535
+ function insertRunShape(previousRuns, run) {
536
+ const existingRun = previousRuns.find((r) => r.id === run.id);
537
+ if (existingRun) {
538
+ return previousRuns.map((r) => (r.id === run.id ? run : r));
539
+ }
540
+ const createdAt = run.createdAt;
541
+ const index = previousRuns.findIndex((r) => r.createdAt > createdAt);
542
+ if (index === -1) {
543
+ return [...previousRuns, run];
544
+ }
545
+ return [...previousRuns.slice(0, index), run, ...previousRuns.slice(index)];
546
+ }
547
+ async function processRealtimeRunWithStreams(runId, filters, apiClient, mutateRunData, mutateStreamData, existingDataRef, onError, abortControllerRef, stopOnCompletion = true, throttleInMs) {
548
+ const subscription = apiClient.subscribeToRun(runId, {
549
+ signal: abortControllerRef.current?.signal,
550
+ closeOnComplete: stopOnCompletion,
551
+ onFetchError: onError,
552
+ skipColumns: filters.skipColumns,
553
+ });
554
+ const streamQueue = (0, throttle_js_1.createThrottledQueue)(async (updates) => {
555
+ const nextStreamData = { ...existingDataRef.current };
556
+ // Group updates by type
557
+ const updatesByType = updates.reduce((acc, update) => {
558
+ if (!acc[update.type]) {
559
+ acc[update.type] = [];
560
+ }
561
+ acc[update.type].push(update.chunk);
562
+ return acc;
563
+ }, {});
564
+ // Apply all updates
565
+ for (const [type, chunks] of Object.entries(updatesByType)) {
566
+ // @ts-ignore
567
+ nextStreamData[type] = [...(existingDataRef.current[type] || []), ...chunks];
568
+ }
569
+ mutateStreamData(nextStreamData);
570
+ }, throttleInMs);
571
+ for await (const part of subscription.withStreams()) {
572
+ if (part.type === "run") {
573
+ mutateRunData(part.run);
574
+ }
575
+ else {
576
+ streamQueue.add({
577
+ type: part.type,
578
+ // @ts-ignore
579
+ chunk: part.chunk,
580
+ });
581
+ }
582
+ }
583
+ }
584
+ async function processRealtimeRun(runId, filters, apiClient, mutateRunData, onError, abortControllerRef, stopOnCompletion = true) {
585
+ const subscription = apiClient.subscribeToRun(runId, {
586
+ signal: abortControllerRef.current?.signal,
587
+ closeOnComplete: stopOnCompletion,
588
+ onFetchError: onError,
589
+ skipColumns: filters.skipColumns,
590
+ });
591
+ for await (const part of subscription) {
592
+ mutateRunData(part);
593
+ }
594
+ }
595
+ async function processRealtimeStream(runId, streamKey, apiClient, mutatePartsData, existingPartsRef, onError, onData, abortControllerRef, timeoutInSeconds, startIndex, throttleInMs, from, maxParts, lastEventIdRef, persistLastEventId, userLastEventId, onParts) {
596
+ try {
597
+ const resumeFromEventId = lastEventIdRef?.current ??
598
+ userLastEventId ??
599
+ (startIndex ? (startIndex - 1).toString() : undefined);
600
+ const partsQueue = (0, throttle_js_1.createThrottledQueue)(async (batch) => {
601
+ const combined = [...existingPartsRef.current, ...batch.map((part) => part.chunk)];
602
+ const bounded = maxParts != null && maxParts >= 0 && combined.length > maxParts
603
+ ? combined.slice(combined.length - maxParts)
604
+ : combined;
605
+ existingPartsRef.current = bounded;
606
+ mutatePartsData(bounded);
607
+ if (persistLastEventId && lastEventIdRef?.current) {
608
+ persistLastEventId(lastEventIdRef.current);
609
+ }
610
+ onParts?.(batch);
611
+ }, throttleInMs);
612
+ const stream = await apiClient.fetchStream(runId, streamKey, {
613
+ signal: abortControllerRef.current?.signal,
614
+ timeoutInSeconds,
615
+ lastEventId: resumeFromEventId,
616
+ from: startIndex !== undefined ? undefined : from,
617
+ onPart: (part) => {
618
+ if (part.id && lastEventIdRef) {
619
+ lastEventIdRef.current = part.id;
620
+ }
621
+ partsQueue.add(part);
622
+ },
623
+ });
624
+ for await (const part of stream) {
625
+ onData(part);
626
+ }
627
+ await partsQueue.flush();
628
+ }
629
+ catch (err) {
630
+ if (err.name === "AbortError") {
631
+ return;
632
+ }
633
+ if (err instanceof Error) {
634
+ onError(err);
635
+ }
636
+ else {
637
+ onError(new Error(String(err)));
638
+ }
639
+ throw err;
640
+ }
641
+ }
642
+ //# sourceMappingURL=useRealtime.js.map