ai-resumable-stream 3.4.0 → 3.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.
package/README.md CHANGED
@@ -65,7 +65,7 @@ const context = createResumableUIMessageStream({
65
65
  Then use the context in your three routes:
66
66
 
67
67
  ```ts
68
- import { streamText, toUIMessageStream, type UIMessage } from "ai";
68
+ import { createUIMessageStreamResponse, streamText, toUIMessageStream, type UIMessage } from "ai";
69
69
 
70
70
  // POST /chat/:chatId
71
71
  export async function send(chatId: string, messages: Array<UIMessage>) {
@@ -82,14 +82,15 @@ export async function send(chatId: string, messages: Array<UIMessage>) {
82
82
  abortController,
83
83
  });
84
84
 
85
- return stream;
85
+ return createUIMessageStreamResponse({ stream });
86
86
  }
87
87
 
88
88
  // GET /chat/:chatId/stream
89
89
  export async function resume(chatId: string) {
90
90
  const stream = await context.resumeStream({ streamId: chatId });
91
+ if (!stream) return new Response(null, { status: 204 });
91
92
 
92
- return stream ?? new Response(null, { status: 204 });
93
+ return createUIMessageStreamResponse({ stream });
93
94
  }
94
95
 
95
96
  // POST /chat/:chatId/stop
@@ -199,11 +200,14 @@ async function resumeMessage(chatId: string) {
199
200
  Pass the `signal` of the incoming request. If the client goes away, the resume ends at once and frees its resources, also while it still waits for the first chunk of the producer. The signal applies to the full resume, until the stream ends. Before `resumeStream` returns, the promise rejects with the reason of the signal. After that, the returned stream errors with it.
200
201
 
201
202
  ```ts
203
+ import { createUIMessageStreamResponse } from "ai";
204
+
202
205
  // GET /chat/:chatId/stream
203
206
  export async function resume(chatId: string, request: Request) {
204
207
  const stream = await context.resumeStream({ streamId: chatId, signal: request.signal });
208
+ if (!stream) return new Response(null, { status: 204 });
205
209
 
206
- return stream ?? new Response(null, { status: 204 });
210
+ return createUIMessageStreamResponse({ stream });
207
211
  }
208
212
  ```
209
213
 
@@ -289,7 +293,7 @@ Use an id that the client already knows, for example the id of the user message
289
293
  This adapter requires two Redis clients, because pub/sub needs a separate connection. The library connects the clients if they are not connected yet, but it never disconnects them. You manage the connection lifecycle in your application and can reuse the clients for all streams.
290
294
 
291
295
  > [!NOTE]
292
- > You need to install `redis` to use this adapter. Both v5 and v6 are supported.
296
+ > This adapter needs a Redis client. Supported clients are `redis` v5 and v6 and the client built into Bun. See [Installation](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-redis.md#installation).
293
297
 
294
298
  ```ts
295
299
  import { createClient } from "redis";
@@ -1,15 +1,15 @@
1
1
  import { t as StreamAdapter } from "../../adapter-DZmSMkrn.mjs";
2
- //#region src/adapters/redis/adapter.d.ts
2
+ //#region src/adapters/redis/client.d.ts
3
3
  /**
4
- * A Redis client, described by the commands this adapter actually calls rather than by
5
- * the client type of a specific `redis` release. The generic parameters of
6
- * `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
7
- * type would pin consumers to one of them.
4
+ * A client from the `redis` package, described by the commands the adapter actually calls
5
+ * rather than by the client type of a specific `redis` release. The generic parameters of
6
+ * `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal type
7
+ * would pin consumers to one of them.
8
8
  *
9
9
  * `unsubscribe` takes the listener because a listener removes itself alone, never every
10
10
  * listener of its channel.
11
11
  */
12
- type Redis = {
12
+ type NodeRedis = {
13
13
  isOpen: boolean;
14
14
  connect(): Promise<unknown>;
15
15
  publish(channel: string, message: string): Promise<unknown>;
@@ -28,16 +28,38 @@ type Redis = {
28
28
  arguments?: Array<string>;
29
29
  }): Promise<unknown>;
30
30
  };
31
+ /**
32
+ * The client built into Bun (`Bun.RedisClient`), described by the commands the adapter
33
+ * calls, so that a consumer on Node does not need the types of Bun.
34
+ */
35
+ type BunRedis = {
36
+ readonly connected: boolean;
37
+ onconnect: (() => void) | null;
38
+ connect(): Promise<unknown>;
39
+ send(command: string, args: Array<string>): Promise<unknown>;
40
+ publish(channel: string, message: string): Promise<unknown>;
41
+ subscribe(channel: string, listener: BunListener): Promise<unknown>;
42
+ unsubscribe(channel: string, listener: BunListener): Promise<unknown>;
43
+ get(key: string): Promise<string | null>;
44
+ set(key: string, value: string): Promise<unknown>;
45
+ set(key: string, value: string, type: `EX` | `PX`, duration: number): Promise<unknown>;
46
+ del(key: string): Promise<unknown>;
47
+ };
48
+ type BunListener = (message: string, channel: string) => void;
49
+ type RedisClient = NodeRedis | BunRedis;
50
+ //#endregion
51
+ //#region src/adapters/redis/adapter.d.ts
31
52
  type CreateRedisAdapterOptions = {
32
53
  /**
33
- * A client from the `redis` package, used to publish chunks and stop requests.
54
+ * A client from the `redis` package or the client built into Bun (`Bun.RedisClient`),
55
+ * used to publish chunks and stop requests.
34
56
  * Connected on first use and never disconnected, so it stays reusable across streams.
35
57
  */
36
- publisher: Redis;
58
+ publisher: RedisClient;
37
59
  /**
38
60
  * A second client, required because a subscribed connection cannot issue commands.
39
61
  */
40
- subscriber: Redis;
62
+ subscriber: RedisClient;
41
63
  /**
42
64
  * Namespace for every key and channel this adapter touches.
43
65
  */
@@ -389,6 +389,175 @@ function resumeStream(ctx, streamId) {
389
389
  });
390
390
  }
391
391
  //#endregion
392
+ //#region src/adapters/redis/client.ts
393
+ /**
394
+ * The Bun client has `connected` in place of `isOpen`. The `isOpen` check comes first, so a
395
+ * `redis` client is never taken for a Bun client.
396
+ */
397
+ function isBunRedis(client) {
398
+ return !(`isOpen` in client) && `connected` in client && typeof client.send === `function`;
399
+ }
400
+ /**
401
+ * One wrapper per client, because a wrapper keeps the subscriptions of its client and
402
+ * hooks into its reconnects. A new adapter on the same clients must not add a second hook.
403
+ */
404
+ const bunWrappers = /* @__PURE__ */ new WeakMap();
405
+ /**
406
+ * Gives a client the commands of a `redis` client. A `redis` client is returned unchanged.
407
+ */
408
+ function toNodeRedis(client) {
409
+ if (!isBunRedis(client)) return client;
410
+ let wrapper = bunWrappers.get(client);
411
+ if (!wrapper) {
412
+ wrapper = wrapBunRedis(client);
413
+ bunWrappers.set(client, wrapper);
414
+ }
415
+ return wrapper;
416
+ }
417
+ /**
418
+ * Bun rejects an unsubscribe when the client is not in subscriber mode, sometimes with a
419
+ * synchronous throw. Then there is nothing to remove, as with a `redis` client.
420
+ */
421
+ async function unsubscribeQuietly({ client, channel, listener }) {
422
+ try {
423
+ await client.unsubscribe(channel, listener);
424
+ } catch (error) {
425
+ if (error?.code !== `ERR_REDIS_INVALID_STATE`) throw error;
426
+ }
427
+ }
428
+ /**
429
+ * Gives the expiry of `set` as positional arguments and sends `EVAL` through `send`.
430
+ *
431
+ * Subscriptions need more. After a reconnect, Bun keeps its listeners but does not
432
+ * subscribe again on the server, so no message arrives. And Bun keeps a list, not a set, of
433
+ * listeners: a second subscribe with the same listener calls it twice. So the wrapper keeps
434
+ * the listeners of each channel itself and gives Bun one listener for all channels. After
435
+ * each reconnect, it unsubscribes and subscribes that listener again for each channel that
436
+ * has listeners, also for a channel whose last subscribe failed.
437
+ *
438
+ * The calls for one channel run one after the other, and each call makes Bun match the
439
+ * listeners that the channel has at that time. So a subscribe and an unsubscribe that
440
+ * overlap, or a reconnect between them, cannot leave the channel in the wrong state.
441
+ */
442
+ function wrapBunRedis(client) {
443
+ const channels = /* @__PURE__ */ new Map();
444
+ const dispatch = (message, channel) => {
445
+ for (const listener of channels.get(channel)?.listeners ?? []) listener(message);
446
+ };
447
+ const reconcile = async ({ name, channel }) => {
448
+ if (channel.stale) {
449
+ await unsubscribeQuietly({
450
+ client,
451
+ channel: name,
452
+ listener: dispatch
453
+ });
454
+ channel.registered = false;
455
+ channel.stale = false;
456
+ }
457
+ if (channel.listeners.size > 0 && !channel.registered) {
458
+ await client.subscribe(name, dispatch);
459
+ channel.registered = true;
460
+ } else if (channel.listeners.size === 0 && channel.registered) {
461
+ await unsubscribeQuietly({
462
+ client,
463
+ channel: name,
464
+ listener: dispatch
465
+ });
466
+ channel.registered = false;
467
+ }
468
+ forgetIfUnused({
469
+ name,
470
+ channel
471
+ });
472
+ };
473
+ const forgetIfUnused = ({ name, channel }) => {
474
+ if (channel.listeners.size === 0 && !channel.registered && channels.get(name) === channel) channels.delete(name);
475
+ };
476
+ const enqueue = ({ name, channel }) => {
477
+ const result = channel.queue.then(() => reconcile({
478
+ name,
479
+ channel
480
+ }));
481
+ channel.queue = result.catch(() => {});
482
+ return result;
483
+ };
484
+ const channelOf = (name) => {
485
+ let channel = channels.get(name);
486
+ if (!channel) {
487
+ channel = {
488
+ listeners: /* @__PURE__ */ new Set(),
489
+ registered: false,
490
+ stale: false,
491
+ queue: Promise.resolve()
492
+ };
493
+ channels.set(name, channel);
494
+ }
495
+ return channel;
496
+ };
497
+ /**
498
+ * Restores before it calls the handler that was there before, so a handler that throws
499
+ * cannot stop the restore. On the first connect, no channel is registered yet, so there
500
+ * is nothing to restore.
501
+ */
502
+ const previous = client.onconnect;
503
+ client.onconnect = function() {
504
+ for (const [name, channel] of channels) {
505
+ if (channel.listeners.size === 0 && !channel.registered) continue;
506
+ channel.stale = true;
507
+ enqueue({
508
+ name,
509
+ channel
510
+ }).catch(() => {});
511
+ }
512
+ previous?.call(this);
513
+ };
514
+ return {
515
+ get isOpen() {
516
+ return client.connected;
517
+ },
518
+ connect: () => client.connect(),
519
+ publish: (channel, message) => client.publish(channel, message),
520
+ subscribe: (name, listener) => {
521
+ const channel = channelOf(name);
522
+ channel.listeners.add(listener);
523
+ /**
524
+ * A failed subscribe registers nothing, as with a `redis` client, so the caller does
525
+ * not have to unsubscribe the listener.
526
+ */
527
+ return enqueue({
528
+ name,
529
+ channel
530
+ }).catch((error) => {
531
+ channel.listeners.delete(listener);
532
+ forgetIfUnused({
533
+ name,
534
+ channel
535
+ });
536
+ throw error;
537
+ });
538
+ },
539
+ unsubscribe: (name, listener) => {
540
+ const channel = channels.get(name);
541
+ if (!channel) return Promise.resolve();
542
+ if (listener) channel.listeners.delete(listener);
543
+ else channel.listeners.clear();
544
+ return enqueue({
545
+ name,
546
+ channel
547
+ });
548
+ },
549
+ get: (key) => client.get(key),
550
+ set: (key, value, options) => options?.expiration ? client.set(key, value, options.expiration.type, options.expiration.value) : client.set(key, value),
551
+ del: (key) => client.del(key),
552
+ eval: (script, { keys = [], arguments: args = [] } = {}) => client.send(`EVAL`, [
553
+ script,
554
+ String(keys.length),
555
+ ...keys,
556
+ ...args
557
+ ])
558
+ };
559
+ }
560
+ //#endregion
392
561
  //#region src/adapters/redis/sse.ts
393
562
  /**
394
563
  * The runtime transports a stream of strings that it is free to concatenate and
@@ -470,9 +639,11 @@ const STOP_TTL_SECONDS = 3600;
470
639
  * durable adapter when a stream must outlive the process that started it.
471
640
  */
472
641
  function createRedisAdapter(options) {
473
- const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX, ackTimeoutMs, ttlSeconds, commandTimeoutMs, heartbeatMs } = options;
642
+ const { keyPrefix = DEFAULT_KEY_PREFIX, ackTimeoutMs, ttlSeconds, commandTimeoutMs, heartbeatMs } = options;
474
643
  if (heartbeatMs !== void 0 && !(heartbeatMs > 0)) throw new RangeError(`heartbeatMs must be greater than 0, got ${heartbeatMs}`);
475
644
  const expireAfterMs = options.expireAfterMs ?? (ttlSeconds === void 0 ? DEFAULT_EXPIRE_AFTER_MS : ttlSeconds * 1e3);
645
+ const publisher = toNodeRedis(options.publisher);
646
+ const subscriber = toNodeRedis(options.subscriber);
476
647
  /**
477
648
  * Rejects with a `CommandTimeoutError` when the call takes longer than
478
649
  * `commandTimeoutMs`. A late failure of the call is handled, so it is not an unhandled
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-resumable-stream",
3
- "version": "3.4.0",
3
+ "version": "3.5.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",
@@ -37,6 +37,7 @@
37
37
  "@arethetypeswrong/cli": "^0.18.5",
38
38
  "@aws-sdk/client-s3": "^3.1131.0",
39
39
  "@total-typescript/tsconfig": "^1.0.4",
40
+ "@types/bun": "^1.4.5",
40
41
  "@types/node": "^26.1.1",
41
42
  "@vitest/coverage-v8": "^4.1.10",
42
43
  "ai": "^7.0.22",
@@ -85,8 +86,9 @@
85
86
  "scripts": {
86
87
  "build": "tsdown",
87
88
  "test": "vitest run",
89
+ "test:bun": "bun test ./src/adapters/redis/compat.bun.test.ts",
88
90
  "test:watch": "vitest",
89
- "typecheck": "tsc --noEmit",
91
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.bun.json",
90
92
  "example:redis": "tsx examples/redis.ts",
91
93
  "example:s3-express": "tsx examples/s3-express.ts",
92
94
  "lint": "oxlint --fix",