react-websocket 4.22.1 → 4.22.3

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 (60) hide show
  1. package/dist/ag-ui.cjs +8 -9
  2. package/dist/ag-ui.cjs.map +1 -1
  3. package/dist/ag-ui.d.cts +3 -8
  4. package/dist/ag-ui.d.ts +0 -2
  5. package/dist/ag-ui.js +8 -9
  6. package/dist/ag-ui.js.map +1 -1
  7. package/dist/chaos.cjs +60 -13
  8. package/dist/chaos.cjs.map +1 -1
  9. package/dist/chaos.d.cts +1 -2
  10. package/dist/chaos.d.ts +1 -2
  11. package/dist/chaos.js +60 -13
  12. package/dist/chaos.js.map +1 -1
  13. package/dist/core.cjs +93 -65
  14. package/dist/core.cjs.map +1 -1
  15. package/dist/core.d.cts +4 -25
  16. package/dist/core.d.ts +4 -25
  17. package/dist/core.js +93 -65
  18. package/dist/core.js.map +1 -1
  19. package/dist/devtools.cjs +1 -2
  20. package/dist/devtools.d.cts +0 -2
  21. package/dist/devtools.d.ts +0 -2
  22. package/dist/devtools.js +1 -2
  23. package/dist/index.cjs +1 -2
  24. package/dist/index.d.cts +4 -31
  25. package/dist/index.d.ts +3 -24
  26. package/dist/index.development.cjs +1 -2
  27. package/dist/index.development.js +1 -2
  28. package/dist/index.js +1 -2
  29. package/dist/outbox.cjs +15 -10
  30. package/dist/outbox.cjs.map +1 -1
  31. package/dist/outbox.d.cts +1 -3
  32. package/dist/outbox.d.ts +0 -2
  33. package/dist/outbox.js +15 -10
  34. package/dist/outbox.js.map +1 -1
  35. package/dist/replay.cjs +13 -9
  36. package/dist/replay.cjs.map +1 -1
  37. package/dist/replay.d.cts +8 -4
  38. package/dist/replay.d.ts +8 -4
  39. package/dist/replay.js +13 -9
  40. package/dist/replay.js.map +1 -1
  41. package/dist/tabs.cjs +12 -16
  42. package/dist/tabs.cjs.map +1 -1
  43. package/dist/tabs.d.cts +0 -2
  44. package/dist/tabs.d.ts +0 -2
  45. package/dist/tabs.js +12 -16
  46. package/dist/tabs.js.map +1 -1
  47. package/dist/timeline.cjs +4 -3
  48. package/dist/timeline.cjs.map +1 -1
  49. package/dist/timeline.d.cts +3 -7
  50. package/dist/timeline.d.ts +2 -4
  51. package/dist/timeline.js +4 -3
  52. package/dist/timeline.js.map +1 -1
  53. package/dist/{types-paLT8yQF.d.cts → types-DyZm2F7B.d.cts} +4 -5
  54. package/dist/webtransport.cjs +13 -12
  55. package/dist/webtransport.cjs.map +1 -1
  56. package/dist/webtransport.d.cts +0 -2
  57. package/dist/webtransport.d.ts +0 -2
  58. package/dist/webtransport.js +13 -12
  59. package/dist/webtransport.js.map +1 -1
  60. package/package.json +9 -9
package/dist/devtools.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use client';
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  let react = require("react");
4
- //#region src/devtools.ts
4
+ // src/devtools.ts
5
5
  const INSPECT = Symbol.for("react-websocket.inspect");
6
6
  const REGISTRY = Symbol.for("react-websocket.registry");
7
7
  const isClient = (value) => typeof value?.acquire === "function" && typeof value.send === "function" && "socket" in value;
@@ -180,7 +180,6 @@ function WebSocketDevtools({ sources = [], open: initiallyOpen = false, position
180
180
  padding: "8px 12px"
181
181
  } }, "No clients yet.")));
182
182
  }
183
- //#endregion
184
183
  exports.WebSocketDevtools = WebSocketDevtools;
185
184
 
186
185
  //# sourceMappingURL=devtools.cjs.map
@@ -1,6 +1,5 @@
1
1
 
2
2
  import { ReactElement } from "react";
3
- //#region src/devtools.d.ts
4
3
  /** Props for {@link WebSocketDevtools}. */
5
4
  export interface WebSocketDevtoolsProps {
6
5
  /**
@@ -28,5 +27,4 @@ export interface WebSocketDevtoolsProps {
28
27
  * ```
29
28
  */
30
29
  export declare function WebSocketDevtools({ sources, open: initiallyOpen, position }: WebSocketDevtoolsProps): ReactElement | null;
31
- //#endregion
32
30
  //# sourceMappingURL=devtools.d.cts.map
@@ -1,6 +1,5 @@
1
1
 
2
2
  import { ReactElement } from "react";
3
- //#region src/devtools.d.ts
4
3
  /** Props for {@link WebSocketDevtools}. */
5
4
  export interface WebSocketDevtoolsProps {
6
5
  /**
@@ -28,5 +27,4 @@ export interface WebSocketDevtoolsProps {
28
27
  * ```
29
28
  */
30
29
  export declare function WebSocketDevtools({ sources, open: initiallyOpen, position }: WebSocketDevtoolsProps): ReactElement | null;
31
- //#endregion
32
30
  //# sourceMappingURL=devtools.d.ts.map
package/dist/devtools.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import { createElement, useEffect, useReducer, useState, useSyncExternalStore } from "react";
3
- //#region src/devtools.ts
3
+ // src/devtools.ts
4
4
  const INSPECT = Symbol.for("react-websocket.inspect");
5
5
  const REGISTRY = Symbol.for("react-websocket.registry");
6
6
  const isClient = (value) => typeof value?.acquire === "function" && typeof value.send === "function" && "socket" in value;
@@ -179,7 +179,6 @@ function WebSocketDevtools({ sources = [], open: initiallyOpen = false, position
179
179
  padding: "8px 12px"
180
180
  } }, "No clients yet.")));
181
181
  }
182
- //#endregion
183
182
  export { WebSocketDevtools };
184
183
 
185
184
  //# sourceMappingURL=devtools.js.map
package/dist/index.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  let __core_cjs = require("./core.cjs");
4
4
  let react = require("react");
5
- //#region src/react.ts
5
+ // src/react.ts
6
6
  const IDLE = Object.freeze({
7
7
  status: "idle",
8
8
  lastMessage: void 0,
@@ -435,7 +435,6 @@ function useWebSocketStream(rpc, options = {}) {
435
435
  ...actions
436
436
  };
437
437
  }
438
- //#endregion
439
438
  exports.useAgUiAgent = useAgUiAgent;
440
439
  exports.useAgentApproval = useAgentApproval;
441
440
  exports.useAgentRun = useAgentRun;
package/dist/index.d.cts CHANGED
@@ -1,6 +1,5 @@
1
1
 
2
2
  import { RefObject } from "react";
3
- //#region src/types.d.ts
4
3
  /**
5
4
  * Where to connect: a URL, or a function that returns one (sync or async).
6
5
  *
@@ -449,8 +448,9 @@ interface WebSocketClient<In = unknown, Out = unknown> {
449
448
  close(code?: number, reason?: string): void;
450
449
  /**
451
450
  * Drop the current socket (if any) and connect again immediately, resetting the
452
- * backoff. Also restarts a `closed` client. The send queue and a `migrate()` target are
453
- * kept: when another user signs in, call `close()` and then `connect()` instead.
451
+ * backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
452
+ * again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
453
+ * are kept: when another user signs in, call `close()` and then `connect()` instead.
454
454
  */
455
455
  reconnect(): void;
456
456
  /**
@@ -482,8 +482,6 @@ interface WebSocketClient<In = unknown, Out = unknown> {
482
482
  */
483
483
  acquire(): () => void;
484
484
  }
485
- //#endregion
486
- //#region src/client.d.ts
487
485
  /**
488
486
  * The default `reconnect.shouldReconnect`: retry every close except `1002` (protocol error),
489
487
  * `1003` (unsupported data) and `1008` (policy violation, often a rejected login), which
@@ -532,8 +530,6 @@ export declare function retryAfter(close: CloseInfo): number | undefined;
532
530
  * ```
533
531
  */
534
532
  export declare function createWebSocket<In = unknown, Out = unknown>(url: UrlSource, options?: WebSocketOptions<In, Out>): WebSocketClient<In, Out>;
535
- //#endregion
536
- //#region src/topics.d.ts
537
533
  /** @internal Option key for a callback run when nothing holds a topic anymore. Used by feeds. */
538
534
  declare const ON_RELEASE: unique symbol;
539
535
  /** Options for {@link createWebSocketTopics}: the messages your server expects. */
@@ -582,8 +578,6 @@ interface WebSocketTopics {
582
578
  export declare function createWebSocketTopics<const Out>(client: WebSocketClient<any, Out>, options: WebSocketTopicsOptions<NoInfer<Out>> & {
583
579
  [ON_RELEASE]?: (topic: string) => void;
584
580
  }): WebSocketTopics;
585
- //#endregion
586
- //#region src/feeds.d.ts
587
581
  /** Where a numbered message belongs: its topic, and its sequence number in that topic. */
588
582
  interface FeedPosition {
589
583
  readonly topic: string;
@@ -663,8 +657,6 @@ interface WebSocketFeeds<In> extends WebSocketTopics {
663
657
  * ```
664
658
  */
665
659
  export declare function createWebSocketFeeds<In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketFeedsOptions<NoInfer<In>, NoInfer<Out>>): WebSocketFeeds<In>;
666
- //#endregion
667
- //#region src/latency.d.ts
668
660
  /** Options for {@link createWebSocketLatency}: how pings and pongs look on the wire. */
669
661
  interface WebSocketLatencyOptions<In, Out> {
670
662
  /** The ping message, tagged with `id`. Sent with `volatile`, so pings are never queued. */
@@ -740,8 +732,6 @@ interface WebSocketLatency {
740
732
  * ```
741
733
  */
742
734
  export declare function createWebSocketLatency<In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketLatencyOptions<NoInfer<In>, NoInfer<Out>>): WebSocketLatency;
743
- //#endregion
744
- //#region src/presence.d.ts
745
735
  /** Another client's shared state, such as its cursor or what it's selected. */
746
736
  interface PresencePeer<P> {
747
737
  /** The peer's id, as the server reports it. */
@@ -825,8 +815,6 @@ interface WebSocketPresence<P> {
825
815
  * ```
826
816
  */
827
817
  export declare function createWebSocketPresence<P, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketPresenceOptions<P, NoInfer<In>, NoInfer<Out>>): WebSocketPresence<P>;
828
- //#endregion
829
- //#region src/requests.d.ts
830
818
  /** Options for {@link createWebSocketRequests}: how requests and replies look on the wire. */
831
819
  interface WebSocketRequestsOptions<Req, In, Out> {
832
820
  /**
@@ -858,7 +846,7 @@ interface WebSocketRequestsOptions<Req, In, Out> {
858
846
  cancel?: (id: number) => Out;
859
847
  /**
860
848
  * Default time to wait for a reply, in ms. For a stream, the time to wait for each reply,
861
- * including the first. `Infinity` waits forever.
849
+ * including the first. `Infinity`, or anything over about 24.8 days, waits forever.
862
850
  * @default 10000
863
851
  */
864
852
  timeout?: number;
@@ -930,8 +918,6 @@ interface WebSocketRequests<Req, In> {
930
918
  * ```
931
919
  */
932
920
  export declare function createWebSocketRequests<Req, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketRequestsOptions<Req, NoInfer<In>, NoInfer<Out>>): WebSocketRequests<Req, In>;
933
- //#endregion
934
- //#region src/responder.d.ts
935
921
  /** What `request` returns for a request: any object with these fields, such as the message itself. */
936
922
  type RequestFields = {
937
923
  id: number | string;
@@ -1067,8 +1053,6 @@ interface WebSocketResponder<P = unknown, R = unknown> {
1067
1053
  * ```
1068
1054
  */
1069
1055
  export declare function createWebSocketResponder<Q extends RequestFields, R, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketResponderOptions<Q, R, NoInfer<In>, NoInfer<Out>>): WebSocketResponder<ParamsOf<Q>, R>;
1070
- //#endregion
1071
- //#region src/runs.d.ts
1072
1056
  /**
1073
1057
  * What happens to a run when its connection drops: `keep` resumes it on the next connection,
1074
1058
  * for agents that keep working in the background; `cancel` aborts it and tells the server, for
@@ -1206,8 +1190,6 @@ interface WebSocketRuns<Req, T> {
1206
1190
  * ```
1207
1191
  */
1208
1192
  export declare function createWebSocketRuns<Req, T, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketRunsOptions<Req, T, NoInfer<In>, NoInfer<Out>>): WebSocketRuns<Req, T>;
1209
- //#endregion
1210
- //#region src/sendrate.d.ts
1211
1193
  /** Options for {@link createWebSocketSendRate}. */
1212
1194
  interface WebSocketSendRateOptions {
1213
1195
  /**
@@ -1285,8 +1267,6 @@ interface WebSocketSendRate<Out> {
1285
1267
  * ```
1286
1268
  */
1287
1269
  export declare function createWebSocketSendRate<Out>(client: WebSocketClient<any, Out>, options?: WebSocketSendRateOptions): WebSocketSendRate<Out>;
1288
- //#endregion
1289
- //#region src/state.d.ts
1290
1270
  /** Options for {@link createWebSocketState}. */
1291
1271
  interface WebSocketStateOptions<S, In> {
1292
1272
  /** The state before any message arrives, and what `reset()` returns to. */
@@ -1361,8 +1341,6 @@ interface WebSocketState<S> {
1361
1341
  * ```
1362
1342
  */
1363
1343
  export declare function createWebSocketState<S, In>(source: WebSocketClient<In, any> | MessageSource<In>, options: WebSocketStateOptions<S, NoInfer<In>>): WebSocketState<S>;
1364
- //#endregion
1365
- //#region src/ag-ui.d.ts
1366
1344
  /** A tool call on an assistant message, as in AG-UI. */
1367
1345
  interface AgUiToolCall {
1368
1346
  readonly id: string;
@@ -1454,8 +1432,6 @@ interface AgUiAgent<S> {
1454
1432
  /** Stop following runs, and release the connection. */
1455
1433
  dispose(): void;
1456
1434
  }
1457
- //#endregion
1458
- //#region src/outbox.d.ts
1459
1435
  /** What an outbox stores for each message. */
1460
1436
  interface OutboxRecord<M = unknown> {
1461
1437
  /** The message's idempotency key, sent with it every time. */
@@ -1503,8 +1479,6 @@ interface WebSocketOutbox<M> {
1503
1479
  /** Stop sending and listening, and release the connection. Stored entries stay stored. */
1504
1480
  dispose(): void;
1505
1481
  }
1506
- //#endregion
1507
- //#region src/react.d.ts
1508
1482
  /**
1509
1483
  * Per-component event handlers. They always see the component's latest props and
1510
1484
  * state, and changing them never reconnects.
@@ -1776,6 +1750,5 @@ export declare function useWebSocketStream<Req, In, T>(rpc: WebSocketRequests<Re
1776
1750
  export declare function useWebSocketStream<Req, In>(rpc: WebSocketRequests<Req, In> | null | undefined, options?: {
1777
1751
  batch?: 'frame';
1778
1752
  }): UseWebSocketStreamResult<Req, readonly In[]>;
1779
- //#endregion
1780
1753
  export type { AgentRun, CloseInfo, EventMap, FeedPosition, HeartbeatOptions, IncomingRequest, Latency, MessageSource, MigrateOptions, PresencePeer, QueueOptions, ReconnectOptions, RequestHandler, RequestOptions, RunPolicy, RunStatus, RunStorage, SendData, SendOptions, SendRate, Snapshot, StandardSchemaV1, Status, UrlSource, UseWebSocketOptions, UseWebSocketResult, UseWebSocketStreamOptions, UseWebSocketStreamResult, WebSocketClient, WebSocketFeeds, WebSocketFeedsOptions, WebSocketHandlers, WebSocketLatency, WebSocketLatencyOptions, WebSocketOptions, WebSocketPresence, WebSocketPresenceOptions, WebSocketRequests, WebSocketRequestsOptions, WebSocketResponder, WebSocketResponderOptions, WebSocketRuns, WebSocketRunsOptions, WebSocketSendRate, WebSocketSendRateOptions, WebSocketState, WebSocketStateOptions, WebSocketTopics, WebSocketTopicsOptions };
1781
1754
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -2,7 +2,6 @@
2
2
  import { RunPolicy, WebSocketClient, WebSocketRuns } from "./core.js";
3
3
  import { RefObject } from "react";
4
4
  export * from "./core.js";
5
- //#region src/ag-ui.d.ts
6
5
  /** A tool call on an assistant message, as in AG-UI. */
7
6
  interface AgUiToolCall {
8
7
  readonly id: string;
@@ -94,8 +93,6 @@ interface AgUiAgent<S> {
94
93
  /** Stop following runs, and release the connection. */
95
94
  dispose(): void;
96
95
  }
97
- //#endregion
98
- //#region src/types.d.ts
99
96
  /**
100
97
  * Where to connect: a URL, or a function that returns one (sync or async).
101
98
  *
@@ -544,8 +541,9 @@ interface WebSocketClient$1<In = unknown, Out = unknown> {
544
541
  close(code?: number, reason?: string): void;
545
542
  /**
546
543
  * Drop the current socket (if any) and connect again immediately, resetting the
547
- * backoff. Also restarts a `closed` client. The send queue and a `migrate()` target are
548
- * kept: when another user signs in, call `close()` and then `connect()` instead.
544
+ * backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
545
+ * again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
546
+ * are kept: when another user signs in, call `close()` and then `connect()` instead.
549
547
  */
550
548
  reconnect(): void;
551
549
  /**
@@ -577,8 +575,6 @@ interface WebSocketClient$1<In = unknown, Out = unknown> {
577
575
  */
578
576
  acquire(): () => void;
579
577
  }
580
- //#endregion
581
- //#region src/latency.d.ts
582
578
  /** Latest latency measurements. A new object is created on every change. */
583
579
  interface Latency {
584
580
  /** Round-trip time in ms: the median of recent pings. `undefined` until the first pong. */
@@ -604,8 +600,6 @@ interface WebSocketLatency {
604
600
  /** Stop pinging and listening. Only needed for instances created dynamically. */
605
601
  dispose(): void;
606
602
  }
607
- //#endregion
608
- //#region src/outbox.d.ts
609
603
  /** What an outbox stores for each message. */
610
604
  interface OutboxRecord<M = unknown> {
611
605
  /** The message's idempotency key, sent with it every time. */
@@ -653,8 +647,6 @@ interface WebSocketOutbox<M> {
653
647
  /** Stop sending and listening, and release the connection. Stored entries stay stored. */
654
648
  dispose(): void;
655
649
  }
656
- //#endregion
657
- //#region src/presence.d.ts
658
650
  /** Another client's shared state, such as its cursor or what it's selected. */
659
651
  interface PresencePeer<P> {
660
652
  /** The peer's id, as the server reports it. */
@@ -681,8 +673,6 @@ interface WebSocketPresence<P> {
681
673
  /** Stop sharing and listening. */
682
674
  dispose(): void;
683
675
  }
684
- //#endregion
685
- //#region src/requests.d.ts
686
676
  /** Per-call options for {@link WebSocketRequests.request} and {@link WebSocketRequests.stream}. */
687
677
  interface RequestOptions extends SendOptions {
688
678
  /**
@@ -731,8 +721,6 @@ interface WebSocketRequests<Req, In> {
731
721
  /** Reject every pending request and stop listening. Only needed for managers created dynamically. */
732
722
  dispose(): void;
733
723
  }
734
- //#endregion
735
- //#region src/responder.d.ts
736
724
  /** A request from the server that hasn't been answered yet. */
737
725
  interface IncomingRequest<P = unknown, R = unknown> {
738
726
  /** The id the server sent. Replies carry it back. */
@@ -792,8 +780,6 @@ interface WebSocketResponder<P = unknown, R = unknown> {
792
780
  */
793
781
  dispose(): void;
794
782
  }
795
- //#endregion
796
- //#region src/runs.d.ts
797
783
  /**
798
784
  * What happens to a run when its connection drops: `keep` resumes it on the next connection,
799
785
  * for agents that keep working in the background; `cancel` aborts it and tells the server, for
@@ -854,8 +840,6 @@ interface WebSocketRuns$1<Req, T> {
854
840
  /** Stop following runs, and release the connection. Remembered runs stay remembered. */
855
841
  dispose(): void;
856
842
  }
857
- //#endregion
858
- //#region src/state.d.ts
859
843
  interface WebSocketState<S> {
860
844
  /** The client whose messages this store reduces. Hooks reading the store keep it connected. */
861
845
  readonly client: WebSocketClient$1<any, any>;
@@ -872,8 +856,6 @@ interface WebSocketState<S> {
872
856
  /** Stop reducing messages. Only needed for stores created dynamically rather than at module level. */
873
857
  dispose(): void;
874
858
  }
875
- //#endregion
876
- //#region src/topics.d.ts
877
859
  /** Reference-counted topic subscriptions on one client. Create with {@link createWebSocketTopics}. */
878
860
  interface WebSocketTopics {
879
861
  /** The client the subscription messages are sent on. */
@@ -888,8 +870,6 @@ interface WebSocketTopics {
888
870
  /** Stop managing subscriptions. Only needed for managers created dynamically. */
889
871
  dispose(): void;
890
872
  }
891
- //#endregion
892
- //#region src/react.d.ts
893
873
  /**
894
874
  * Per-component event handlers. They always see the component's latest props and
895
875
  * state, and changing them never reconnects.
@@ -1161,6 +1141,5 @@ export declare function useWebSocketStream<Req, In, T>(rpc: WebSocketRequests<Re
1161
1141
  export declare function useWebSocketStream<Req, In>(rpc: WebSocketRequests<Req, In> | null | undefined, options?: {
1162
1142
  batch?: 'frame';
1163
1143
  }): UseWebSocketStreamResult<Req, readonly In[]>;
1164
- //#endregion
1165
1144
  export type { UseWebSocketOptions, UseWebSocketResult, UseWebSocketStreamOptions, UseWebSocketStreamResult, WebSocketHandlers };
1166
1145
  //# sourceMappingURL=index.d.ts.map
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  let __core_cjs = require("./core.cjs");
4
4
  let react = require("react");
5
- //#region src/react.ts
5
+ // src/react.ts
6
6
  const IDLE = Object.freeze({
7
7
  status: "idle",
8
8
  lastMessage: void 0,
@@ -472,7 +472,6 @@ function useWebSocketStream(rpc, options = {}) {
472
472
  ...actions
473
473
  };
474
474
  }
475
- //#endregion
476
475
  exports.useAgUiAgent = useAgUiAgent;
477
476
  exports.useAgentApproval = useAgentApproval;
478
477
  exports.useAgentRun = useAgentRun;
@@ -2,7 +2,7 @@
2
2
  import { createWebSocket } from "./core.js";
3
3
  import { useEffect, useId, useInsertionEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
4
  export * from "./core.js";
5
- //#region src/react.ts
5
+ // src/react.ts
6
6
  const IDLE = Object.freeze({
7
7
  status: "idle",
8
8
  lastMessage: void 0,
@@ -472,7 +472,6 @@ function useWebSocketStream(rpc, options = {}) {
472
472
  ...actions
473
473
  };
474
474
  }
475
- //#endregion
476
475
  export { useAgUiAgent, useAgentApproval, useAgentRun, useInView, useWebSocket, useWebSocketEvent, useWebSocketLatency, useWebSocketOutbox, useWebSocketPresence, useWebSocketState, useWebSocketStatus, useWebSocketStream, useWebSocketTopic };
477
476
 
478
477
  //# sourceMappingURL=index.development.js.map
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createWebSocket } from "./core.js";
3
3
  import { useEffect, useId, useInsertionEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
4
  export * from "./core.js";
5
- //#region src/react.ts
5
+ // src/react.ts
6
6
  const IDLE = Object.freeze({
7
7
  status: "idle",
8
8
  lastMessage: void 0,
@@ -435,7 +435,6 @@ function useWebSocketStream(rpc, options = {}) {
435
435
  ...actions
436
436
  };
437
437
  }
438
- //#endregion
439
438
  export { useAgUiAgent, useAgentApproval, useAgentRun, useInView, useWebSocket, useWebSocketEvent, useWebSocketLatency, useWebSocketOutbox, useWebSocketPresence, useWebSocketState, useWebSocketStatus, useWebSocketStream, useWebSocketTopic };
440
439
 
441
440
  //# sourceMappingURL=index.js.map
package/dist/outbox.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/outbox.ts
2
+ // src/outbox.ts
3
3
  /** Keep outbox entries in IndexedDB, in the database `react-websocket-outbox:<name>`. */
4
4
  function indexedDBStorage(name) {
5
5
  let db;
@@ -80,9 +80,10 @@ function createWebSocketOutbox(client, options) {
80
80
  const removed = /* @__PURE__ */ new Set();
81
81
  let clearedBeforeLoad = false;
82
82
  let addedSinceClear;
83
- const channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
83
+ let channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
84
84
  let disposed = false;
85
85
  let release;
86
+ let sentOn = null;
86
87
  let lastCreated = 0;
87
88
  function changed() {
88
89
  snapshot = [...entries.values()];
@@ -115,11 +116,16 @@ function createWebSocketOutbox(client, options) {
115
116
  return storage.delete(id);
116
117
  }
117
118
  function flush() {
118
- if (!loaded || disposed || client.socket?.readyState !== 1) return;
119
+ const socket = client.socket;
120
+ if (!loaded || disposed || socket?.readyState !== 1) return;
121
+ if (socket !== sentOn) {
122
+ unsend();
123
+ sentOn = socket;
124
+ }
119
125
  const now = Date.now();
120
126
  let sent = false;
121
127
  for (const entry of [...entries.values()]) {
122
- if (entry.sent) continue;
128
+ if (entry.sent || entries.get(entry.id) !== entry) continue;
123
129
  if (now - entry.createdAt > maxAge) {
124
130
  forget(entry.id).catch(noop);
125
131
  options.onExpire?.(entry);
@@ -169,11 +175,11 @@ function createWebSocketOutbox(client, options) {
169
175
  } else if (data?.id) drop(data.id);
170
176
  };
171
177
  const offs = [
172
- () => channel?.close(),
173
- client.on("open", () => {
174
- unsend();
175
- flush();
176
- }),
178
+ () => {
179
+ channel?.close();
180
+ channel = void 0;
181
+ },
182
+ client.on("open", flush),
177
183
  client.subscribe(() => {
178
184
  if (client.getSnapshot().status !== "open") unsend();
179
185
  }),
@@ -228,7 +234,6 @@ function createWebSocketOutbox(client, options) {
228
234
  }
229
235
  };
230
236
  }
231
- //#endregion
232
237
  exports.createWebSocketOutbox = createWebSocketOutbox;
233
238
  exports.indexedDBStorage = indexedDBStorage;
234
239
  exports.memoryStorage = memoryStorage;
@@ -1 +1 @@
1
- {"version":3,"file":"outbox.cjs","names":[],"sources":["../src/outbox.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient } from './core';\n\n/** What an outbox stores for each message. */\nexport interface OutboxRecord<M = unknown> {\n /** The message's idempotency key, sent with it every time. */\n readonly id: string;\n /** The message, as passed to `add()`. */\n readonly message: M;\n /** When it was added, from `Date.now()`. Entries are sent in this order. */\n readonly createdAt: number;\n}\n\n/** A message waiting in the outbox. */\nexport interface OutboxEntry<M = unknown> extends OutboxRecord<M> {\n /** Sent on the current connection, and waiting for the server's ack. */\n readonly sent: boolean;\n}\n\n/**\n * Where an outbox keeps its messages. The default, {@link indexedDBStorage}, keeps them across\n * reloads. Pass your own to store them elsewhere, or {@link memoryStorage} in tests.\n */\nexport interface OutboxStorage {\n /** Every stored record, in any order. */\n load(): Promise<OutboxRecord[]>;\n put(record: OutboxRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\n/** Options for {@link createWebSocketOutbox}. */\nexport interface WebSocketOutboxOptions<M, In, Out> {\n /**\n * Names the outbox's IndexedDB database, `react-websocket-outbox:<name>`. Give each outbox\n * its own. Unused with `storage`.\n */\n name: string;\n /**\n * Build the message to send for an entry, with its `id` as the idempotency key: the server\n * should do nothing for an id it has already handled, except acknowledge it again. Annotate\n * `message`: that's what `outbox.add()` accepts.\n */\n send: (message: M, id: string) => Out;\n /**\n * Recognize the server's acknowledgement and return the id it confirms, or `undefined` (or\n * `null`) for any other message. An entry stays until it's acknowledged, and is sent again\n * on every new connection until then. Without `ack`, an entry is removed once it has been\n * sent, so one sent just before the connection dropped can be lost.\n */\n ack?: (message: In) => string | null | undefined;\n /**\n * Drop an entry instead of sending it once it's older than this many ms. Checked when it\n * would be sent: on a new connection, and when stored entries are loaded.\n * @default Infinity\n */\n maxAge?: number;\n /** Called with each entry dropped by `maxAge`. */\n onExpire?: (entry: OutboxEntry<M>) => void;\n /**\n * Where to keep entries.\n * @default indexedDBStorage(name), or memoryStorage() where IndexedDB doesn't exist\n */\n storage?: OutboxStorage;\n}\n\n/** A persistent outbox on one client. Create with {@link createWebSocketOutbox}. */\nexport interface WebSocketOutbox<M> {\n /** The client the entries are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Resolves once the entries stored by an earlier page load are back in the outbox, and\n * rejects if they couldn't be loaded. Nothing is sent before.\n */\n readonly ready: Promise<void>;\n /**\n * Add a message and send it as soon as the socket is open. Resolves with its id once it's\n * stored, and rejects if storing failed; the entry is still sent from memory then, but won't\n * survive a reload. Without `ack`, one sent right away isn't stored, and resolves at once.\n * @param id - The idempotency key, e.g. an order number. A new random one by default.\n */\n add(message: M, id?: string): Promise<string>;\n /**\n * Remove an entry without sending it again, e.g. when the user cancels it. Other tabs using\n * the same `name` drop it too.\n */\n remove(id: string): Promise<void>;\n /**\n * Remove every entry at once, including ones other tabs stored, e.g. on logout. Other tabs\n * using the same `name` drop theirs too. Resolves once they're deleted from storage.\n */\n clear(): Promise<void>;\n /** The waiting entries, oldest first. A new array on every change. */\n getSnapshot(): readonly OutboxEntry<M>[];\n /** Get notified when the entries change. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop sending and listening, and release the connection. Stored entries stay stored. */\n dispose(): void;\n}\n\n/** Keep outbox entries in IndexedDB, in the database `react-websocket-outbox:<name>`. */\nexport function indexedDBStorage(name: string): OutboxStorage {\n let db: Promise<IDBDatabase> | undefined;\n // Settles once the transaction has committed, not when its request succeeds: a write isn't\n // durable before, and could still be lost if the page closed.\n const run = async <T>(\n mode: IDBTransactionMode,\n ask: (store: IDBObjectStore) => IDBRequest<T>\n ): Promise<T> => {\n db ??= new Promise((resolve, reject) => {\n const open = indexedDB.open(`react-websocket-outbox:${name}`, 1);\n open.onupgradeneeded = () => open.result.createObjectStore('entries', { keyPath: 'id' });\n open.onsuccess = () => {\n const connection = open.result;\n // Let another page delete or upgrade the database: the next write opens it again.\n connection.onversionchange = () => {\n connection.close();\n db = undefined;\n };\n resolve(connection);\n };\n open.onerror = () => reject(open.error);\n });\n const transaction = (await db).transaction('entries', mode);\n const req = ask(transaction.objectStore('entries'));\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve(req.result);\n transaction.onerror = transaction.onabort = () => reject(transaction.error ?? req.error);\n });\n };\n return {\n load: () => run('readonly', store => store.getAll()),\n put: record => run('readwrite', store => store.put(record)).then(noop),\n delete: id => run('readwrite', store => store.delete(id))\n };\n}\n\n/** Keep outbox entries in memory only: they don't survive a reload. For tests and servers. */\nexport function memoryStorage(): OutboxStorage {\n const records = new Map<string, OutboxRecord>();\n return {\n load: async () => [...records.values()],\n put: async record => void records.set(record.id, record),\n delete: async id => void records.delete(id)\n };\n}\n\nconst noop = () => {};\n\nfunction randomId() {\n // `randomUUID` needs a secure context; plain-HTTP pages fall back to a timestamp and random digits.\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\n/**\n * Keep messages until the server acknowledges them, across reconnects and page reloads, for\n * apps that must not lose a message on flaky Wi-Fi: point of sale, field service, warehouses.\n *\n * - `add(message)` stores the message (in IndexedDB by default) and sends it, tagged with an\n * idempotency key, as soon as the socket is open.\n * - It stays until the server acknowledges that key (`ack`). Every new connection sends the\n * unacknowledged entries again, in order, so the server must ignore a key it has already\n * handled and acknowledge it again.\n * - After a reload, the stored entries are loaded and sent before new ones.\n * - While entries are waiting, the outbox holds the client's connection open.\n *\n * Its entries don't go through the client's send queue, so `queue` options don't apply to them.\n *\n * @example\n * ```ts\n * import { createWebSocketOutbox } from 'react-websocket/outbox';\n *\n * export const orders = createWebSocketOutbox(pos, {\n * name: 'orders',\n * send: (order: Order, id) => ({ type: 'order', id, order }),\n * ack: message => (message.type === 'ack' ? message.id : undefined)\n * });\n *\n * await orders.add({ table: 4, items });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only; `M` comes from how `send`\n// annotates its parameter.\nexport function createWebSocketOutbox<M, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketOutboxOptions<M, NoInfer<In>, NoInfer<Out>>\n): WebSocketOutbox<M> {\n const storage =\n options.storage ??\n (typeof indexedDB === 'undefined' ? memoryStorage() : indexedDBStorage(options.name));\n const maxAge = options.maxAge ?? Infinity;\n // Insertion order is `createdAt` order: entries loaded from storage are sorted in.\n let entries = new Map<string, OutboxEntry<M>>();\n let snapshot: readonly OutboxEntry<M>[] = [];\n const listeners = new Set<() => void>();\n let loaded = false;\n // Removed (or acknowledged) before the stored entries were loaded: don't restore them.\n const removed = new Set<string>();\n // Cleared, here or in another tab, before the stored entries were loaded: restore none.\n let clearedBeforeLoad = false;\n // Ids added since the latest `clear()` here began: the only stored entries it keeps.\n let addedSinceClear: Set<string> | undefined;\n // Other tabs using the same outbox, which loaded the same entries: tell them what's gone. Not\n // on a server, where an open channel would keep the process alive.\n const channel =\n typeof window !== 'undefined' && typeof BroadcastChannel === 'function'\n ? new BroadcastChannel(`react-websocket-outbox:${options.name}`)\n : undefined;\n let disposed = false;\n let release: (() => void) | undefined;\n // A strictly increasing `createdAt`, so entries added in the same ms keep their order.\n let lastCreated = 0;\n\n function changed() {\n snapshot = [...entries.values()];\n // Hold the connection while anything is waiting, so it gets delivered.\n if (snapshot.length && !release && !disposed) release = client.acquire();\n else if (!snapshot.length && release) {\n release();\n release = undefined;\n }\n for (const listener of [...listeners]) listener();\n }\n\n function drop(id: string) {\n if (!loaded) removed.add(id);\n if (entries.delete(id)) changed();\n }\n\n /**\n * Drop every entry held now, and its stored copy. Not by `createdAt`: that comes from the clock\n * of whichever page added it, which can be ahead of this one's.\n */\n function dropAll() {\n if (!loaded) clearedBeforeLoad = true;\n const held = [...entries.keys()];\n if (!held.length) return;\n entries = new Map();\n changed();\n for (const id of held) storage.delete(id).catch(noop);\n }\n\n // Also deletes a stored entry that isn't loaded yet, so it doesn't come back.\n function forget(id: string) {\n drop(id);\n channel?.postMessage({ id });\n return storage.delete(id);\n }\n\n function flush() {\n // The socket, not the status, which reads `open` while the server closes it. Not `volatile`\n // either, which can be a datagram that never arrives.\n if (!loaded || disposed || client.socket?.readyState !== 1) return;\n const now = Date.now();\n let sent = false;\n for (const entry of [...entries.values()]) {\n if (entry.sent) continue;\n if (now - entry.createdAt > maxAge) {\n forget(entry.id).catch(noop);\n options.onExpire?.(entry);\n } else if (client.send(options.send(entry.message, entry.id))) {\n if (!options.ack) forget(entry.id).catch(noop);\n else {\n entries.set(entry.id, { ...entry, sent: true });\n sent = true;\n }\n }\n }\n if (sent) changed();\n }\n\n const ready = storage\n .load()\n .then(records => {\n if (disposed) return;\n // Entries added from now on sort after the stored ones, whichever clock stored them.\n for (const record of records) lastCreated = Math.max(lastCreated, record.createdAt);\n // Entries added meanwhile are newer than the stored ones, unless one has the same id.\n entries = new Map(\n [\n ...records.filter(\n record => !clearedBeforeLoad && !entries.has(record.id) && !removed.has(record.id)\n ),\n ...entries.values()\n ]\n .sort((a, b) => a.createdAt - b.createdAt)\n .map(record => [record.id, { ...record, sent: false } as OutboxEntry<M>])\n );\n changed();\n })\n // Even without its stored entries, the outbox works from memory.\n .finally(() => {\n loaded = true;\n removed.clear();\n flush();\n });\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n ready.catch(noop);\n\n /** What was sent on the last connection may not have arrived: send it again on the next. */\n function unsend() {\n let changes = false;\n for (const entry of entries.values()) {\n if (entry.sent) {\n entries.set(entry.id, { ...entry, sent: false });\n changes = true;\n }\n }\n if (changes) changed();\n }\n\n if (channel) {\n channel.onmessage = ({ data }: MessageEvent<{ id?: string; before?: number } | null>) => {\n // Another tab cleared: drop everything held now, whenever it was added.\n if (data?.before) {\n lastCreated = Math.max(lastCreated, data.before);\n dropAll();\n } else if (data?.id) drop(data.id);\n };\n }\n\n const offs = [\n () => channel?.close(),\n // Also after `migrate()`, where the status stays `open`.\n client.on('open', () => {\n unsend();\n flush();\n }),\n client.subscribe(() => {\n if (client.getSnapshot().status !== 'open') unsend();\n }),\n client.on('message', message => {\n const id = options.ack?.(message);\n if (id != null) forget(String(id)).catch(noop);\n })\n ];\n\n return {\n client,\n ready,\n add(message, id = randomId()) {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const record: OutboxRecord<M> = { id, message, createdAt: lastCreated };\n // Re-adding an id moves it to the end, as a new message.\n entries.delete(id);\n entries.set(id, { ...record, sent: false });\n addedSinceClear?.add(id);\n changed();\n flush();\n // Sent, with no ack to wait for: there's nothing to keep. Storing it now would outlive its\n // delete, and send it again after a reload.\n if (!entries.has(id)) return Promise.resolve(id);\n return storage.put(record).then(() => id);\n },\n remove: forget,\n clear() {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const kept = (addedSinceClear = new Set<string>());\n // At once, like `remove()`: waiting for the stored entries would send them first.\n dropAll();\n channel?.postMessage({ before: lastCreated });\n // Everything stored, by other tabs and earlier page loads too, but not what's added from\n // now on.\n return storage\n .load()\n .then(records =>\n Promise.all(\n records.filter(record => !kept.has(record.id)).map(record => storage.delete(record.id))\n )\n )\n .then(() => {\n if (addedSinceClear === kept) addedSinceClear = undefined;\n });\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n for (const off of offs) off();\n release?.();\n release = undefined;\n }\n };\n}\n"],"mappings":";;;AAoGA,SAAgB,iBAAiB,MAA6B;CAC5D,IAAI;CAGJ,MAAM,MAAM,OACV,MACA,QACe;EACf,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,OAAO,UAAU,KAAK,0BAA0B,QAAQ,CAAC;GAC/D,KAAK,wBAAwB,KAAK,OAAO,kBAAkB,WAAW,EAAE,SAAS,KAAK,CAAC;GACvF,KAAK,kBAAkB;IACrB,MAAM,aAAa,KAAK;IAExB,WAAW,wBAAwB;KACjC,WAAW,MAAM;KACjB,KAAK,KAAA;IACP;IACA,QAAQ,UAAU;GACpB;GACA,KAAK,gBAAgB,OAAO,KAAK,KAAK;EACxC,CAAC;EACD,MAAM,eAAe,MAAM,GAAA,CAAI,YAAY,WAAW,IAAI;EAC1D,MAAM,MAAM,IAAI,YAAY,YAAY,SAAS,CAAC;EAClD,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,YAAY,mBAAmB,QAAQ,IAAI,MAAM;GACjD,YAAY,UAAU,YAAY,gBAAgB,OAAO,YAAY,SAAS,IAAI,KAAK;EACzF,CAAC;CACH;CACA,OAAO;EACL,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.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient } from './core';\n\n/** What an outbox stores for each message. */\nexport interface OutboxRecord<M = unknown> {\n /** The message's idempotency key, sent with it every time. */\n readonly id: string;\n /** The message, as passed to `add()`. */\n readonly message: M;\n /** When it was added, from `Date.now()`. Entries are sent in this order. */\n readonly createdAt: number;\n}\n\n/** A message waiting in the outbox. */\nexport interface OutboxEntry<M = unknown> extends OutboxRecord<M> {\n /** Sent on the current connection, and waiting for the server's ack. */\n readonly sent: boolean;\n}\n\n/**\n * Where an outbox keeps its messages. The default, {@link indexedDBStorage}, keeps them across\n * reloads. Pass your own to store them elsewhere, or {@link memoryStorage} in tests.\n */\nexport interface OutboxStorage {\n /** Every stored record, in any order. */\n load(): Promise<OutboxRecord[]>;\n put(record: OutboxRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\n/** Options for {@link createWebSocketOutbox}. */\nexport interface WebSocketOutboxOptions<M, In, Out> {\n /**\n * Names the outbox's IndexedDB database, `react-websocket-outbox:<name>`. Give each outbox\n * its own. Unused with `storage`.\n */\n name: string;\n /**\n * Build the message to send for an entry, with its `id` as the idempotency key: the server\n * should do nothing for an id it has already handled, except acknowledge it again. Annotate\n * `message`: that's what `outbox.add()` accepts.\n */\n send: (message: M, id: string) => Out;\n /**\n * Recognize the server's acknowledgement and return the id it confirms, or `undefined` (or\n * `null`) for any other message. An entry stays until it's acknowledged, and is sent again\n * on every new connection until then. Without `ack`, an entry is removed once it has been\n * sent, so one sent just before the connection dropped can be lost.\n */\n ack?: (message: In) => string | null | undefined;\n /**\n * Drop an entry instead of sending it once it's older than this many ms. Checked when it\n * would be sent: on a new connection, and when stored entries are loaded.\n * @default Infinity\n */\n maxAge?: number;\n /** Called with each entry dropped by `maxAge`. */\n onExpire?: (entry: OutboxEntry<M>) => void;\n /**\n * Where to keep entries.\n * @default indexedDBStorage(name), or memoryStorage() where IndexedDB doesn't exist\n */\n storage?: OutboxStorage;\n}\n\n/** A persistent outbox on one client. Create with {@link createWebSocketOutbox}. */\nexport interface WebSocketOutbox<M> {\n /** The client the entries are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Resolves once the entries stored by an earlier page load are back in the outbox, and\n * rejects if they couldn't be loaded. Nothing is sent before.\n */\n readonly ready: Promise<void>;\n /**\n * Add a message and send it as soon as the socket is open. Resolves with its id once it's\n * stored, and rejects if storing failed; the entry is still sent from memory then, but won't\n * survive a reload. Without `ack`, one sent right away isn't stored, and resolves at once.\n * @param id - The idempotency key, e.g. an order number. A new random one by default.\n */\n add(message: M, id?: string): Promise<string>;\n /**\n * Remove an entry without sending it again, e.g. when the user cancels it. Other tabs using\n * the same `name` drop it too.\n */\n remove(id: string): Promise<void>;\n /**\n * Remove every entry at once, including ones other tabs stored, e.g. on logout. Other tabs\n * using the same `name` drop theirs too. Resolves once they're deleted from storage.\n */\n clear(): Promise<void>;\n /** The waiting entries, oldest first. A new array on every change. */\n getSnapshot(): readonly OutboxEntry<M>[];\n /** Get notified when the entries change. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop sending and listening, and release the connection. Stored entries stay stored. */\n dispose(): void;\n}\n\n/** Keep outbox entries in IndexedDB, in the database `react-websocket-outbox:<name>`. */\nexport function indexedDBStorage(name: string): OutboxStorage {\n let db: Promise<IDBDatabase> | undefined;\n // Settles once the transaction has committed, not when its request succeeds: a write isn't\n // durable before, and could still be lost if the page closed.\n const run = async <T>(\n mode: IDBTransactionMode,\n ask: (store: IDBObjectStore) => IDBRequest<T>\n ): Promise<T> => {\n db ??= new Promise((resolve, reject) => {\n const open = indexedDB.open(`react-websocket-outbox:${name}`, 1);\n open.onupgradeneeded = () => open.result.createObjectStore('entries', { keyPath: 'id' });\n open.onsuccess = () => {\n const connection = open.result;\n // Let another page delete or upgrade the database: the next write opens it again.\n connection.onversionchange = () => {\n connection.close();\n db = undefined;\n };\n resolve(connection);\n };\n open.onerror = () => reject(open.error);\n });\n const transaction = (await db).transaction('entries', mode);\n const req = ask(transaction.objectStore('entries'));\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve(req.result);\n transaction.onerror = transaction.onabort = () => reject(transaction.error ?? req.error);\n });\n };\n return {\n load: () => run('readonly', store => store.getAll()),\n put: record => run('readwrite', store => store.put(record)).then(noop),\n delete: id => run('readwrite', store => store.delete(id))\n };\n}\n\n/** Keep outbox entries in memory only: they don't survive a reload. For tests and servers. */\nexport function memoryStorage(): OutboxStorage {\n const records = new Map<string, OutboxRecord>();\n return {\n load: async () => [...records.values()],\n put: async record => void records.set(record.id, record),\n delete: async id => void records.delete(id)\n };\n}\n\nconst noop = () => {};\n\nfunction randomId() {\n // `randomUUID` needs a secure context; plain-HTTP pages fall back to a timestamp and random digits.\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\n/**\n * Keep messages until the server acknowledges them, across reconnects and page reloads, for\n * apps that must not lose a message on flaky Wi-Fi: point of sale, field service, warehouses.\n *\n * - `add(message)` stores the message (in IndexedDB by default) and sends it, tagged with an\n * idempotency key, as soon as the socket is open.\n * - It stays until the server acknowledges that key (`ack`). Every new connection sends the\n * unacknowledged entries again, in order, so the server must ignore a key it has already\n * handled and acknowledge it again.\n * - After a reload, the stored entries are loaded and sent before new ones.\n * - While entries are waiting, the outbox holds the client's connection open.\n *\n * Its entries don't go through the client's send queue, so `queue` options don't apply to them.\n *\n * @example\n * ```ts\n * import { createWebSocketOutbox } from 'react-websocket/outbox';\n *\n * export const orders = createWebSocketOutbox(pos, {\n * name: 'orders',\n * send: (order: Order, id) => ({ type: 'order', id, order }),\n * ack: message => (message.type === 'ack' ? message.id : undefined)\n * });\n *\n * await orders.add({ table: 4, items });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only; `M` comes from how `send`\n// annotates its parameter.\nexport function createWebSocketOutbox<M, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketOutboxOptions<M, NoInfer<In>, NoInfer<Out>>\n): WebSocketOutbox<M> {\n const storage =\n options.storage ??\n (typeof indexedDB === 'undefined' ? memoryStorage() : indexedDBStorage(options.name));\n const maxAge = options.maxAge ?? Infinity;\n // Insertion order is `createdAt` order: entries loaded from storage are sorted in.\n let entries = new Map<string, OutboxEntry<M>>();\n let snapshot: readonly OutboxEntry<M>[] = [];\n const listeners = new Set<() => void>();\n let loaded = false;\n // Removed (or acknowledged) before the stored entries were loaded: don't restore them.\n const removed = new Set<string>();\n // Cleared, here or in another tab, before the stored entries were loaded: restore none.\n let clearedBeforeLoad = false;\n // Ids added since the latest `clear()` here began: the only stored entries it keeps.\n let addedSinceClear: Set<string> | undefined;\n // Other tabs using the same outbox, which loaded the same entries: tell them what's gone. Not\n // on a server, where an open channel would keep the process alive.\n let channel =\n typeof window !== 'undefined' && typeof BroadcastChannel === 'function'\n ? new BroadcastChannel(`react-websocket-outbox:${options.name}`)\n : undefined;\n let disposed = false;\n let release: (() => void) | undefined;\n // The socket that entries marked `sent` went out on. On any other, they go out again.\n let sentOn: WebSocket | null = null;\n // A strictly increasing `createdAt`, so entries added in the same ms keep their order.\n let lastCreated = 0;\n\n function changed() {\n snapshot = [...entries.values()];\n // Hold the connection while anything is waiting, so it gets delivered.\n if (snapshot.length && !release && !disposed) release = client.acquire();\n else if (!snapshot.length && release) {\n release();\n release = undefined;\n }\n for (const listener of [...listeners]) listener();\n }\n\n function drop(id: string) {\n if (!loaded) removed.add(id);\n if (entries.delete(id)) changed();\n }\n\n /**\n * Drop every entry held now, and its stored copy. Not by `createdAt`: that comes from the clock\n * of whichever page added it, which can be ahead of this one's.\n */\n function dropAll() {\n if (!loaded) clearedBeforeLoad = true;\n const held = [...entries.keys()];\n if (!held.length) return;\n entries = new Map();\n changed();\n for (const id of held) storage.delete(id).catch(noop);\n }\n\n // Also deletes a stored entry that isn't loaded yet, so it doesn't come back.\n function forget(id: string) {\n drop(id);\n channel?.postMessage({ id });\n return storage.delete(id);\n }\n\n function flush() {\n const socket = client.socket;\n // The socket, not the status, which reads `open` while the server closes it. Not `volatile`\n // either, which can be a datagram that never arrives.\n if (!loaded || disposed || socket?.readyState !== 1) return;\n // A new connection, including after `migrate()`, where the status stays `open`.\n if (socket !== sentOn) {\n unsend();\n sentOn = socket;\n }\n const now = Date.now();\n let sent = false;\n for (const entry of [...entries.values()]) {\n // Sent, removed or replaced meanwhile, by `onExpire` or a listener.\n if (entry.sent || entries.get(entry.id) !== entry) continue;\n if (now - entry.createdAt > maxAge) {\n forget(entry.id).catch(noop);\n options.onExpire?.(entry);\n } else if (client.send(options.send(entry.message, entry.id))) {\n if (!options.ack) forget(entry.id).catch(noop);\n else {\n entries.set(entry.id, { ...entry, sent: true });\n sent = true;\n }\n }\n }\n if (sent) changed();\n }\n\n const ready = storage\n .load()\n .then(records => {\n if (disposed) return;\n // Entries added from now on sort after the stored ones, whichever clock stored them.\n for (const record of records) lastCreated = Math.max(lastCreated, record.createdAt);\n // Entries added meanwhile are newer than the stored ones, unless one has the same id.\n entries = new Map(\n [\n ...records.filter(\n record => !clearedBeforeLoad && !entries.has(record.id) && !removed.has(record.id)\n ),\n ...entries.values()\n ]\n .sort((a, b) => a.createdAt - b.createdAt)\n .map(record => [record.id, { ...record, sent: false } as OutboxEntry<M>])\n );\n changed();\n })\n // Even without its stored entries, the outbox works from memory.\n .finally(() => {\n loaded = true;\n removed.clear();\n flush();\n });\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n ready.catch(noop);\n\n /** What was sent on the last connection may not have arrived: send it again on the next. */\n function unsend() {\n let changes = false;\n for (const entry of entries.values()) {\n if (entry.sent) {\n entries.set(entry.id, { ...entry, sent: false });\n changes = true;\n }\n }\n if (changes) changed();\n }\n\n if (channel) {\n channel.onmessage = ({ data }: MessageEvent<{ id?: string; before?: number } | null>) => {\n // Another tab cleared: drop everything held now, whenever it was added.\n if (data?.before) {\n lastCreated = Math.max(lastCreated, data.before);\n dropAll();\n } else if (data?.id) drop(data.id);\n };\n }\n\n const offs = [\n () => {\n // A closed channel throws on `postMessage`, which `remove()` and `clear()` still call.\n channel?.close();\n channel = undefined;\n },\n client.on('open', flush),\n client.subscribe(() => {\n if (client.getSnapshot().status !== 'open') unsend();\n }),\n client.on('message', message => {\n const id = options.ack?.(message);\n if (id != null) forget(String(id)).catch(noop);\n })\n ];\n\n return {\n client,\n ready,\n add(message, id = randomId()) {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const record: OutboxRecord<M> = { id, message, createdAt: lastCreated };\n // Re-adding an id moves it to the end, as a new message.\n entries.delete(id);\n entries.set(id, { ...record, sent: false });\n addedSinceClear?.add(id);\n changed();\n flush();\n // Sent, with no ack to wait for: there's nothing to keep. Storing it now would outlive its\n // delete, and send it again after a reload.\n if (!entries.has(id)) return Promise.resolve(id);\n return storage.put(record).then(() => id);\n },\n remove: forget,\n clear() {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const kept = (addedSinceClear = new Set<string>());\n // At once, like `remove()`: waiting for the stored entries would send them first.\n dropAll();\n channel?.postMessage({ before: lastCreated });\n // Everything stored, by other tabs and earlier page loads too, but not what's added from\n // now on.\n return storage\n .load()\n .then(records =>\n Promise.all(\n records.filter(record => !kept.has(record.id)).map(record => storage.delete(record.id))\n )\n )\n .then(() => {\n if (addedSinceClear === kept) addedSinceClear = undefined;\n });\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n for (const off of offs) off();\n release?.();\n release = undefined;\n }\n };\n}\n"],"mappings":";;;AAoGA,SAAgB,iBAAiB,MAA6B;CAC5D,IAAI;CAGJ,MAAM,MAAM,OACV,MACA,QACe;EACf,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,OAAO,UAAU,KAAK,0BAA0B,QAAQ,CAAC;GAC/D,KAAK,wBAAwB,KAAK,OAAO,kBAAkB,WAAW,EAAE,SAAS,KAAK,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Q,kCAAkB,IAAI,IAAY;GAEhD,QAAQ;GACR,SAAS,YAAY,EAAE,QAAQ,YAAY,CAAC;GAG5C,OAAO,QACJ,KAAK,CAAC,CACN,MAAK,YACJ,QAAQ,IACN,QAAQ,QAAO,WAAU,CAAC,KAAK,IAAI,OAAO,EAAE,CAAC,CAAC,CAAC,KAAI,WAAU,QAAQ,OAAO,OAAO,EAAE,CAAC,CACxF,CACF,CAAC,CACA,WAAW;IACV,IAAI,oBAAoB,MAAM,kBAAkB,KAAA;GAClD,CAAC;EACL;EACA,mBAAmB;EACnB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,WAAW;GACX,KAAK,MAAM,OAAO,MAAM,IAAI;GAC5B,UAAU;GACV,UAAU,KAAA;EACZ;CACF;AACF"}
package/dist/outbox.d.cts CHANGED
@@ -1,5 +1,4 @@
1
- import { t as WebSocketClient } from "./types-paLT8yQF.cjs";
2
- //#region src/outbox.d.ts
1
+ import { t as WebSocketClient } from "./types-DyZm2F7B.cjs";
3
2
  /** What an outbox stores for each message. */
4
3
  export interface OutboxRecord<M = unknown> {
5
4
  /** The message's idempotency key, sent with it every time. */
@@ -123,5 +122,4 @@ export declare function memoryStorage(): OutboxStorage;
123
122
  * ```
124
123
  */
125
124
  export declare function createWebSocketOutbox<M, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketOutboxOptions<M, NoInfer<In>, NoInfer<Out>>): WebSocketOutbox<M>;
126
- //#endregion
127
125
  //# sourceMappingURL=outbox.d.cts.map
package/dist/outbox.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { WebSocketClient } from "./core.js";
2
- //#region src/outbox.d.ts
3
2
  /** What an outbox stores for each message. */
4
3
  export interface OutboxRecord<M = unknown> {
5
4
  /** The message's idempotency key, sent with it every time. */
@@ -123,5 +122,4 @@ export declare function memoryStorage(): OutboxStorage;
123
122
  * ```
124
123
  */
125
124
  export declare function createWebSocketOutbox<M, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketOutboxOptions<M, NoInfer<In>, NoInfer<Out>>): WebSocketOutbox<M>;
126
- //#endregion
127
125
  //# sourceMappingURL=outbox.d.ts.map
package/dist/outbox.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/outbox.ts
1
+ // src/outbox.ts
2
2
  /** Keep outbox entries in IndexedDB, in the database `react-websocket-outbox:<name>`. */
3
3
  function indexedDBStorage(name) {
4
4
  let db;
@@ -79,9 +79,10 @@ function createWebSocketOutbox(client, options) {
79
79
  const removed = /* @__PURE__ */ new Set();
80
80
  let clearedBeforeLoad = false;
81
81
  let addedSinceClear;
82
- const channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
82
+ let channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
83
83
  let disposed = false;
84
84
  let release;
85
+ let sentOn = null;
85
86
  let lastCreated = 0;
86
87
  function changed() {
87
88
  snapshot = [...entries.values()];
@@ -114,11 +115,16 @@ function createWebSocketOutbox(client, options) {
114
115
  return storage.delete(id);
115
116
  }
116
117
  function flush() {
117
- if (!loaded || disposed || client.socket?.readyState !== 1) return;
118
+ const socket = client.socket;
119
+ if (!loaded || disposed || socket?.readyState !== 1) return;
120
+ if (socket !== sentOn) {
121
+ unsend();
122
+ sentOn = socket;
123
+ }
118
124
  const now = Date.now();
119
125
  let sent = false;
120
126
  for (const entry of [...entries.values()]) {
121
- if (entry.sent) continue;
127
+ if (entry.sent || entries.get(entry.id) !== entry) continue;
122
128
  if (now - entry.createdAt > maxAge) {
123
129
  forget(entry.id).catch(noop);
124
130
  options.onExpire?.(entry);
@@ -168,11 +174,11 @@ function createWebSocketOutbox(client, options) {
168
174
  } else if (data?.id) drop(data.id);
169
175
  };
170
176
  const offs = [
171
- () => channel?.close(),
172
- client.on("open", () => {
173
- unsend();
174
- flush();
175
- }),
177
+ () => {
178
+ channel?.close();
179
+ channel = void 0;
180
+ },
181
+ client.on("open", flush),
176
182
  client.subscribe(() => {
177
183
  if (client.getSnapshot().status !== "open") unsend();
178
184
  }),
@@ -227,7 +233,6 @@ function createWebSocketOutbox(client, options) {
227
233
  }
228
234
  };
229
235
  }
230
- //#endregion
231
236
  export { createWebSocketOutbox, indexedDBStorage, memoryStorage };
232
237
 
233
238
  //# sourceMappingURL=outbox.js.map