gemi 0.128.0 → 0.130.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.
Files changed (90) hide show
  1. package/dist/{chunk-0mp9tck6.js → chunk-0ryswty9.js} +20 -20
  2. package/dist/{chunk-0mp9tck6.js.map → chunk-0ryswty9.js.map} +5 -4
  3. package/dist/{chunk-df0mekds.js → chunk-13agap7z.js} +1 -1
  4. package/dist/{chunk-qz0da20r.js → chunk-7ynnce4b.js} +1 -1
  5. package/dist/{chunk-wzfvwvz0.js → chunk-jj1ppnnk.js} +2 -2
  6. package/dist/{chunk-wzfvwvz0.js.map → chunk-jj1ppnnk.js.map} +1 -1
  7. package/dist/{chunk-tchte4dv.js → chunk-xtqhagxz.js} +2 -2
  8. package/dist/{chunk-tchte4dv.js.map → chunk-xtqhagxz.js.map} +1 -1
  9. package/dist/chunks/MutationError-DuKqBW8o.js +199 -0
  10. package/dist/chunks/MutationError-DuKqBW8o.js.map +1 -0
  11. package/dist/chunks/RealtimeClient-DsWbFRC7.js +553 -0
  12. package/dist/chunks/RealtimeClient-DsWbFRC7.js.map +1 -0
  13. package/dist/chunks/{ThemeProvider-BIrCSrFY.js → ThemeProvider-gWqXjGh-.js} +173 -578
  14. package/dist/chunks/ThemeProvider-gWqXjGh-.js.map +1 -0
  15. package/dist/chunks/channelKey-CIhHpX6x.js +10 -0
  16. package/dist/chunks/channelKey-CIhHpX6x.js.map +1 -0
  17. package/dist/chunks/fetchFileRequest-BSrgYnAy.js +57 -0
  18. package/dist/chunks/fetchFileRequest-BSrgYnAy.js.map +1 -0
  19. package/dist/chunks/live-CUdMhXHL.js +88 -0
  20. package/dist/chunks/live-CUdMhXHL.js.map +1 -0
  21. package/dist/chunks/mutationExtras-CtY-X9m7.js +115 -0
  22. package/dist/chunks/mutationExtras-CtY-X9m7.js.map +1 -0
  23. package/dist/chunks/subscriptionStream-CULcRbx0.js +166 -0
  24. package/dist/chunks/subscriptionStream-CULcRbx0.js.map +1 -0
  25. package/dist/client/MutationError.d.ts +7 -9
  26. package/dist/client/MutationError.d.ts.map +1 -1
  27. package/dist/client/QueryResource.d.ts +3 -11
  28. package/dist/client/QueryResource.d.ts.map +1 -1
  29. package/dist/client/fetchFile.d.ts +4 -7
  30. package/dist/client/fetchFile.d.ts.map +1 -1
  31. package/dist/client/fetchFileRequest.d.ts +14 -0
  32. package/dist/client/fetchFileRequest.d.ts.map +1 -0
  33. package/dist/client/index.d.ts +1 -1
  34. package/dist/client/index.d.ts.map +1 -1
  35. package/dist/client/index.js +201 -664
  36. package/dist/client/index.js.map +1 -1
  37. package/dist/client/init.d.ts +1 -1
  38. package/dist/client/init.d.ts.map +1 -1
  39. package/dist/client/lazyModule.d.ts +32 -0
  40. package/dist/client/lazyModule.d.ts.map +1 -0
  41. package/dist/client/mutationErrorHelpers.d.ts +11 -0
  42. package/dist/client/mutationErrorHelpers.d.ts.map +1 -0
  43. package/dist/client/mutationExtras.d.ts +3 -0
  44. package/dist/client/mutationExtras.d.ts.map +1 -0
  45. package/dist/client/mutationModules.d.ts +17 -0
  46. package/dist/client/mutationModules.d.ts.map +1 -0
  47. package/dist/client/queryUpdates.d.ts +22 -0
  48. package/dist/client/queryUpdates.d.ts.map +1 -0
  49. package/dist/client/realtime/FakeSocket.d.ts +1 -1
  50. package/dist/client/realtime/FakeSocket.d.ts.map +1 -1
  51. package/dist/client/realtime/RealtimeClient.d.ts +7 -18
  52. package/dist/client/realtime/RealtimeClient.d.ts.map +1 -1
  53. package/dist/client/realtime/channelKey.d.ts +4 -0
  54. package/dist/client/realtime/channelKey.d.ts.map +1 -0
  55. package/dist/client/realtime/live.d.ts +31 -0
  56. package/dist/client/realtime/live.d.ts.map +1 -0
  57. package/dist/client/realtime/loader.d.ts +56 -0
  58. package/dist/client/realtime/loader.d.ts.map +1 -0
  59. package/dist/client/realtime/useChannelSubscription.d.ts +1 -1
  60. package/dist/client/realtime/useChannelSubscription.d.ts.map +1 -1
  61. package/dist/client/subscriptionStream.d.ts +36 -0
  62. package/dist/client/subscriptionStream.d.ts.map +1 -0
  63. package/dist/client/useChannel.d.ts +1 -13
  64. package/dist/client/useChannel.d.ts.map +1 -1
  65. package/dist/client/useMutation.d.ts +1 -1
  66. package/dist/client/useMutation.d.ts.map +1 -1
  67. package/dist/client/useQuery.d.ts +1 -1
  68. package/dist/client/useQuery.d.ts.map +1 -1
  69. package/dist/client/useSetQueryData.d.ts +4 -17
  70. package/dist/client/useSetQueryData.d.ts.map +1 -1
  71. package/dist/client/useSubscription.d.ts +5 -10
  72. package/dist/client/useSubscription.d.ts.map +1 -1
  73. package/dist/facades/index.js +1 -1
  74. package/dist/http/index.js +1 -1
  75. package/dist/i18n/index.js +1 -1
  76. package/dist/kernel/index.js +1 -1
  77. package/dist/server/index.js +1 -1
  78. package/dist/services/broadcast/protocol.d.ts +1 -2
  79. package/dist/services/broadcast/protocol.d.ts.map +1 -1
  80. package/dist/services/broadcast/socketHeader.d.ts +9 -0
  81. package/dist/services/broadcast/socketHeader.d.ts.map +1 -0
  82. package/dist/services/index.js +2 -2
  83. package/dist/services/index.js.map +1 -1
  84. package/dist/testing/Page.d.ts.map +1 -1
  85. package/dist/testing/index.js +4 -1
  86. package/dist/testing/index.js.map +1 -1
  87. package/package.json +1 -1
  88. package/dist/chunks/ThemeProvider-BIrCSrFY.js.map +0 -1
  89. /package/dist/{chunk-df0mekds.js.map → chunk-13agap7z.js.map} +0 -0
  90. /package/dist/{chunk-qz0da20r.js.map → chunk-7ynnce4b.js.map} +0 -0
@@ -178,18 +178,7 @@ var QueryResource = class {
178
178
  const current = store.get(variantKey);
179
179
  if (current?.loading) continue;
180
180
  if (current?.hasData && current.data === data) continue;
181
- store.set(variantKey, {
182
- loading: false,
183
- data,
184
- hasData: true,
185
- error: null,
186
- version: now
187
- });
188
- this.staleVariants.delete(variantKey);
189
- this.lastFetchRecord.set(variantKey, now);
190
- this.failures.delete(variantKey);
191
- this.cancelRetry(variantKey);
192
- this.settle(variantKey);
181
+ this.fill(store, variantKey, data, now);
193
182
  changed = true;
194
183
  }
195
184
  if (changed) this.store.next(store);
@@ -463,30 +452,18 @@ var QueryResource = class {
463
452
  }));
464
453
  this.resolveVariant(variantKey, false, false);
465
454
  }
466
- /**
467
- * Write data the server just produced (a mutation's answer) into a
468
- * variant, with no refetch: unlike `mutate`, the value is not a guess to
469
- * reconcile. The variant counts as freshly fetched, so its `staleTime`
470
- * starts again, and a GET already on the wire for it is dropped when it
471
- * lands, since it may carry the data from before the write. A reader
472
- * suspended on the variant wakes up with it (#897).
473
- */
474
- set(variantKey, data) {
475
- this.dropHttpCache(variantKey);
476
- const now = Date.now();
477
- this.markApplied(variantKey);
478
- this.staleVariants.delete(variantKey);
479
- this.lastFetchRecord.set(variantKey, now);
480
- this.failures.delete(variantKey);
481
- this.cancelRetry(variantKey);
482
- const store = this.store.getValue();
483
- this.store.next(store.set(variantKey, {
455
+ fill(store, variantKey, data, now) {
456
+ store.set(variantKey, {
484
457
  loading: false,
485
458
  data,
486
459
  hasData: true,
487
460
  error: null,
488
461
  version: now
489
- }));
462
+ });
463
+ this.staleVariants.delete(variantKey);
464
+ this.lastFetchRecord.set(variantKey, now);
465
+ this.failures.delete(variantKey);
466
+ this.cancelRetry(variantKey);
490
467
  this.settle(variantKey);
491
468
  }
492
469
  refetch(variantKey) {
@@ -752,575 +729,108 @@ function toVariantKey(search) {
752
729
  return searchParams.toString();
753
730
  }
754
731
  //#endregion
755
- //#region services/broadcast/protocol.ts
756
- /**
757
- * The `gemi.v1` WebSocket protocol, shared by the server transport
758
- * (`SocketHub`) and the browser client (`gemi/client`'s connection manager).
759
- * Types and constants only: this module is imported by the browser bundle, so
760
- * it must never import a server module.
761
- *
762
- * Every frame is a JSON text frame. Binary frames are refused.
763
- *
764
- * From the client:
765
- *
766
- * - `{op:"sub", id, ch, p?}`: subscribe `id` (chosen by the client, unique per
767
- * socket) to the channel pattern `ch` with params `p`. The server builds
768
- * the topic and authorizes it.
769
- * - `{op:"unsub", id}`
770
- * - `{op:"ping"}`: answered with `pong`. The client sends one every
771
- * `heartbeatMs` and reconnects when it hears nothing for twice that.
772
- *
773
- * From the server:
774
- *
775
- * - `{op:"hello", socketId, tag, heartbeatMs}`: the first frame. `socketId`
776
- * goes in the `X-Gemi-Socket` header of the client's own requests (for
777
- * `Broadcast.toOthers`); it is never shown to anyone else. `tag` is what
778
- * an event frame's `x` carries when it skips this socket.
779
- * - `{op:"subscribed", id, t}`: `id` joined topic `t`. Sent only once this
780
- * process receives the topic's events, so the resync the client runs on it
781
- * cannot miss one.
782
- * - `{op:"denied", id, code}`: `id` was refused, or later revoked.
783
- * - `{op:"ev", t, ev, d?, x?}`: an event on topic `t`. Dropped by the socket
784
- * whose `tag` is `x`.
785
- * - `{op:"gap"}`: events may have been lost for this socket; resync all.
786
- * - `{op:"pong"}`
787
- * - `{op:"bye", code, retryAfter}`: the server is going away (a restart).
788
- * Reconnect after `retryAfter` ms.
789
- */
790
- /** The WebSocket subprotocol. */
791
- var BROADCAST_PROTOCOL = "gemi.v1";
792
- /** The request header a client sends its socket id in, for `toOthers`. */
793
- var SOCKET_ID_HEADER = "x-gemi-socket";
732
+ //#region client/lazyModule.ts
794
733
  /**
795
- * Close codes the server uses. 1012 and 1013 are the standard "restart" and
796
- * "try again later"; the 4xxx ones are gemi's own.
734
+ * What a lazy `import()` resolved to, or a thrown error when it is missing.
735
+ * Vite's preload helper resolves the `import()` to `undefined` instead of
736
+ * rejecting when a `vite:preloadError` listener handled the failure (`init`'s
737
+ * chunk-load recovery does, as it starts a reload): treated as a failed load.
797
738
  */
798
- var CloseCode = {
799
- /** The client went away (tab closed, socket released). */
800
- Normal: 1e3,
801
- /** A frame that was not JSON text, or not a known op. */
802
- UnsupportedData: 1003,
803
- /** Too many frames, or a frame over the size limit. */
804
- PolicyViolation: 1008,
805
- /** The server is restarting; `bye` said when to come back. */
806
- Restart: 1012,
807
- /** The socket fell too far behind; reconnect and resync. */
808
- TryAgainLater: 1013,
809
- /** The socket's user was signed out or its access revoked. */
810
- Revoked: 4001
811
- };
739
+ function loadedModule(module) {
740
+ if (!module) throw new Error("[gemi] A lazily loaded chunk is unavailable.");
741
+ return module;
742
+ }
812
743
  /**
813
- * Whether a refusal is final for this socket's session: resubscribing will
814
- * get the same answer, so the client does not retry it on its own.
744
+ * The module, loading it if it is not there yet. Callers while it loads share
745
+ * one load, so their callbacks run in call order. A failed load is not kept:
746
+ * the next call runs `import()` again.
815
747
  */
816
- function isPermanentDenial(code) {
817
- return code === "unknown_channel" || code === "invalid_params" || code === "invalid";
748
+ function loadLazy(lazy) {
749
+ if (lazy.current) return Promise.resolve(lazy.current);
750
+ return lazy.loading ??= lazy.load().then((module) => {
751
+ lazy.loading = null;
752
+ return lazy.current = loadedModule(module);
753
+ }, (error) => {
754
+ lazy.loading = null;
755
+ throw error;
756
+ });
818
757
  }
819
758
  //#endregion
820
- //#region client/realtime/RealtimeClient.ts
821
- /** The minimum gap between two resyncs of one subscription. */
822
- var RESYNC_COALESCE_MS = 2e3;
823
- /** How long the socket stays open after its last subscription goes. */
824
- var IDLE_CLOSE_MS = 5e3;
759
+ //#region client/realtime/loader.ts
825
760
  /**
826
- * How long a subscription outlives its last listener. A hook that remounts
827
- * within it (StrictMode's double mount, a route change back, a list that
828
- * re-renders its rows) picks the same subscription up again: no `unsub`, no
829
- * new `sub`, nothing counted against the server's rate limit.
761
+ * The tab's client, once loaded and created (`tabClient` in
762
+ * `./RealtimeClient` creates it), and the options it is created with.
830
763
  */
831
- var RELEASE_LINGER_MS = 1500;
832
- /** The least wait before resending a `sub` denied with `rate_limited`. */
833
- var RATE_LIMITED_RETRY_MS = 5e3;
834
- var MIN_BACKOFF_MS = 1e3;
835
- var MAX_BACKOFF_MS = 3e4;
836
- var DEFAULT_HEARTBEAT_MS = 25e3;
837
- var DEFAULT_HIDDEN_DISCONNECT_MS = 6e4;
838
- /** `pattern` and its params, canonical: two hooks on one channel share a `sub`. */
839
- function channelKey(pattern, params) {
840
- const sorted = Object.keys(params).sort().map((key) => [key, String(params[key])]);
841
- return `${pattern}\u0000${JSON.stringify(sorted)}`;
842
- }
764
+ var realtime = {
765
+ client: null,
766
+ options: {}
767
+ };
843
768
  /**
844
- * The tab's one WebSocket to the app (`gemi.v1`), multiplexing every channel
845
- * the mounted hooks subscribe to.
846
- *
847
- * Opened by the first subscription and closed a few seconds after the last
848
- * one goes. Reconnects with full-jitter backoff (1 to 30 s), or after the
849
- * server's `bye.retryAfter`, at once on `online`; resubscribes everything
850
- * then. A tab hidden for `hiddenDisconnectMs` disconnects, and reconnects
851
- * when shown. Every `subscribed` ack and every `gap` resyncs the
852
- * subscription (coalesced to one per 2 s), because events are volatile: a
853
- * client that may have missed one refetches over HTTP.
769
+ * Sets the socket options (`init({ realtime })` calls it). Takes effect on
770
+ * the next connection.
854
771
  */
855
- var RealtimeClient = class {
856
- options;
857
- internals;
858
- ws = null;
859
- entries = /* @__PURE__ */ new Map();
860
- byId = /* @__PURE__ */ new Map();
861
- topics = /* @__PURE__ */ new Map();
862
- nextId = 1;
863
- attempt = 0;
864
- tag = null;
865
- socketIdValue = null;
866
- heartbeatMs = DEFAULT_HEARTBEAT_MS;
867
- reconnectTimer = null;
868
- idleTimer = null;
869
- hiddenTimer = null;
870
- pingTimer = null;
871
- livenessTimer = null;
872
- retryAfter = null;
873
- revoked = false;
874
- pausedWhileHidden = false;
875
- listening = false;
876
- constructor(options = {}, internals = {}) {
877
- this.options = withDefaults(options);
878
- this.internals = internals;
879
- }
880
- configure(options) {
881
- this.options = withDefaults({
882
- ...this.options,
883
- ...options
884
- });
885
- }
886
- /** The id to send as `X-Gemi-Socket`, while the socket is open. */
887
- get socketId() {
888
- return this.socketIdValue;
889
- }
890
- subscribe(pattern, params, listener) {
891
- const key = channelKey(pattern, params);
892
- let entry = this.entries.get(key);
893
- if (!entry) {
894
- entry = {
895
- key,
896
- id: String(this.nextId++),
897
- pattern,
898
- params: { ...params },
899
- listeners: /* @__PURE__ */ new Set(),
900
- status: "closed",
901
- code: null,
902
- permanent: false,
903
- topic: null,
904
- lastResyncAt: 0,
905
- resyncTimer: null,
906
- lingerTimer: null,
907
- retryTimer: null,
908
- retries: 0
909
- };
910
- this.entries.set(key, entry);
911
- this.byId.set(entry.id, entry);
912
- if (this.isOpen()) this.sendSub(entry);
913
- }
914
- if (entry.lingerTimer) {
915
- clearTimeout(entry.lingerTimer);
916
- entry.lingerTimer = null;
917
- }
918
- entry.listeners.add(listener);
919
- listener.onStatus?.(entry.status, entry.code);
920
- this.cancelIdleClose();
921
- this.listen();
922
- if (!this.ws && !this.reconnectTimer && !this.pausedWhileHidden) this.connect();
923
- let released = false;
924
- return () => {
925
- if (released) return;
926
- released = true;
927
- this.release(entry, listener);
928
- };
929
- }
930
- release(entry, listener) {
931
- entry.listeners.delete(listener);
932
- if (entry.listeners.size > 0 || entry.lingerTimer) return;
933
- entry.lingerTimer = setTimeout(() => {
934
- entry.lingerTimer = null;
935
- if (entry.listeners.size === 0) this.drop(entry);
936
- }, RELEASE_LINGER_MS);
937
- }
938
- drop(entry) {
939
- if (entry.resyncTimer) clearTimeout(entry.resyncTimer);
940
- this.clearRetry(entry);
941
- this.entries.delete(entry.key);
942
- this.byId.delete(entry.id);
943
- this.dropTopic(entry);
944
- if (this.isOpen() && (entry.status === "open" || entry.status === "connecting")) this.send({
945
- op: "unsub",
946
- id: entry.id
947
- });
948
- if (this.entries.size === 0) this.scheduleIdleClose();
949
- }
950
- isOpen() {
951
- return this.ws !== null && this.ws.readyState === 1;
952
- }
953
- connect() {
954
- if (typeof window === "undefined") return;
955
- if (this.entries.size === 0) return;
956
- const Impl = this.internals.WebSocket ?? globalThis.WebSocket;
957
- if (!Impl) return;
958
- this.clearReconnect();
959
- let ws;
960
- try {
961
- ws = new Impl(this.url(), [BROADCAST_PROTOCOL]);
962
- } catch {
963
- this.scheduleReconnect();
964
- return;
965
- }
966
- this.ws = ws;
967
- for (const entry of this.entries.values()) if (!entry.permanent) this.setStatus(entry, "connecting", null);
968
- ws.onopen = () => {
969
- if (this.ws !== ws) return;
970
- this.touch();
971
- for (const entry of this.entries.values()) {
972
- if (entry.permanent) continue;
973
- entry.retries = 0;
974
- this.sendSub(entry);
975
- }
976
- };
977
- ws.onmessage = (event) => {
978
- if (this.ws !== ws) return;
979
- this.touch();
980
- let frame;
981
- try {
982
- frame = JSON.parse(String(event.data));
983
- } catch {
984
- return;
985
- }
986
- this.handle(frame);
987
- };
988
- ws.onclose = (event) => {
989
- if (this.ws !== ws) return;
990
- this.onClosed(event.code);
991
- };
992
- ws.onerror = () => {};
993
- }
994
- url() {
995
- if (this.internals.url) return this.internals.url;
996
- const { protocol, host } = window.location;
997
- return `${protocol === "https:" ? "wss:" : "ws:"}//${host}${this.options.path}`;
998
- }
999
- sendSub(entry) {
1000
- this.setStatus(entry, "connecting", null);
1001
- const frame = {
1002
- op: "sub",
1003
- id: entry.id,
1004
- ch: entry.pattern
1005
- };
1006
- if (Object.keys(entry.params).length > 0) frame.p = entry.params;
1007
- this.send(frame);
1008
- }
1009
- send(frame) {
1010
- if (!this.isOpen()) return;
1011
- try {
1012
- this.ws.send(JSON.stringify(frame));
1013
- } catch {}
1014
- }
1015
- handle(frame) {
1016
- switch (frame.op) {
1017
- case "hello":
1018
- this.socketIdValue = frame.socketId;
1019
- this.tag = frame.tag;
1020
- this.attempt = 0;
1021
- this.revoked = false;
1022
- if (frame.heartbeatMs > 0) this.heartbeatMs = frame.heartbeatMs;
1023
- this.startHeartbeat();
1024
- return;
1025
- case "subscribed": {
1026
- const entry = this.byId.get(frame.id);
1027
- if (!entry) return;
1028
- this.dropTopic(entry);
1029
- entry.topic = frame.t;
1030
- let ids = this.topics.get(frame.t);
1031
- if (!ids) this.topics.set(frame.t, ids = /* @__PURE__ */ new Set());
1032
- ids.add(entry.id);
1033
- this.clearRetry(entry);
1034
- entry.retries = 0;
1035
- this.setStatus(entry, "open", null);
1036
- this.resync(entry);
1037
- return;
1038
- }
1039
- case "denied": {
1040
- const entry = this.byId.get(frame.id);
1041
- if (!entry) return;
1042
- this.dropTopic(entry);
1043
- entry.permanent = isPermanentDenial(frame.code);
1044
- this.setStatus(entry, "denied", frame.code);
1045
- this.scheduleRetry(entry, frame.code);
1046
- return;
1047
- }
1048
- case "ev": {
1049
- if (frame.x !== void 0 && frame.x === this.tag) return;
1050
- const ids = this.topics.get(frame.t);
1051
- if (!ids) return;
1052
- for (const id of Array.from(ids)) {
1053
- const entry = this.byId.get(id);
1054
- if (!entry) continue;
1055
- for (const listener of Array.from(entry.listeners)) try {
1056
- listener.onEvent?.(frame.ev, frame.d);
1057
- } catch (error) {
1058
- reportListenerError(error);
1059
- }
1060
- }
1061
- return;
1062
- }
1063
- case "gap":
1064
- for (const entry of this.entries.values()) if (entry.status === "open") this.resync(entry);
1065
- return;
1066
- case "bye":
1067
- this.retryAfter = Math.max(0, Number(frame.retryAfter) || 0);
1068
- return;
1069
- case "pong": return;
1070
- }
1071
- }
1072
- onClosed(code) {
1073
- this.ws = null;
1074
- this.socketIdValue = null;
1075
- this.tag = null;
1076
- this.stopHeartbeat();
1077
- this.topics.clear();
1078
- for (const entry of this.entries.values()) {
1079
- entry.topic = null;
1080
- this.clearRetry(entry);
1081
- if (!entry.permanent) this.setStatus(entry, "closed", null);
1082
- }
1083
- if (code === CloseCode.Revoked) this.revoked = true;
1084
- if (this.entries.size > 0 && !this.pausedWhileHidden) this.scheduleReconnect();
1085
- }
1086
- scheduleReconnect() {
1087
- this.clearReconnect();
1088
- let delay;
1089
- if (this.retryAfter !== null) {
1090
- delay = this.retryAfter;
1091
- this.retryAfter = null;
1092
- } else if (this.revoked) {
1093
- this.revoked = false;
1094
- delay = Math.floor(this.random() * 500);
1095
- } else delay = backoffDelay(this.attempt, this.random());
1096
- this.attempt++;
1097
- this.reconnectTimer = setTimeout(() => {
1098
- this.reconnectTimer = null;
1099
- this.connect();
1100
- }, delay);
1101
- }
1102
- clearReconnect() {
1103
- if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
1104
- this.reconnectTimer = null;
1105
- }
1106
- random() {
1107
- return (this.internals.random ?? Math.random)();
1108
- }
1109
- startHeartbeat() {
1110
- this.stopHeartbeat();
1111
- this.pingTimer = setInterval(() => this.send({ op: "ping" }), this.heartbeatMs);
1112
- this.touch();
1113
- }
1114
- stopHeartbeat() {
1115
- if (this.pingTimer) clearInterval(this.pingTimer);
1116
- if (this.livenessTimer) clearTimeout(this.livenessTimer);
1117
- this.pingTimer = null;
1118
- this.livenessTimer = null;
1119
- }
1120
- /** Anything from the server proves the socket alive. */
1121
- touch() {
1122
- if (this.livenessTimer) clearTimeout(this.livenessTimer);
1123
- const ws = this.ws;
1124
- this.livenessTimer = setTimeout(() => {
1125
- if (this.ws !== ws || !ws) return;
1126
- try {
1127
- ws.close();
1128
- } catch {}
1129
- this.onClosed(1006);
1130
- }, this.heartbeatMs * 2);
1131
- }
1132
- setStatus(entry, status, code) {
1133
- if (entry.status === status && entry.code === code) return;
1134
- entry.status = status;
1135
- entry.code = code;
1136
- for (const listener of Array.from(entry.listeners)) try {
1137
- listener.onStatus?.(status, code);
1138
- } catch (error) {
1139
- reportListenerError(error);
1140
- }
1141
- }
1142
- /** At most one resync per subscription per 2 s; a later one is deferred, not dropped. */
1143
- resync(entry) {
1144
- if (entry.resyncTimer) return;
1145
- const now = Date.now();
1146
- const wait = entry.lastResyncAt + RESYNC_COALESCE_MS - now;
1147
- const fire = () => {
1148
- entry.resyncTimer = null;
1149
- entry.lastResyncAt = Date.now();
1150
- for (const listener of Array.from(entry.listeners)) try {
1151
- listener.onResync?.();
1152
- } catch (error) {
1153
- reportListenerError(error);
1154
- }
1155
- };
1156
- if (entry.lastResyncAt === 0 || wait <= 0) fire();
1157
- else entry.resyncTimer = setTimeout(fire, wait);
1158
- }
1159
- /**
1160
- * A transient denial (`rate_limited`, `error`, `limit`) is retried on the
1161
- * same socket, with backoff: a healthy socket may never reconnect. `denied`
1162
- * and `revoked` are the channel's answer for this session, so they wait for
1163
- * the next connection (a sign-in reconnects), and a permanent one is never
1164
- * resent. `limit` gives up after `MAX_LIMIT_RETRIES` on one socket.
1165
- */
1166
- scheduleRetry(entry, code) {
1167
- if (code !== "rate_limited" && code !== "error" && code !== "limit") return;
1168
- if (code === "limit" && entry.retries >= 5) return;
1169
- this.clearRetry(entry);
1170
- const delay = Math.max(code === "rate_limited" ? RATE_LIMITED_RETRY_MS : MIN_BACKOFF_MS, backoffDelay(entry.retries, this.random()));
1171
- entry.retries++;
1172
- entry.retryTimer = setTimeout(() => {
1173
- entry.retryTimer = null;
1174
- if (this.entries.get(entry.key) !== entry || entry.status !== "denied") return;
1175
- if (this.isOpen()) this.sendSub(entry);
1176
- }, delay);
1177
- }
1178
- clearRetry(entry) {
1179
- if (entry.retryTimer) clearTimeout(entry.retryTimer);
1180
- entry.retryTimer = null;
1181
- }
1182
- dropTopic(entry) {
1183
- if (!entry.topic) return;
1184
- const ids = this.topics.get(entry.topic);
1185
- ids?.delete(entry.id);
1186
- if (ids && ids.size === 0) this.topics.delete(entry.topic);
1187
- entry.topic = null;
1188
- }
1189
- scheduleIdleClose() {
1190
- this.cancelIdleClose();
1191
- this.idleTimer = setTimeout(() => {
1192
- this.idleTimer = null;
1193
- if (this.entries.size > 0) return;
1194
- this.clearReconnect();
1195
- this.close();
1196
- }, IDLE_CLOSE_MS);
1197
- }
1198
- cancelIdleClose() {
1199
- if (this.idleTimer) clearTimeout(this.idleTimer);
1200
- this.idleTimer = null;
1201
- }
1202
- /** Closes the socket without reconnecting. */
1203
- close() {
1204
- const ws = this.ws;
1205
- if (!ws) return;
1206
- this.ws = null;
1207
- try {
1208
- ws.close(CloseCode.Normal);
1209
- } catch {}
1210
- this.onClosed(CloseCode.Normal);
1211
- }
1212
- listen() {
1213
- if (this.listening || typeof window === "undefined") return;
1214
- this.listening = true;
1215
- window.addEventListener("online", this.onOnline);
1216
- if (typeof document !== "undefined") document.addEventListener("visibilitychange", this.onVisibility);
1217
- }
1218
- onOnline = () => {
1219
- if (this.entries.size === 0 || this.ws || this.pausedWhileHidden) return;
1220
- this.attempt = 0;
1221
- this.connect();
1222
- };
1223
- onVisibility = () => {
1224
- if (document.visibilityState === "hidden") {
1225
- if (this.hiddenTimer) return;
1226
- this.hiddenTimer = setTimeout(() => {
1227
- this.hiddenTimer = null;
1228
- if (document.visibilityState !== "hidden") return;
1229
- this.pausedWhileHidden = true;
1230
- this.clearReconnect();
1231
- this.close();
1232
- }, this.options.hiddenDisconnectMs);
1233
- return;
1234
- }
1235
- if (this.hiddenTimer) clearTimeout(this.hiddenTimer);
1236
- this.hiddenTimer = null;
1237
- if (this.pausedWhileHidden) {
1238
- this.pausedWhileHidden = false;
1239
- this.attempt = 0;
1240
- this.connect();
1241
- }
1242
- };
1243
- /**
1244
- * Drops the socket and opens a new one at once, when anything is
1245
- * subscribed. A socket keeps the session it was opened with (the upgrade's
1246
- * cookies), so signing in or out in this tab reconnects it: every channel
1247
- * is then authorized as the new session, and the acks resync.
1248
- */
1249
- reconnect() {
1250
- this.close();
1251
- this.clearReconnect();
1252
- this.attempt = 0;
1253
- if (this.entries.size > 0 && !this.pausedWhileHidden) this.connect();
1254
- }
1255
- /** For tests: drops the socket, timers and listeners. */
1256
- dispose() {
1257
- this.clearReconnect();
1258
- this.cancelIdleClose();
1259
- if (this.hiddenTimer) clearTimeout(this.hiddenTimer);
1260
- for (const entry of this.entries.values()) {
1261
- if (entry.resyncTimer) clearTimeout(entry.resyncTimer);
1262
- if (entry.lingerTimer) clearTimeout(entry.lingerTimer);
1263
- this.clearRetry(entry);
1264
- }
1265
- this.entries.clear();
1266
- this.byId.clear();
1267
- this.close();
1268
- if (this.listening && typeof window !== "undefined") {
1269
- window.removeEventListener("online", this.onOnline);
1270
- document?.removeEventListener("visibilitychange", this.onVisibility);
1271
- this.listening = false;
1272
- }
1273
- }
1274
- };
1275
- /** Full jitter, 1 to 30 s: `max(1 s, random × min(30 s, 1 s × 2^attempt))`. */
1276
- function backoffDelay(attempt, random) {
1277
- const cap = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** Math.min(attempt, 10));
1278
- return Math.max(MIN_BACKOFF_MS, Math.floor(random * cap));
772
+ function configureRealtime(options = {}) {
773
+ Object.assign(realtime.options, options);
774
+ realtime.client?.configure(realtime.options);
1279
775
  }
1280
- function withDefaults(options) {
1281
- return {
1282
- path: options.path ?? "/__gemi/socket",
1283
- hiddenDisconnectMs: options.hiddenDisconnectMs ?? DEFAULT_HIDDEN_DISCONNECT_MS
1284
- };
776
+ /** The tab's client if it is already loaded, else `null`. Never loads it. */
777
+ function loadedRealtimeClient() {
778
+ return realtime.client;
1285
779
  }
1286
- function reportListenerError(error) {
1287
- setTimeout(() => {
780
+ var loading = null;
781
+ /** The lazily loaded client. Replaceable in tests, to simulate a failed load. */
782
+ var lazyModules = { client: () => import("./RealtimeClient-DsWbFRC7.js") };
783
+ /**
784
+ * `./live`, loaded by the first live query. `<Page>` in `gemi/testing` sets
785
+ * `current` up front, so a live query on a provided socket subscribes during
786
+ * its effect, as it did before the module was split out.
787
+ */
788
+ var liveModule = {
789
+ current: null,
790
+ load: () => import("./live-CUdMhXHL.js").then((n) => n.n)
791
+ };
792
+ /**
793
+ * The tab's client, loading its module and creating it on first use. `null`
794
+ * on the server. A failed load (a chunk gone after a deploy, the network) is
795
+ * not kept, so a later subscription calls `import()` again; whether that
796
+ * fetches anew is up to the browser, and the usual recovery is `init`'s
797
+ * reload.
798
+ */
799
+ function loadRealtimeClient() {
800
+ if (typeof window === "undefined") return null;
801
+ if (realtime.client) return Promise.resolve(realtime.client);
802
+ loading ??= lazyModules.client().then((module) => loadedModule(module).tabClient()).catch((error) => {
803
+ loading = null;
1288
804
  throw error;
1289
805
  });
806
+ return loading;
1290
807
  }
1291
- var configured = {};
1292
- var instance = null;
1293
808
  /**
1294
- * Sets the socket options (`init({ realtime })` calls it). Takes effect on
1295
- * the next connection.
809
+ * Follows `useQuery`'s `live` channel until the returned function is called.
810
+ * `./live` loads on first use and does the rest, loading the socket client
811
+ * in turn, so `useQuery` carries only this. `setOpen` reports `false` until
812
+ * the channel is open.
1296
813
  */
1297
- function configureRealtime(options = {}) {
1298
- configured = {
1299
- ...configured,
1300
- ...options
814
+ function followLive(provided, live, resource, setOpen) {
815
+ let stop;
816
+ const start = (module) => {
817
+ if (stop === void 0) stop = module.followLive(provided, live, resource, setOpen);
818
+ };
819
+ if (liveModule.current) start(liveModule.current);
820
+ else loadLazy(liveModule).then(start).catch(() => {});
821
+ return () => {
822
+ stop?.();
823
+ stop = null;
824
+ setOpen(false);
1301
825
  };
1302
- instance?.configure(configured);
1303
- }
1304
- /** The tab's client, created on first use. `null` on the server. */
1305
- function getRealtimeClient() {
1306
- if (typeof window === "undefined") return null;
1307
- instance ??= new RealtimeClient(configured);
1308
- return instance;
1309
826
  }
1310
827
  /**
1311
828
  * Reconnects the tab's socket, if it has one, so its channels are authorized
1312
829
  * as the current session. The auth hooks call it after signing in or out.
1313
- * Never creates the client.
830
+ * Never loads or creates the client.
1314
831
  */
1315
832
  function reconnectRealtime() {
1316
- instance?.reconnect();
1317
- }
1318
- /**
1319
- * The open socket's id, for the `X-Gemi-Socket` header, or `null`. Never
1320
- * creates the client.
1321
- */
1322
- function currentSocketId() {
1323
- return instance?.socketId ?? null;
833
+ realtime.client?.reconnect();
1324
834
  }
1325
835
  //#endregion
1326
836
  //#region client/realtime/RealtimeContext.ts
@@ -3887,6 +3397,91 @@ var ClientRouterProvider = (props) => {
3887
3397
  });
3888
3398
  };
3889
3399
  //#endregion
3400
+ //#region client/realtime/useChannelSubscription.ts
3401
+ var CLOSED = {
3402
+ status: "closed",
3403
+ code: null
3404
+ };
3405
+ var IDLE = {
3406
+ status: "idle",
3407
+ code: null
3408
+ };
3409
+ /**
3410
+ * The one subscription primitive the channel hooks share. Subscribes only in
3411
+ * an effect, so a server render, a static page or an island that never
3412
+ * mounts opens no socket; on the server it reports `closed`. Handlers may
3413
+ * change between renders without resubscribing.
3414
+ */
3415
+ function useChannelSubscription(pattern, params, handlers, enabled) {
3416
+ const active = enabled && pattern !== null;
3417
+ const [state, setState] = useState(active ? CLOSED : IDLE);
3418
+ const provided = useContext(RealtimeContext);
3419
+ const handlersRef = useRef(handlers);
3420
+ handlersRef.current = handlers;
3421
+ const paramsRef = useRef(params);
3422
+ paramsRef.current = params;
3423
+ useEffect(() => {
3424
+ if (!active || pattern === null) {
3425
+ setState(IDLE);
3426
+ return;
3427
+ }
3428
+ let release = null;
3429
+ let cancelled = false;
3430
+ const subscribe = (socket) => {
3431
+ if (cancelled) return;
3432
+ release = socket.subscribe(pattern, paramsRef.current, {
3433
+ onEvent: (event, data) => handlersRef.current.onEvent?.(event, data),
3434
+ onResync: () => handlersRef.current.onResync?.(),
3435
+ onStatus: (status, code) => setState((previous) => previous.status === status && previous.code === code ? previous : {
3436
+ status,
3437
+ code
3438
+ })
3439
+ });
3440
+ };
3441
+ const socket = provided ?? loadedRealtimeClient();
3442
+ if (socket) subscribe(socket);
3443
+ else {
3444
+ const pending = loadRealtimeClient();
3445
+ if (!pending) return;
3446
+ pending.then(subscribe, () => {});
3447
+ }
3448
+ return () => {
3449
+ cancelled = true;
3450
+ release?.();
3451
+ setState(CLOSED);
3452
+ };
3453
+ }, [
3454
+ provided,
3455
+ pattern === null ? null : JSON.stringify([pattern, params]),
3456
+ active
3457
+ ]);
3458
+ if (typeof window === "undefined") return active ? CLOSED : IDLE;
3459
+ return state;
3460
+ }
3461
+ /**
3462
+ * `fn`, run at most once per `ms`: the first call starts the window, and the
3463
+ * calls inside it fold into the one run at its end. Stable across renders;
3464
+ * a pending run is dropped on unmount.
3465
+ */
3466
+ function useCoalesced(fn, ms = 150) {
3467
+ const fnRef = useRef(fn);
3468
+ fnRef.current = fn;
3469
+ const timer = useRef(null);
3470
+ useEffect(() => () => {
3471
+ if (timer.current) clearTimeout(timer.current);
3472
+ timer.current = null;
3473
+ }, []);
3474
+ const coalesced = useRef(null);
3475
+ coalesced.current ??= () => {
3476
+ if (timer.current) return;
3477
+ timer.current = setTimeout(() => {
3478
+ timer.current = null;
3479
+ fnRef.current();
3480
+ }, ms);
3481
+ };
3482
+ return coalesced.current;
3483
+ }
3484
+ //#endregion
3890
3485
  //#region client/RouteTransitionProvider.tsx
3891
3486
  var RouteTransitionContext = createContext({
3892
3487
  isTransitioning: false,
@@ -4013,6 +3608,6 @@ function useTheme() {
4013
3608
  return context;
4014
3609
  }
4015
3610
  //#endregion
4016
- export { retryDelayFor as $, useLocation as A, getRealtimeClient as B, useRoute as C, I18nProvider as D, I18nContext as E, createMemoryHistory as F, QueryConfigContext as G, SOCKET_ID_HEADER as H, RealtimeContext as I, USER_QUERY_CONFIG_KEYS as J, QueryManagerContext as K, channelKey as L, isAbsoluteUrl as M, ProgressManager as N, ServerDataContext as O, Action as P, parseRetryAfter as Q, configureRealtime as R, routeDataUrl as S, useNavigate as T, toVariantKey as U, reconnectRealtime as V, applyParams as W, DEFAULT_STALE_TIME as X, pickDefined as Y, isRetryableQueryError as Z, loadDictionary as _, useRouteTransition as a, setActiveLocale as b, ComponentsContext as c, loadViewModule as d, shouldRetryQuery as et, subscribeViewModules as f, recoverFromChunkLoadError as g, isChunkLoadError as h, RouteTransitionProvider as i, domainUrl as j, ServerDataProvider as k, ComponentsProvider as l, configureChunkLoadRecovery as m, useTheme as n, Subject as nt, ClientRouterContext as o, CHUNK_RELOAD_MARKER as p, QueryManagerProvider as q, m as r, ClientRouterProvider as s, ThemeProvider as t, QueryError as tt, initialViewModulesReady as u, loadDictionaryForRender as v, useSearchParams as w, readRoutePayload as x, registerDictionary as y, currentSocketId as z };
3611
+ export { DEFAULT_STALE_TIME as $, ServerDataContext as A, followLive as B, readRoutePayload as C, useNavigate as D, useSearchParams as E, ProgressManager as F, loadedModule as G, realtime as H, Action as I, QueryConfigContext as J, toVariantKey as K, createMemoryHistory as L, useLocation as M, domainUrl as N, I18nContext as O, isAbsoluteUrl as P, pickDefined as Q, RealtimeContext as R, setActiveLocale as S, useRoute as T, reconnectRealtime as U, liveModule as V, loadLazy as W, QueryManagerProvider as X, QueryManagerContext as Y, USER_QUERY_CONFIG_KEYS as Z, isChunkLoadError as _, useRouteTransition as a, Subject as at, loadDictionaryForRender as b, ClientRouterContext as c, ComponentsProvider as d, isRetryableQueryError as et, initialViewModulesReady as f, configureChunkLoadRecovery as g, CHUNK_RELOAD_MARKER as h, RouteTransitionProvider as i, QueryError as it, ServerDataProvider as j, I18nProvider as k, ClientRouterProvider as l, subscribeViewModules as m, useTheme as n, retryDelayFor as nt, useChannelSubscription as o, loadViewModule as p, applyParams as q, m as r, shouldRetryQuery as rt, useCoalesced as s, ThemeProvider as t, parseRetryAfter as tt, ComponentsContext as u, recoverFromChunkLoadError as v, routeDataUrl as w, registerDictionary as x, loadDictionary as y, configureRealtime as z };
4017
3612
 
4018
- //# sourceMappingURL=ThemeProvider-BIrCSrFY.js.map
3613
+ //# sourceMappingURL=ThemeProvider-gWqXjGh-.js.map