ai-resumable-stream 3.1.0 → 3.2.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/README.md CHANGED
@@ -136,6 +136,7 @@ async function sendMessage(chatId: string, messages: UIMessage[]) {
136
136
  | `streamId` | `string` | Id of the stream. Use it to resume or stop the stream. Defaults to a generated id, returned as `streamId` |
137
137
  | `generationId` | `string` | Id of this generation. Use it to resume or stop only this generation. Must be unique within the stream id. Defaults to a generated id, returned as `generationId` |
138
138
  | `abortController` | `AbortController` | Aborted when the stream is stopped. Created by the library if you do not pass one |
139
+ | `stopTimeoutMs` | `number` | Time that a stop waits for the source to end before it cancels the source. Defaults to `1000` with a supplied `abortController`, `0` without one |
139
140
  | `onStopSubscriptionError` | `(error: unknown) => void` | Called when the subscription to stop requests fails. The stream continues, but it cannot be stopped |
140
141
  | `onFinish` | `() => void \| Promise<void>` | Called after the source stream has ended, also after an error or a stop. Errors thrown by the callback are ignored |
141
142
 
@@ -158,6 +159,24 @@ await context.startStream(toUIMessageStream({ stream: result.stream }), {
158
159
 
159
160
  We recommend that you pass your own `abortController` and give its signal to `streamText`. A stop then aborts the request to the provider directly, and the AI SDK emits its `abort` chunk and calls `onAbort`. Without it, a stop only cancels the source stream, and the cancellation must propagate back to `streamText`.
160
161
 
162
+ #### Stop timeout
163
+
164
+ A stop aborts the `abortController` and waits up to `stopTimeoutMs` for the source to end. This lets `streamText` emit its `abort` chunk, so `onEnd` and `onFinish` get `isAborted: true`. A source that does not end in time is cancelled.
165
+
166
+ With `stopTimeoutMs: 0`, or without an `abortController`, a stop cancels the source immediately and `isAborted` is `false`.
167
+
168
+ ```ts
169
+ const abortController = new AbortController();
170
+ const result = streamText({ model, messages, abortSignal: abortController.signal });
171
+ const source = toUIMessageStream({
172
+ stream: result.stream,
173
+ onFinish: ({ isAborted, responseMessage }) => {
174
+ // `isAborted` is `true` after a stop
175
+ },
176
+ });
177
+ await context.startStream(source, { streamId, abortController });
178
+ ```
179
+
161
180
  ### `resumeStream`
162
181
 
163
182
  Resumes an existing stream. The returned stream first replays all chunks produced so far and then continues with the new chunks. Pass `generationId` to resume a specific generation. Omit it to resume the current generation of the stream id. Returns `null` when there is nothing to resume.
@@ -504,6 +523,7 @@ type StartStreamOptions = {
504
523
  streamId?: string;
505
524
  generationId?: string;
506
525
  abortController?: AbortController;
526
+ stopTimeoutMs?: number;
507
527
  onStopSubscriptionError?: (error: unknown) => void;
508
528
  onFinish?: () => void | Promise<void>;
509
529
  };
@@ -1,5 +1,5 @@
1
1
  import { n as StreamCodec } from "../adapter-CTz0z2k0.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-DmhblcmG.mjs";
2
+ import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-DaFTnidy.mjs";
3
3
  import { UIMessageChunk } from "ai";
4
4
  //#region src/ai-sdk/index.d.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { t as createResumableStream } from "../core-DAlVpiTc.mjs";
1
+ import { t as createResumableStream } from "../core-DLalFjGA.mjs";
2
2
  import { asSchema, uiMessageChunkSchema } from "ai";
3
3
  //#region src/ai-sdk/index.ts
4
4
  const schema = asSchema(uiMessageChunkSchema);
@@ -1,6 +1,10 @@
1
1
  import { createAsyncIterableStream } from "ai-stream-utils";
2
2
  //#region src/core.ts
3
3
  /**
4
+ * The longest delay a timer accepts. A longer one fires almost immediately instead.
5
+ */
6
+ const MAX_TIMEOUT_MS = 2147483647;
7
+ /**
4
8
  * Ignores teardown failures so they never mask the original outcome.
5
9
  */
6
10
  async function ignoreErrors(fn) {
@@ -18,7 +22,8 @@ async function ignoreErrors(fn) {
18
22
  function createResumableStream(options) {
19
23
  const { adapter, codec, waitUntil, generateId = () => crypto.randomUUID() } = options;
20
24
  async function startStream(source, startOptions = {}) {
21
- const { streamId = generateId(), generationId = generateId(), abortController = new AbortController(), onFinish, onStopSubscriptionError } = startOptions;
25
+ const { streamId = generateId(), generationId = generateId(), abortController: suppliedController, stopTimeoutMs = suppliedController ? 1e3 : 0, onFinish, onStopSubscriptionError } = startOptions;
26
+ const abortController = suppliedController ?? new AbortController();
22
27
  /**
23
28
  * Chunks for the client, exactly as produced. Cancelling stops the client fan-out
24
29
  * but leaves the drain loop running so the adapter still receives every chunk.
@@ -46,14 +51,25 @@ function createResumableStream(options) {
46
51
  const reader = source.getReader();
47
52
  /**
48
53
  * Cancelling the source resolves any pending read as done, which ends the drain
49
- * loop, and propagates upstream so the producer stops doing work. Registered before
50
- * anything can request a stop, so an early stop is not missed.
54
+ * loop, and propagates upstream so the producer stops doing work. Deferred by
55
+ * `stopTimeoutMs`, so a producer that observes the signal can end its stream first and
56
+ * the chunks that report the stop are still drained. Registered before anything can
57
+ * request a stop, so an early stop is not missed.
51
58
  */
52
- const onAbort = () => {
59
+ let cancelTimer;
60
+ const cancelSource = () => {
53
61
  reader.cancel().catch(() => {
54
62
  /** The source is already gone */
55
63
  });
56
64
  };
65
+ const onAbort = () => {
66
+ if (stopTimeoutMs <= 0) {
67
+ cancelSource();
68
+ return;
69
+ }
70
+ if (stopTimeoutMs > MAX_TIMEOUT_MS) return;
71
+ cancelTimer = setTimeout(cancelSource, stopTimeoutMs);
72
+ };
57
73
  abortController.signal.addEventListener(`abort`, onAbort, { once: true });
58
74
  /**
59
75
  * Set once the source has ended, after which a stop has nothing left to abort and a
@@ -66,6 +82,7 @@ function createResumableStream(options) {
66
82
  */
67
83
  async function finish() {
68
84
  finished = true;
85
+ clearTimeout(cancelTimer);
69
86
  abortController.signal.removeEventListener(`abort`, onAbort);
70
87
  const remove = unsubscribe;
71
88
  unsubscribe = void 0;
@@ -28,6 +28,23 @@ type StartStreamOptions = {
28
28
  * of relying on stream cancellation propagating upstream.
29
29
  */
30
30
  abortController?: AbortController;
31
+ /**
32
+ * How long a stop waits for the source to end on its own before it cancels the source.
33
+ * Defaults to `1_000` when an `abortController` is supplied, and to `0` otherwise, since
34
+ * a controller created here has no other listener that could end the source.
35
+ *
36
+ * A producer that observes the signal ends its stream itself, and the chunks it emits
37
+ * while doing so still reach the client and the adapter. For `streamText` that is the
38
+ * `abort` chunk, which is what makes `isAborted` true in the UI message stream's
39
+ * `onEnd`/`onFinish`: cancelling first ends that stream before the chunk arrives. A
40
+ * source that ignores the signal, or hangs, is cancelled once the time runs out, so it
41
+ * may produce chunks for that long after the stop. `0` cancels the source immediately.
42
+ *
43
+ * Must be longer than the work a producer does before it ends its stream, for `streamText`
44
+ * the `onAbort` callbacks it awaits before it emits the `abort` chunk. Values longer than a
45
+ * timer can hold, such as `Infinity`, never cancel the source.
46
+ */
47
+ stopTimeoutMs?: number;
31
48
  /**
32
49
  * Called when listening for stop requests fails. The stream is unaffected, but it
33
50
  * cannot be stopped. Errors thrown by the callback are ignored.
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { n as StreamCodec, t as StreamAdapter } from "./adapter-CTz0z2k0.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-DmhblcmG.mjs";
2
+ import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-DaFTnidy.mjs";
3
3
  export { CreateResumableStreamOptions, ResumeStreamOptions, StartStreamOptions, StartStreamResult, StopStreamOptions, type StreamAdapter, type StreamCodec, createResumableStream };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as createResumableStream } from "./core-DAlVpiTc.mjs";
1
+ import { t as createResumableStream } from "./core-DLalFjGA.mjs";
2
2
  export { createResumableStream };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-resumable-stream",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "Resume and stop AI SDK streams, backed by S3, Redis, or any store you provide",
5
5
  "keywords": [
6
6
  "ai",