ai-resumable-stream 2.0.0 → 3.0.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 +445 -262
- package/dist/adapter-D9qrs60B.d.mts +61 -0
- package/dist/adapters/redis/index.d.mts +48 -0
- package/dist/adapters/redis/index.mjs +177 -0
- package/dist/adapters/s3-express/index.d.mts +65 -0
- package/dist/adapters/s3-express/index.mjs +719 -0
- package/dist/ai-sdk/index.d.mts +23 -0
- package/dist/ai-sdk/index.mjs +37 -0
- package/dist/core-BteCDwPY.mjs +124 -0
- package/dist/core-CE_FvT5z.d.mts +76 -0
- package/dist/index.d.mts +3 -78
- package/dist/index.mjs +2 -195
- package/package.json +24 -5
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { n as StreamCodec } from "../adapter-D9qrs60B.mjs";
|
|
2
|
+
import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-CE_FvT5z.mjs";
|
|
3
|
+
import { UIMessageChunk } from "ai";
|
|
4
|
+
//#region src/ai-sdk/index.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Serializes UI message chunks as JSON and validates them on the way back.
|
|
7
|
+
*
|
|
8
|
+
* Chunks are validated rather than trusted because they may have been written by an
|
|
9
|
+
* older version of the application. A chunk that no longer parses is dropped instead
|
|
10
|
+
* of failing the resume.
|
|
11
|
+
*/
|
|
12
|
+
declare const uiMessageChunkCodec: StreamCodec<UIMessageChunk>;
|
|
13
|
+
type CreateResumableUIMessageStreamOptions = Omit<CreateResumableStreamOptions<UIMessageChunk>, `codec`>;
|
|
14
|
+
/**
|
|
15
|
+
* Creates a resumable stream context for AI SDK UI message streams.
|
|
16
|
+
*/
|
|
17
|
+
declare function createResumableUIMessageStream(options: CreateResumableUIMessageStreamOptions): {
|
|
18
|
+
startStream: (source: ReadableStream<UIMessageChunk>, startOptions?: StartStreamOptions) => Promise<StartStreamResult<UIMessageChunk>>;
|
|
19
|
+
resumeStream: (options: ResumeStreamOptions) => Promise<import("ai").AsyncIterableStream<UIMessageChunk> | null>;
|
|
20
|
+
stopStream: (options: StopStreamOptions) => Promise<void>;
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { CreateResumableUIMessageStreamOptions, createResumableUIMessageStream, uiMessageChunkCodec };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { t as createResumableStream } from "../core-BteCDwPY.mjs";
|
|
2
|
+
import { asSchema, uiMessageChunkSchema } from "ai";
|
|
3
|
+
//#region src/ai-sdk/index.ts
|
|
4
|
+
const schema = asSchema(uiMessageChunkSchema);
|
|
5
|
+
/**
|
|
6
|
+
* Serializes UI message chunks as JSON and validates them on the way back.
|
|
7
|
+
*
|
|
8
|
+
* Chunks are validated rather than trusted because they may have been written by an
|
|
9
|
+
* older version of the application. A chunk that no longer parses is dropped instead
|
|
10
|
+
* of failing the resume.
|
|
11
|
+
*/
|
|
12
|
+
const uiMessageChunkCodec = {
|
|
13
|
+
encode(chunk) {
|
|
14
|
+
return JSON.stringify(chunk);
|
|
15
|
+
},
|
|
16
|
+
async decode(data) {
|
|
17
|
+
let value;
|
|
18
|
+
try {
|
|
19
|
+
value = JSON.parse(data);
|
|
20
|
+
} catch {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const result = await schema.validate(value);
|
|
24
|
+
return result.success ? result.value : void 0;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Creates a resumable stream context for AI SDK UI message streams.
|
|
29
|
+
*/
|
|
30
|
+
function createResumableUIMessageStream(options) {
|
|
31
|
+
return createResumableStream({
|
|
32
|
+
...options,
|
|
33
|
+
codec: uiMessageChunkCodec
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { createResumableUIMessageStream, uiMessageChunkCodec };
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { createAsyncIterableStream } from "ai-stream-utils";
|
|
2
|
+
//#region src/core.ts
|
|
3
|
+
/**
|
|
4
|
+
* Ignores teardown failures so they never mask the original outcome.
|
|
5
|
+
*/
|
|
6
|
+
async function ignoreErrors(fn) {
|
|
7
|
+
try {
|
|
8
|
+
await fn();
|
|
9
|
+
} catch {}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Creates a resumable stream context bound to a storage adapter and a chunk codec.
|
|
13
|
+
*
|
|
14
|
+
* The returned stream is drained once and fanned out to two consumers: the client
|
|
15
|
+
* that started it, and the adapter. The two are independent, so a client that
|
|
16
|
+
* disconnects mid-stream neither stops nor corrupts persistence.
|
|
17
|
+
*/
|
|
18
|
+
function createResumableStream(options) {
|
|
19
|
+
const { adapter, codec, waitUntil, generateId = () => crypto.randomUUID() } = options;
|
|
20
|
+
async function startStream(source, startOptions = {}) {
|
|
21
|
+
const { streamId = generateId(), abortController = new AbortController(), onFinish } = startOptions;
|
|
22
|
+
const unsubscribe = await adapter.onStopRequested({
|
|
23
|
+
streamId,
|
|
24
|
+
onStop: () => abortController.abort()
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* Chunks for the client, exactly as produced. Cancelling stops the client fan-out
|
|
28
|
+
* but leaves the drain loop running so the adapter still receives every chunk.
|
|
29
|
+
*/
|
|
30
|
+
let clientCancelled = false;
|
|
31
|
+
let clientController;
|
|
32
|
+
const clientStream = new ReadableStream({
|
|
33
|
+
start(controller) {
|
|
34
|
+
clientController = controller;
|
|
35
|
+
},
|
|
36
|
+
cancel() {
|
|
37
|
+
clientCancelled = true;
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* Serialized chunks for the adapter.
|
|
42
|
+
*/
|
|
43
|
+
let adapterController;
|
|
44
|
+
const adapterStream = new ReadableStream({ start(controller) {
|
|
45
|
+
adapterController = controller;
|
|
46
|
+
} });
|
|
47
|
+
/**
|
|
48
|
+
* Acquired before registration so a locked source fails before any state is written.
|
|
49
|
+
*/
|
|
50
|
+
const reader = source.getReader();
|
|
51
|
+
try {
|
|
52
|
+
await adapter.createStream({
|
|
53
|
+
streamId,
|
|
54
|
+
chunks: adapterStream,
|
|
55
|
+
waitUntil
|
|
56
|
+
});
|
|
57
|
+
} catch (error) {
|
|
58
|
+
reader.releaseLock();
|
|
59
|
+
await ignoreErrors(unsubscribe);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Cancelling the source resolves any pending read as done, which ends the drain
|
|
64
|
+
* loop, and propagates upstream so the producer stops doing work.
|
|
65
|
+
*/
|
|
66
|
+
abortController.signal.addEventListener(`abort`, () => {
|
|
67
|
+
reader.cancel().catch(() => {
|
|
68
|
+
/** The source is already gone */
|
|
69
|
+
});
|
|
70
|
+
}, { once: true });
|
|
71
|
+
const drained = (async () => {
|
|
72
|
+
try {
|
|
73
|
+
while (true) {
|
|
74
|
+
const { done, value } = await reader.read();
|
|
75
|
+
if (done) {
|
|
76
|
+
if (!clientCancelled) clientController.close();
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
adapterController.enqueue(codec.encode(value));
|
|
80
|
+
if (!clientCancelled) clientController.enqueue(value);
|
|
81
|
+
}
|
|
82
|
+
} catch (error) {
|
|
83
|
+
adapterController.error(error);
|
|
84
|
+
if (!clientCancelled) clientController.error(error);
|
|
85
|
+
} finally {
|
|
86
|
+
reader.releaseLock();
|
|
87
|
+
await ignoreErrors(unsubscribe);
|
|
88
|
+
await ignoreErrors(() => adapterController.close());
|
|
89
|
+
await ignoreErrors(() => onFinish?.());
|
|
90
|
+
}
|
|
91
|
+
})();
|
|
92
|
+
waitUntil?.(drained);
|
|
93
|
+
return {
|
|
94
|
+
streamId,
|
|
95
|
+
stream: createAsyncIterableStream(clientStream)
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Returns the chunks of an in-flight stream, starting from the first one it produced,
|
|
100
|
+
* or `null` when there is nothing to resume.
|
|
101
|
+
*/
|
|
102
|
+
async function resumeStream(options) {
|
|
103
|
+
const encoded = await adapter.resumeStream({ streamId: options.streamId });
|
|
104
|
+
if (!encoded) return null;
|
|
105
|
+
return createAsyncIterableStream(encoded.pipeThrough(new TransformStream({ async transform(data, controller) {
|
|
106
|
+
const chunk = await codec.decode(data);
|
|
107
|
+
if (chunk !== void 0) controller.enqueue(chunk);
|
|
108
|
+
} })));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Asks the process producing the stream to stop. Resolves once the request is
|
|
112
|
+
* recorded, which may be before the producer has observed it.
|
|
113
|
+
*/
|
|
114
|
+
async function stopStream(options) {
|
|
115
|
+
await adapter.requestStop({ streamId: options.streamId });
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
startStream,
|
|
119
|
+
resumeStream,
|
|
120
|
+
stopStream
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
export { createResumableStream as t };
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { n as StreamCodec, t as StreamAdapter } from "./adapter-D9qrs60B.mjs";
|
|
2
|
+
import { AsyncIterableStream } from "ai-stream-utils";
|
|
3
|
+
//#region src/core.d.ts
|
|
4
|
+
type StartStreamOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* A stable identifier for the stream, used to resume and to stop it.
|
|
7
|
+
* Defaults to a generated id.
|
|
8
|
+
*
|
|
9
|
+
* Passing an id the caller already owns (a chat id, a message id) removes the need
|
|
10
|
+
* to track a separate pointer. Reusing an id discards the previous stream's chunks.
|
|
11
|
+
*/
|
|
12
|
+
streamId?: string;
|
|
13
|
+
/**
|
|
14
|
+
* The controller aborted when the stream is stopped. Created if not supplied, so a
|
|
15
|
+
* stream is always stoppable.
|
|
16
|
+
*
|
|
17
|
+
* Supply one when the producer needs the signal, for example to pass it to
|
|
18
|
+
* `streamText({ abortSignal })`, so the provider request is aborted directly instead
|
|
19
|
+
* of relying on stream cancellation propagating upstream.
|
|
20
|
+
*/
|
|
21
|
+
abortController?: AbortController;
|
|
22
|
+
/**
|
|
23
|
+
* Called once the source has ended and the adapter has been told the stream is
|
|
24
|
+
* complete. Runs on every exit path, including errors and stops. Errors are ignored.
|
|
25
|
+
*/
|
|
26
|
+
onFinish?: () => void | Promise<void>;
|
|
27
|
+
};
|
|
28
|
+
type ResumeStreamOptions = {
|
|
29
|
+
/**
|
|
30
|
+
* The id the stream was started under.
|
|
31
|
+
*/
|
|
32
|
+
streamId: string;
|
|
33
|
+
};
|
|
34
|
+
type StopStreamOptions = {
|
|
35
|
+
/**
|
|
36
|
+
* The id of the stream to stop.
|
|
37
|
+
*/
|
|
38
|
+
streamId: string;
|
|
39
|
+
};
|
|
40
|
+
type StartStreamResult<CHUNK> = {
|
|
41
|
+
/**
|
|
42
|
+
* The id the stream was registered under, whether supplied or generated.
|
|
43
|
+
*/
|
|
44
|
+
streamId: string;
|
|
45
|
+
/**
|
|
46
|
+
* The chunks, for the client that started the stream. Cancelling it does not stop
|
|
47
|
+
* persistence, so a disconnected client can still resume.
|
|
48
|
+
*/
|
|
49
|
+
stream: AsyncIterableStream<CHUNK>;
|
|
50
|
+
};
|
|
51
|
+
type CreateResumableStreamOptions<CHUNK> = {
|
|
52
|
+
adapter: StreamAdapter;
|
|
53
|
+
codec: StreamCodec<CHUNK>;
|
|
54
|
+
/**
|
|
55
|
+
* Keeps the host process alive until persistence finishes. Omit on long-lived servers.
|
|
56
|
+
*/
|
|
57
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
58
|
+
/**
|
|
59
|
+
* Generates a stream id when `startStream` is not given one.
|
|
60
|
+
*/
|
|
61
|
+
generateId?: () => string;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Creates a resumable stream context bound to a storage adapter and a chunk codec.
|
|
65
|
+
*
|
|
66
|
+
* The returned stream is drained once and fanned out to two consumers: the client
|
|
67
|
+
* that started it, and the adapter. The two are independent, so a client that
|
|
68
|
+
* disconnects mid-stream neither stops nor corrupts persistence.
|
|
69
|
+
*/
|
|
70
|
+
declare function createResumableStream<CHUNK>(options: CreateResumableStreamOptions<CHUNK>): {
|
|
71
|
+
startStream: (source: ReadableStream<CHUNK>, startOptions?: StartStreamOptions) => Promise<StartStreamResult<CHUNK>>;
|
|
72
|
+
resumeStream: (options: ResumeStreamOptions) => Promise<AsyncIterableStream<CHUNK> | null>;
|
|
73
|
+
stopStream: (options: StopStreamOptions) => Promise<void>;
|
|
74
|
+
};
|
|
75
|
+
//#endregion
|
|
76
|
+
export { StopStreamOptions as a, StartStreamResult as i, ResumeStreamOptions as n, createResumableStream as o, StartStreamOptions as r, CreateResumableStreamOptions as t };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,78 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/resumable-ui-message-stream.d.ts
|
|
5
|
-
/**
|
|
6
|
-
* A Redis client, described by the commands this library actually calls rather than
|
|
7
|
-
* by the client type of a specific `redis` release. The generic parameters of
|
|
8
|
-
* `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
|
|
9
|
-
* type would pin consumers to one of them.
|
|
10
|
-
*/
|
|
11
|
-
type Redis = Publisher & Subscriber & {
|
|
12
|
-
isOpen: boolean;
|
|
13
|
-
};
|
|
14
|
-
type CreateResumableUIMessageStream = {
|
|
15
|
-
/**
|
|
16
|
-
* A unique identifier for the stream.
|
|
17
|
-
*/
|
|
18
|
-
streamId: string;
|
|
19
|
-
/**
|
|
20
|
-
* A Redis client from the `redis` package.
|
|
21
|
-
* Checks if the client is already connected before attempting to connect.
|
|
22
|
-
*/
|
|
23
|
-
subscriber: Redis;
|
|
24
|
-
/**
|
|
25
|
-
* A Redis client from the `redis` package.
|
|
26
|
-
* Checks if the client is already connected before attempting to connect.
|
|
27
|
-
*/
|
|
28
|
-
publisher: Redis;
|
|
29
|
-
/**
|
|
30
|
-
* An optional AbortController that, when provided, allows the stream to be stopped by aborting the controller.
|
|
31
|
-
* If not provided, the stream will not be stoppable.
|
|
32
|
-
*/
|
|
33
|
-
abortController?: AbortController;
|
|
34
|
-
/**
|
|
35
|
-
* A function that takes a promise and ensures that the current program stays alive
|
|
36
|
-
* until the promise is resolved.
|
|
37
|
-
*
|
|
38
|
-
* Omit if you are deploying to a server environment, where you don't have to worry about
|
|
39
|
-
* the function getting suspended.
|
|
40
|
-
*/
|
|
41
|
-
waitUntil?: (promise: Promise<unknown>) => void;
|
|
42
|
-
};
|
|
43
|
-
type StartStreamOptions = {
|
|
44
|
-
/**
|
|
45
|
-
* A promise that is awaited before closing the Redis stream, keeping the
|
|
46
|
-
* resumable-stream producer alive so late resume requests can be served
|
|
47
|
-
* from the in-memory buffer. The producer tears down when the promise resolves.
|
|
48
|
-
*
|
|
49
|
-
* Use `Promise.withResolvers()` to create a deferred promise and resolve it
|
|
50
|
-
* after post-stream work (e.g. DB writes) is complete:
|
|
51
|
-
* ```ts
|
|
52
|
-
* const { promise, resolve } = Promise.withResolvers<void>();
|
|
53
|
-
* const stream = await ctx.startStream(input, { keepAlive: promise });
|
|
54
|
-
* for await (const chunk of stream) { ... }
|
|
55
|
-
* await saveToDb();
|
|
56
|
-
* resolve();
|
|
57
|
-
* ```
|
|
58
|
-
*/
|
|
59
|
-
keepAlive?: Promise<void>;
|
|
60
|
-
/**
|
|
61
|
-
* Called after the Redis stream is closed and the producer has torn down.
|
|
62
|
-
* Use for post-teardown cleanup.
|
|
63
|
-
*/
|
|
64
|
-
onFlush?: () => void | Promise<void>;
|
|
65
|
-
};
|
|
66
|
-
/**
|
|
67
|
-
* Creates a resumable context for starting, resuming and stopping UI message streams.
|
|
68
|
-
*
|
|
69
|
-
* Leverages resumable-stream's internal eager drain pattern which drains the source
|
|
70
|
-
* eagerly and enqueues directly to the output stream.
|
|
71
|
-
*/
|
|
72
|
-
declare function createResumableUIMessageStream(options: CreateResumableUIMessageStream): Promise<{
|
|
73
|
-
startStream: (stream: ReadableStream<UIMessageChunk>, options?: StartStreamOptions) => Promise<AsyncIterableStream<UIMessageChunk>>;
|
|
74
|
-
resumeStream: () => Promise<AsyncIterableStream<UIMessageChunk> | null>;
|
|
75
|
-
stopStream: () => Promise<void>;
|
|
76
|
-
}>;
|
|
77
|
-
//#endregion
|
|
78
|
-
export { createResumableUIMessageStream };
|
|
1
|
+
import { n as StreamCodec, t as StreamAdapter } from "./adapter-D9qrs60B.mjs";
|
|
2
|
+
import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-CE_FvT5z.mjs";
|
|
3
|
+
export { CreateResumableStreamOptions, ResumeStreamOptions, StartStreamOptions, StartStreamResult, StopStreamOptions, type StreamAdapter, type StreamCodec, createResumableStream };
|
package/dist/index.mjs
CHANGED
|
@@ -1,195 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { createResumableStreamContext } from "resumable-stream";
|
|
4
|
-
//#region src/convert-sse-stream-to-ui-message-stream.ts
|
|
5
|
-
/**
|
|
6
|
-
* Converts an SSE stream to a UI message stream.
|
|
7
|
-
*/
|
|
8
|
-
function convertSSEToUIMessageStream(stream, onFlush) {
|
|
9
|
-
return parseJsonEventStream({
|
|
10
|
-
stream: stream.pipeThrough(new TextEncoderStream()),
|
|
11
|
-
schema: uiMessageChunkSchema
|
|
12
|
-
}).pipeThrough(new TransformStream({
|
|
13
|
-
transform(result, controller) {
|
|
14
|
-
if (result.success) controller.enqueue(result.value);
|
|
15
|
-
},
|
|
16
|
-
flush() {
|
|
17
|
-
onFlush?.();
|
|
18
|
-
}
|
|
19
|
-
}));
|
|
20
|
-
}
|
|
21
|
-
//#endregion
|
|
22
|
-
//#region src/resumable-ui-message-stream.ts
|
|
23
|
-
const KEY_PREFIX = `ai-resumable-stream`;
|
|
24
|
-
/**
|
|
25
|
-
* Creates a resumable context for starting, resuming and stopping UI message streams.
|
|
26
|
-
*
|
|
27
|
-
* Leverages resumable-stream's internal eager drain pattern which drains the source
|
|
28
|
-
* eagerly and enqueues directly to the output stream.
|
|
29
|
-
*/
|
|
30
|
-
async function createResumableUIMessageStream(options) {
|
|
31
|
-
const { streamId, abortController, publisher, subscriber, waitUntil = null } = options;
|
|
32
|
-
const stopChannel = `${KEY_PREFIX}:stop:${streamId}`;
|
|
33
|
-
const context = createResumableStreamContext({
|
|
34
|
-
waitUntil,
|
|
35
|
-
publisher,
|
|
36
|
-
subscriber,
|
|
37
|
-
keyPrefix: KEY_PREFIX
|
|
38
|
-
});
|
|
39
|
-
await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
|
|
40
|
-
/**
|
|
41
|
-
* Unsubscribe from stop channel
|
|
42
|
-
*/
|
|
43
|
-
async function unsubscribe() {
|
|
44
|
-
if (!abortController) return;
|
|
45
|
-
await subscriber.unsubscribe(stopChannel);
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Set up stop subscription if abortController provided
|
|
49
|
-
*/
|
|
50
|
-
if (abortController) {
|
|
51
|
-
await subscriber.subscribe(stopChannel, () => {
|
|
52
|
-
abortController.abort();
|
|
53
|
-
});
|
|
54
|
-
/**
|
|
55
|
-
* Cleanup when abort signal fires
|
|
56
|
-
*/
|
|
57
|
-
abortController.signal.addEventListener(`abort`, () => {
|
|
58
|
-
unsubscribe();
|
|
59
|
-
}, { once: true });
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Start a new stream by creating a new resumable stream in Redis and returning a client stream for the UI.
|
|
63
|
-
*
|
|
64
|
-
* Uses a single drain loop that:
|
|
65
|
-
* 1. Reads from source stream
|
|
66
|
-
* 2. Sends UIMessageChunk directly to client stream (no conversion)
|
|
67
|
-
* 3. Sends SSE to Redis stream → resumable-stream → Redis
|
|
68
|
-
* 4. If `keepAlive` is provided, awaits it before closing the Redis stream
|
|
69
|
-
* 5. Closes the Redis stream, triggering resumable-stream teardown
|
|
70
|
-
* 6. Calls `onFlush` after teardown
|
|
71
|
-
* 7. Propagates errors to both streams
|
|
72
|
-
*/
|
|
73
|
-
async function startStream(stream, options) {
|
|
74
|
-
const { keepAlive = Promise.resolve(), onFlush } = options ?? {};
|
|
75
|
-
/**
|
|
76
|
-
* Track client disconnect to avoid unbounded memory growth
|
|
77
|
-
*/
|
|
78
|
-
let clientCancelled = false;
|
|
79
|
-
/**
|
|
80
|
-
* Client stream for sending UI message chunks directly to the client without conversion.
|
|
81
|
-
*/
|
|
82
|
-
let clientController;
|
|
83
|
-
const clientStream = new ReadableStream({
|
|
84
|
-
start(controller) {
|
|
85
|
-
clientController = controller;
|
|
86
|
-
},
|
|
87
|
-
cancel() {
|
|
88
|
-
clientCancelled = true;
|
|
89
|
-
}
|
|
90
|
-
});
|
|
91
|
-
/**
|
|
92
|
-
* Redis stream with SSE conversion for resumable-stream persistence in Redis.
|
|
93
|
-
* JsonToSseTransformStream converts UIMessageChunk → SSE string and adds [DONE] on flush.
|
|
94
|
-
*/
|
|
95
|
-
let redisController;
|
|
96
|
-
const redisStream = new ReadableStream({ start(controller) {
|
|
97
|
-
redisController = controller;
|
|
98
|
-
} }).pipeThrough(new JsonToSseTransformStream());
|
|
99
|
-
/**
|
|
100
|
-
* Get reader synchronously to fail fast if stream is locked
|
|
101
|
-
*/
|
|
102
|
-
const reader = stream.getReader();
|
|
103
|
-
/**
|
|
104
|
-
* Register Redis stream with resumable-stream for persistence.
|
|
105
|
-
* Release reader lock if registration fails to avoid locking the source stream.
|
|
106
|
-
*/
|
|
107
|
-
try {
|
|
108
|
-
await context.createNewResumableStream(streamId, () => redisStream);
|
|
109
|
-
} catch (error) {
|
|
110
|
-
reader.releaseLock();
|
|
111
|
-
throw error;
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Single drain loop.
|
|
115
|
-
* Continues draining to Redis even if client disconnects
|
|
116
|
-
*/
|
|
117
|
-
(async () => {
|
|
118
|
-
/**
|
|
119
|
-
* Tracks whether the source stream completed successfully (reader.read() returned done: true).
|
|
120
|
-
* Used to guard the keepAlive await in finally — on error, the caller may never resolve
|
|
121
|
-
* the keepAlive promise, so awaiting it would hang the drain loop forever.
|
|
122
|
-
*/
|
|
123
|
-
let sourceDone = false;
|
|
124
|
-
try {
|
|
125
|
-
while (true) {
|
|
126
|
-
const { done, value } = await reader.read();
|
|
127
|
-
if (done) {
|
|
128
|
-
if (!clientCancelled) clientController.close();
|
|
129
|
-
sourceDone = true;
|
|
130
|
-
break;
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Always enqueue to Redis for persistence
|
|
134
|
-
*/
|
|
135
|
-
redisController.enqueue(value);
|
|
136
|
-
/**
|
|
137
|
-
* Only enqueue to client if still connected to avoid unbounded memory growth.
|
|
138
|
-
*
|
|
139
|
-
*/
|
|
140
|
-
if (!clientCancelled) clientController.enqueue(value);
|
|
141
|
-
}
|
|
142
|
-
} catch (error) {
|
|
143
|
-
redisController.error(error);
|
|
144
|
-
if (!clientCancelled) clientController.error(error);
|
|
145
|
-
} finally {
|
|
146
|
-
reader.releaseLock();
|
|
147
|
-
try {
|
|
148
|
-
await unsubscribe();
|
|
149
|
-
} catch {}
|
|
150
|
-
/**
|
|
151
|
-
* Await keepAlive promise before closing the Redis stream.
|
|
152
|
-
* This keeps the resumable-stream producer alive so late resume requests
|
|
153
|
-
* can be served from the in-memory chunk buffer.
|
|
154
|
-
* Defaults to a resolved promise (no-op) when not provided.
|
|
155
|
-
* Only await on successful source completion — on error the caller
|
|
156
|
-
* may never resolve the promise, which would hang the drain loop.
|
|
157
|
-
*/
|
|
158
|
-
if (sourceDone) try {
|
|
159
|
-
await keepAlive;
|
|
160
|
-
} catch {}
|
|
161
|
-
try {
|
|
162
|
-
redisController.close();
|
|
163
|
-
} catch {}
|
|
164
|
-
try {
|
|
165
|
-
await onFlush?.();
|
|
166
|
-
} catch {}
|
|
167
|
-
}
|
|
168
|
-
})();
|
|
169
|
-
return createAsyncIterableStream(clientStream);
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Resume an existing stream by fetching the resumable stream from Redis using the stream ID.
|
|
173
|
-
*/
|
|
174
|
-
async function resumeStream() {
|
|
175
|
-
/**
|
|
176
|
-
* Resume the existing stream from Redis using the stream ID.
|
|
177
|
-
*/
|
|
178
|
-
const resumableStream = await context.resumeExistingStream(streamId);
|
|
179
|
-
if (!resumableStream) return null;
|
|
180
|
-
return createAsyncIterableStream(convertSSEToUIMessageStream(resumableStream));
|
|
181
|
-
}
|
|
182
|
-
/**
|
|
183
|
-
* Publish a stop message to the stop channel, which will trigger the abortController to abort the stream.
|
|
184
|
-
*/
|
|
185
|
-
async function stopStream() {
|
|
186
|
-
await publisher.publish(stopChannel, `stop`);
|
|
187
|
-
}
|
|
188
|
-
return {
|
|
189
|
-
startStream,
|
|
190
|
-
resumeStream,
|
|
191
|
-
stopStream
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
//#endregion
|
|
195
|
-
export { createResumableUIMessageStream };
|
|
1
|
+
import { t as createResumableStream } from "./core-BteCDwPY.mjs";
|
|
2
|
+
export { createResumableStream };
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-resumable-stream",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "AI SDK
|
|
3
|
+
"version": "3.0.0",
|
|
4
|
+
"description": "Resume and stop AI SDK streams, backed by S3, Redis, or any store you provide",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
7
7
|
"ai-sdk",
|
|
8
8
|
"redis",
|
|
9
9
|
"resumable",
|
|
10
10
|
"resumable-stream",
|
|
11
|
+
"s3",
|
|
11
12
|
"stream"
|
|
12
13
|
],
|
|
13
14
|
"license": "MIT",
|
|
@@ -23,6 +24,9 @@
|
|
|
23
24
|
"types": "./dist/index.d.mts",
|
|
24
25
|
"exports": {
|
|
25
26
|
".": "./dist/index.mjs",
|
|
27
|
+
"./adapters/redis": "./dist/adapters/redis/index.mjs",
|
|
28
|
+
"./adapters/s3-express": "./dist/adapters/s3-express/index.mjs",
|
|
29
|
+
"./ai-sdk": "./dist/ai-sdk/index.mjs",
|
|
26
30
|
"./package.json": "./package.json"
|
|
27
31
|
},
|
|
28
32
|
"dependencies": {
|
|
@@ -32,6 +36,7 @@
|
|
|
32
36
|
"devDependencies": {
|
|
33
37
|
"@ai-sdk/provider": "^4.0.3",
|
|
34
38
|
"@arethetypeswrong/cli": "^0.18.5",
|
|
39
|
+
"@aws-sdk/client-s3": "^3.1131.0",
|
|
35
40
|
"@total-typescript/tsconfig": "^1.0.4",
|
|
36
41
|
"@types/node": "^26.1.1",
|
|
37
42
|
"@vitest/coverage-v8": "^4.1.10",
|
|
@@ -39,7 +44,6 @@
|
|
|
39
44
|
"ai-test-kit": "^3.0.1",
|
|
40
45
|
"husky": "^9.1.7",
|
|
41
46
|
"lint-staged": "^17.0.8",
|
|
42
|
-
"mitata": "^1.0.34",
|
|
43
47
|
"oxfmt": "^0.58.0",
|
|
44
48
|
"oxlint": "^1.73.0",
|
|
45
49
|
"pkg-pr-new": "^0.0.75",
|
|
@@ -49,15 +53,27 @@
|
|
|
49
53
|
"redis-v5": "npm:redis@^5.12.1",
|
|
50
54
|
"redis-v6": "npm:redis@^6.1.0",
|
|
51
55
|
"tsdown": "^0.22.7",
|
|
52
|
-
"tsx": "^4.23.
|
|
56
|
+
"tsx": "^4.23.13",
|
|
53
57
|
"typescript": "^7.0.2",
|
|
54
58
|
"vitest": "^4.1.10",
|
|
55
59
|
"zod": "^4.4.3"
|
|
56
60
|
},
|
|
57
61
|
"peerDependencies": {
|
|
62
|
+
"@aws-sdk/client-s3": "^3.700.0",
|
|
58
63
|
"ai": "^7.0.0",
|
|
59
64
|
"redis": "^5.0.0 || ^6.0.0"
|
|
60
65
|
},
|
|
66
|
+
"peerDependenciesMeta": {
|
|
67
|
+
"@aws-sdk/client-s3": {
|
|
68
|
+
"optional": true
|
|
69
|
+
},
|
|
70
|
+
"ai": {
|
|
71
|
+
"optional": true
|
|
72
|
+
},
|
|
73
|
+
"redis": {
|
|
74
|
+
"optional": true
|
|
75
|
+
}
|
|
76
|
+
},
|
|
61
77
|
"lint-staged": {
|
|
62
78
|
"*.{js,ts,tsx,jsx}": [
|
|
63
79
|
"pnpm lint",
|
|
@@ -69,8 +85,11 @@
|
|
|
69
85
|
},
|
|
70
86
|
"scripts": {
|
|
71
87
|
"build": "tsdown",
|
|
72
|
-
"test": "vitest",
|
|
88
|
+
"test": "vitest run",
|
|
89
|
+
"test:watch": "vitest",
|
|
73
90
|
"typecheck": "tsc --noEmit",
|
|
91
|
+
"example:redis": "tsx examples/redis.ts",
|
|
92
|
+
"example:s3-express": "tsx examples/s3-express.ts",
|
|
74
93
|
"lint": "oxlint --fix",
|
|
75
94
|
"lint:ci": "oxlint",
|
|
76
95
|
"format": "oxfmt --write",
|