@jskit-ai/realtime 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/realtime",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -13,6 +13,7 @@
13
13
  "./client/RealtimeClientProvider": "./src/client/RealtimeClientProvider.js",
14
14
  "./client/composables/useRealtimeEvent": "./src/client/composables/useRealtimeEvent.js",
15
15
  "./client/runtime": "./src/client/runtime.js",
16
+ "./client/types": "./src/client/types.js",
16
17
  "./locales/en.json": "./locales/en.json"
17
18
  },
18
19
  "dependencies": {
@@ -22,7 +23,7 @@
22
23
  "socket.io-client": "^4.8.3"
23
24
  },
24
25
  "peerDependencies": {
25
- "@jskit-ai/kernel": "0.2.4",
26
+ "@jskit-ai/kernel": "0.2.5",
26
27
  "vue": "^3.5.13"
27
28
  },
28
29
  "description": "Thin, generic realtime runtime wrappers for socket.io server and client.",
@@ -88,12 +89,16 @@
88
89
  },
89
90
  {
90
91
  "subpath": "./client/composables/useRealtimeEvent",
91
- "summary": "Exports useRealtimeEvent and useRealtimeSocket; listeners are owned by their Vue effect scope."
92
+ "summary": "Exports useRealtimeEvent, useRealtimeSocket, REALTIME_SOCKET_KEY and NO_REALTIME_SOCKET; listeners are owned by their Vue effect scope."
92
93
  },
93
94
  {
94
95
  "subpath": "./client/runtime",
95
96
  "summary": "Exports createSocketIoClient, disconnectSocketIoClient and reconnectSocketIoClient."
96
97
  },
98
+ {
99
+ "subpath": "./client/types",
100
+ "summary": "Types of the application's socket, useRealtimeEvent's options and the client.realtime capability."
101
+ },
97
102
  {
98
103
  "subpath": "./locales/en.json",
99
104
  "summary": "English catalog for the realtime connection indicator, registered by the generated client bootstrap."
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@jskit-ai/realtime": "0.2.7",
6
- "@jskit-ai/shell-web": "0.2.4"
5
+ "@jskit-ai/realtime": "0.2.8",
6
+ "@jskit-ai/shell-web": "0.2.5"
7
7
  }
8
8
  }
@@ -3,10 +3,18 @@ import { normalizeObject, normalizeText } from "@jskit-ai/kernel/shared/support/
3
3
  import { createProviderLogger } from "@jskit-ai/kernel/shared/support/providerLogger";
4
4
  import { getClientAppConfig, resolveClientBootstrapDebugEnabled, resolveMobileConfig } from "@jskit-ai/kernel/client";
5
5
  import RealtimeConnectionIndicator from "./components/RealtimeConnectionIndicator.js";
6
+ import { REALTIME_SOCKET_KEY } from "./composables/useRealtimeEvent.js";
6
7
  import { createSocketIoClient, disconnectSocketIoClient } from "./runtime.js";
7
8
  import { attachSocketConnectionRecovery } from "./connectionRecovery.js";
8
9
  import { SERVED_CLIENT_BUILD_EVENT } from "../shared/servedClientBuild.js";
9
10
 
11
+ function skipReconnectPreparation() {}
12
+
13
+ /**
14
+ * @param {object} [capabilities]
15
+ * @param {import("@jskit-ai/kernel/client/types").ClientEnv} [capabilities.env]
16
+ * @param {import("./types.js").RealtimeMobile | null} [capabilities.mobile]
17
+ */
10
18
  function resolveRealtimeClientConfig({ env = {}, mobile = null } = {}) {
11
19
  const appConfig = normalizeObject(getClientAppConfig());
12
20
  const realtime = normalizeObject(appConfig.realtime);
@@ -35,13 +43,18 @@ function resolveRealtimeClientConfig({ env = {}, mobile = null } = {}) {
35
43
  debugEnvKey: "VITE_REALTIME_DEBUG"
36
44
  });
37
45
 
38
- return Object.freeze({ url, options, debugEnabled });
46
+ return Object.freeze({
47
+ url,
48
+ options,
49
+ debugEnabled
50
+ });
39
51
  }
40
52
 
41
53
  /**
42
54
  * @param {object} options
43
- * @param {any} options.config
44
- * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} options.logger
55
+ * @param {import("./types.js").RealtimeClientConfig} options.config
56
+ * @param {import("@jskit-ai/kernel/client/types").ClientLogger} options.logger
57
+ * @returns {import("./types.js").RealtimeClient}
45
58
  */
46
59
  function createRealtimeClient({ config, logger: appLogger }) {
47
60
  const logger = createProviderLogger(appLogger, {
@@ -54,53 +67,52 @@ function createRealtimeClient({ config, logger: appLogger }) {
54
67
  const servedClientBuild = trackServedClientBuild(socket, logger);
55
68
  const detach = [];
56
69
  let initialized = false;
57
- let beforeReconnect = null;
70
+ let beforeReconnect = skipReconnectPreparation;
58
71
 
59
- function initialize(vueApp = null) {
72
+ /** @param {import("@jskit-ai/kernel/client/types").ClientVueApp} vueApp */
73
+ function initialize(vueApp) {
60
74
  if (initialized) {
61
75
  return;
62
76
  }
63
77
  initialized = true;
64
78
 
65
- if (typeof socket.on === "function") {
66
- detach.push(attachSocketConnectionRecovery(socket, { prepareReconnect: () => beforeReconnect?.() }));
67
- const onConnect = () => logger.debug({ socketConnected: true }, "Realtime client socket connected.");
68
- const onDisconnect = (reason) =>
79
+ detach.push(attachSocketConnectionRecovery(socket, { prepareReconnect: () => beforeReconnect() }));
80
+ const onConnect = () => logger.debug({ socketConnected: true }, "Realtime client socket connected.");
81
+ const onDisconnect = (reason) =>
82
+ logger.debug(
83
+ { socketConnected: false, reason: String(reason || "") },
84
+ "Realtime client socket disconnected."
85
+ );
86
+ const onConnectError = (error) =>
87
+ logger.warn(
88
+ { error: String(error?.message || error || "unknown error") },
89
+ "Realtime client socket connect error."
90
+ );
91
+
92
+ socket.on("connect", onConnect);
93
+ socket.on("disconnect", onDisconnect);
94
+ socket.on("connect_error", onConnectError);
95
+ detach.push(() => {
96
+ socket.off("connect", onConnect);
97
+ socket.off("disconnect", onDisconnect);
98
+ socket.off("connect_error", onConnectError);
99
+ });
100
+
101
+ if (config.debugEnabled === true) {
102
+ const onAny = (eventName, payload) =>
69
103
  logger.debug(
70
- { socketConnected: false, reason: String(reason || "") },
71
- "Realtime client socket disconnected."
72
- );
73
- const onConnectError = (error) =>
74
- logger.warn(
75
- { error: String(error?.message || error || "unknown error") },
76
- "Realtime client socket connect error."
104
+ {
105
+ event: String(eventName || ""),
106
+ payloadScope: payload?.scope || null,
107
+ payloadEntityId: payload?.entityId || null
108
+ },
109
+ "Realtime client received socket event."
77
110
  );
78
-
79
- socket.on("connect", onConnect);
80
- socket.on("disconnect", onDisconnect);
81
- socket.on("connect_error", onConnectError);
82
- detach.push(() => {
83
- socket.off?.("connect", onConnect);
84
- socket.off?.("disconnect", onDisconnect);
85
- socket.off?.("connect_error", onConnectError);
86
- });
87
-
88
- if (config.debugEnabled === true && typeof socket.onAny === "function") {
89
- const onAny = (eventName, payload) =>
90
- logger.debug(
91
- {
92
- event: String(eventName || ""),
93
- payloadScope: payload?.scope || null,
94
- payloadEntityId: payload?.entityId || null
95
- },
96
- "Realtime client received socket event."
97
- );
98
- socket.onAny(onAny);
99
- detach.push(() => socket.offAny?.(onAny));
100
- }
111
+ socket.onAny(onAny);
112
+ detach.push(() => socket.offAny(onAny));
101
113
  }
102
114
 
103
- vueApp?.provide?.("jskit.realtime.runtime.client.socket", socket);
115
+ vueApp.provide(REALTIME_SOCKET_KEY, socket);
104
116
  }
105
117
 
106
118
  function dispose() {
@@ -114,15 +126,15 @@ function createRealtimeClient({ config, logger: appLogger }) {
114
126
  initialized = false;
115
127
  }
116
128
 
117
- // The step to run before recovery reconnects after the server refused or
118
- // dropped the socket, such as auth refreshing the session.
129
+ /**
130
+ * The step to run before recovery reconnects after the server refused or dropped the socket, such as auth refreshing
131
+ * the session.
132
+ * @param {() => unknown} prepare
133
+ */
119
134
  function setBeforeReconnect(prepare) {
120
- if (typeof prepare !== "function") {
121
- throw new TypeError("setBeforeReconnect requires a function.");
122
- }
123
135
  beforeReconnect = prepare;
124
136
  return () => {
125
- if (beforeReconnect === prepare) beforeReconnect = null;
137
+ if (beforeReconnect === prepare) beforeReconnect = skipReconnectPreparation;
126
138
  };
127
139
  }
128
140
 
@@ -136,9 +148,12 @@ function createRealtimeClient({ config, logger: appLogger }) {
136
148
  });
137
149
  }
138
150
 
139
- // The server names the client build it serves on every connection. Listening
140
- // from the socket's creation keeps the first announcement even when it arrives
141
- // before anything subscribes; a subscriber receives the latest one at once.
151
+ /**
152
+ * The server names the client build it serves on every connection. Listening from the socket's creation keeps the first
153
+ * announcement even when it arrives before anything subscribes; a subscriber receives the latest one at once.
154
+ * @param {import("./types.js").RealtimeSocket} socket
155
+ * @param {ReturnType<typeof createProviderLogger>} logger
156
+ */
142
157
  function trackServedClientBuild(socket, logger) {
143
158
  const listeners = new Set();
144
159
  let buildId = "";
@@ -158,18 +173,16 @@ function trackServedClientBuild(socket, logger) {
158
173
  }
159
174
  }
160
175
 
161
- socket.on?.(SERVED_CLIENT_BUILD_EVENT, onServedClientBuild);
176
+ socket.on(SERVED_CLIENT_BUILD_EVENT, onServedClientBuild);
162
177
  return Object.freeze({
178
+ /** @param {(buildId: string) => void} listener */
163
179
  subscribe(listener) {
164
- if (typeof listener !== "function") {
165
- throw new TypeError("onServedClientBuild requires a listener function.");
166
- }
167
180
  listeners.add(listener);
168
181
  if (buildId) notify(listener);
169
182
  return () => listeners.delete(listener);
170
183
  },
171
184
  dispose() {
172
- socket.off?.(SERVED_CLIENT_BUILD_EVENT, onServedClientBuild);
185
+ socket.off(SERVED_CLIENT_BUILD_EVENT, onServedClientBuild);
173
186
  listeners.clear();
174
187
  }
175
188
  });
@@ -189,6 +202,13 @@ const RealtimeClientProvider = defineProvider({
189
202
  provides: {
190
203
  realtime: "client.realtime"
191
204
  },
205
+ /**
206
+ * @param {object} capabilities
207
+ * @param {import("@jskit-ai/kernel/client/types").ClientComponents} capabilities.components
208
+ * @param {import("@jskit-ai/kernel/client/types").ClientEnv} capabilities.env
209
+ * @param {import("@jskit-ai/kernel/client/types").ClientLogger} capabilities.logger
210
+ * @param {import("./types.js").RealtimeMobile | null} capabilities.mobile
211
+ */
192
212
  setup({ components, env, logger, mobile }) {
193
213
  components.register("realtime.web.connection.indicator", RealtimeConnectionIndicator);
194
214
  return {
@@ -198,9 +218,17 @@ const RealtimeClientProvider = defineProvider({
198
218
  })
199
219
  };
200
220
  },
221
+ /**
222
+ * @param {{ vueApp: import("@jskit-ai/kernel/client/types").ClientVueApp }} capabilities
223
+ * @param {{ outputs: { realtime: import("./types.js").RealtimeClient } }} lifecycle
224
+ */
201
225
  boot({ vueApp }, { outputs }) {
202
226
  outputs.realtime.initialize(vueApp);
203
227
  },
228
+ /**
229
+ * @param {unknown} _dependencies
230
+ * @param {{ outputs: { realtime: import("./types.js").RealtimeClient } }} lifecycle
231
+ */
204
232
  shutdown(_dependencies, { outputs }) {
205
233
  outputs.realtime.dispose();
206
234
  }
@@ -1,5 +1,5 @@
1
1
  import { computed, defineComponent, h, onBeforeUnmount, onMounted, ref } from "vue";
2
- import { EMPTY_REALTIME_SOCKET, useRealtimeSocket } from "../composables/useRealtimeEvent.js";
2
+ import { NO_REALTIME_SOCKET, useRealtimeSocket } from "../composables/useRealtimeEvent.js";
3
3
  import { reconnectSocketIoClient } from "../runtime.js";
4
4
  import { useJskitText } from "../i18n.js";
5
5
 
@@ -51,10 +51,9 @@ function resolveTooltipText({ realtimeAvailable, connected }) {
51
51
  const RealtimeConnectionIndicator = defineComponent({
52
52
  name: "RealtimeConnectionIndicator",
53
53
  setup() {
54
- const socket = useRealtimeSocket({ required: false });
55
- const connected = ref(Boolean(socket?.connected));
56
- const realtimeAvailable = socket !== EMPTY_REALTIME_SOCKET;
57
- let detach = null;
54
+ const socket = useRealtimeSocket();
55
+ const connected = ref(Boolean(socket.connected));
56
+ const realtimeAvailable = socket !== NO_REALTIME_SOCKET;
58
57
 
59
58
  const tooltipText = computed(() => {
60
59
  return resolveTooltipText({
@@ -76,40 +75,21 @@ const RealtimeConnectionIndicator = defineComponent({
76
75
  connected.value = Boolean(nextState);
77
76
  }
78
77
 
79
- function bindSocketStatusListeners() {
80
- if (!realtimeAvailable || typeof socket.on !== "function") {
81
- syncConnected(false);
82
- return;
83
- }
78
+ const onConnect = () => syncConnected(true);
79
+ const onDisconnect = () => syncConnected(false);
80
+ const onConnectError = () => syncConnected(false);
84
81
 
82
+ onMounted(() => {
85
83
  syncConnected(socket.connected);
86
-
87
- const onConnect = () => syncConnected(true);
88
- const onDisconnect = () => syncConnected(false);
89
- const onConnectError = () => syncConnected(false);
90
-
91
84
  socket.on("connect", onConnect);
92
85
  socket.on("disconnect", onDisconnect);
93
86
  socket.on("connect_error", onConnectError);
94
-
95
- detach = () => {
96
- if (typeof socket.off === "function") {
97
- socket.off("connect", onConnect);
98
- socket.off("disconnect", onDisconnect);
99
- socket.off("connect_error", onConnectError);
100
- }
101
- };
102
- }
103
-
104
- onMounted(() => {
105
- bindSocketStatusListeners();
106
87
  });
107
88
 
108
89
  onBeforeUnmount(() => {
109
- if (typeof detach === "function") {
110
- detach();
111
- }
112
- detach = null;
90
+ socket.off("connect", onConnect);
91
+ socket.off("disconnect", onDisconnect);
92
+ socket.off("connect_error", onConnectError);
113
93
  });
114
94
 
115
95
  return () =>
@@ -1,20 +1,30 @@
1
1
  import { inject, onScopeDispose, ref, unref, watch } from "vue";
2
2
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
3
 
4
- const EMPTY_REALTIME_SOCKET = Object.freeze({
4
+ const REALTIME_SOCKET_KEY = "jskit.realtime.runtime.client.socket";
5
+
6
+ /**
7
+ * The socket of an application without the realtime provider: it is never connected, and nothing it is asked to do
8
+ * happens.
9
+ * @type {import("../types.js").RealtimeSocket}
10
+ */
11
+ const NO_REALTIME_SOCKET = Object.freeze({
12
+ active: false,
13
+ connected: false,
14
+ connect() {},
15
+ disconnect() {},
16
+ emit() {},
17
+ timeout() {
18
+ return NO_REALTIME_SOCKET;
19
+ },
5
20
  on() {},
6
21
  off() {},
7
22
  onAny() {},
8
23
  offAny() {}
9
24
  });
10
25
 
11
- function isRealtimeSocket(socket) {
12
- return Boolean(
13
- socket &&
14
- typeof socket === "object" &&
15
- typeof socket.on === "function" &&
16
- typeof socket.off === "function"
17
- );
26
+ function matchesEveryEvent() {
27
+ return true;
18
28
  }
19
29
 
20
30
  function resolveEnabled(value) {
@@ -29,35 +39,27 @@ function resolveEventName(value) {
29
39
  return normalized || "*";
30
40
  }
31
41
 
32
- function useRealtimeSocket({ required = false } = {}) {
33
- const socket = inject("jskit.realtime.runtime.client.socket", null);
34
- if (isRealtimeSocket(socket)) {
35
- return socket;
36
- }
37
-
38
- if (required) {
39
- throw new Error("Realtime client socket is not available in Vue injection context.");
40
- }
41
-
42
- return EMPTY_REALTIME_SOCKET;
42
+ /**
43
+ * The application's socket, or `NO_REALTIME_SOCKET` in an application without the realtime provider.
44
+ * @returns {import("../types.js").RealtimeSocket}
45
+ */
46
+ function useRealtimeSocket() {
47
+ return inject(REALTIME_SOCKET_KEY, NO_REALTIME_SOCKET);
43
48
  }
44
49
 
50
+ /** @param {import("../types.js").RealtimeEventOptions} options */
45
51
  function useRealtimeEvent({
46
52
  event = "*",
47
53
  enabled = true,
48
- matches = null,
54
+ matches = matchesEveryEvent,
49
55
  onEvent
50
- } = {}) {
51
- if (typeof onEvent !== "function") {
52
- throw new TypeError("useRealtimeEvent requires onEvent().");
53
- }
54
-
55
- const socket = useRealtimeSocket({ required: false });
56
+ }) {
57
+ const socket = useRealtimeSocket();
56
58
  const active = ref(false);
57
59
  let release = null;
58
60
 
59
61
  function detach() {
60
- if (typeof release === "function") {
62
+ if (release) {
61
63
  try {
62
64
  release();
63
65
  } catch {}
@@ -73,7 +75,7 @@ function useRealtimeEvent({
73
75
  socket
74
76
  });
75
77
 
76
- if (typeof matches === "function" && matches(context) !== true) {
78
+ if (matches(context) !== true) {
77
79
  return;
78
80
  }
79
81
 
@@ -91,7 +93,7 @@ function useRealtimeEvent({
91
93
  function attach() {
92
94
  detach();
93
95
 
94
- if (socket === EMPTY_REALTIME_SOCKET) {
96
+ if (socket === NO_REALTIME_SOCKET) {
95
97
  return;
96
98
  }
97
99
  if (!resolveEnabled(enabled)) {
@@ -100,15 +102,10 @@ function useRealtimeEvent({
100
102
 
101
103
  const eventName = resolveEventName(event);
102
104
  if (eventName === "*") {
103
- if (typeof socket.onAny !== "function") {
104
- return;
105
- }
106
105
  const onAny = (nextEventName, payload) => runHandler(nextEventName, payload);
107
106
  socket.onAny(onAny);
108
107
  release = () => {
109
- if (typeof socket.offAny === "function") {
110
- socket.offAny(onAny);
111
- }
108
+ socket.offAny(onAny);
112
109
  };
113
110
  active.value = true;
114
111
  return;
@@ -132,13 +129,14 @@ function useRealtimeEvent({
132
129
 
133
130
  onScopeDispose(detach);
134
131
 
135
- return Object.freeze({
132
+ return {
136
133
  active
137
- });
134
+ };
138
135
  }
139
136
 
140
137
  export {
141
- EMPTY_REALTIME_SOCKET,
138
+ NO_REALTIME_SOCKET,
139
+ REALTIME_SOCKET_KEY,
142
140
  useRealtimeSocket,
143
141
  useRealtimeEvent
144
142
  };
@@ -1,8 +1,12 @@
1
1
  import { reconnectSocketIoClient } from "./runtime.js";
2
2
 
3
- // `prepareReconnect` runs before each recovery reconnect; auth uses it to
4
- // refresh an expired session over HTTP so the handshake carries fresh cookies.
5
- function attachSocketConnectionRecovery(socket, { prepareReconnect = null } = {}) {
3
+ /**
4
+ * Reconnects a socket Socket.IO will not retry by itself; returns the function that stops.
5
+ * @param {import("socket.io-client").Socket} socket
6
+ * @param {object} recovery
7
+ * @param {() => unknown} recovery.prepareReconnect Runs before each recovery reconnect; auth uses it to refresh an expired session over HTTP so the handshake carries fresh cookies.
8
+ */
9
+ function attachSocketConnectionRecovery(socket, { prepareReconnect }) {
6
10
  let timer = null;
7
11
  let delay = 1_000;
8
12
  let recovering = false;
@@ -21,12 +25,10 @@ function attachSocketConnectionRecovery(socket, { prepareReconnect = null } = {}
21
25
  }
22
26
 
23
27
  async function retry() {
24
- if (prepareReconnect) {
25
- try {
26
- await prepareReconnect();
27
- } catch {
28
- // The handshake then decides; a refusal schedules the next retry.
29
- }
28
+ try {
29
+ await prepareReconnect();
30
+ } catch {
31
+ // The handshake then decides; a refusal schedules the next retry.
30
32
  }
31
33
  if (canRetry()) socket.connect();
32
34
  }
@@ -1,21 +1,22 @@
1
1
  import { io as connectSocketIoClient } from "socket.io-client";
2
- import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
+ import { normalizeObject, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
3
 
4
4
  const SOCKET_IO_PATH = "/socket.io";
5
5
 
6
+ /**
7
+ * @param {object} client
8
+ * @param {string} [client.url]
9
+ * @param {Partial<import("socket.io-client").ManagerOptions & import("socket.io-client").SocketOptions>} [client.options]
10
+ * @param {typeof connectSocketIoClient} [client.connect]
11
+ */
6
12
  function createSocketIoClient({
7
13
  url = "",
8
14
  options = {},
9
15
  connect = connectSocketIoClient
10
- } = {}) {
11
- if (typeof connect !== "function") {
12
- throw new Error("createSocketIoClient requires a valid socket.io client connect function.");
13
- }
14
-
16
+ }) {
15
17
  const normalizedUrl = normalizeText(url);
16
- const source = options && typeof options === "object" && !Array.isArray(options) ? options : {};
17
18
  const normalizedOptions = {
18
- ...source,
19
+ ...normalizeObject(options),
19
20
  path: SOCKET_IO_PATH
20
21
  };
21
22
  if (normalizedUrl) {
@@ -24,18 +25,18 @@ function createSocketIoClient({
24
25
  return connect(normalizedOptions);
25
26
  }
26
27
 
28
+ /** @param {import("./types.js").RealtimeSocket} socket */
27
29
  function disconnectSocketIoClient(socket) {
28
- if (!socket || typeof socket.disconnect !== "function") {
29
- return;
30
- }
31
30
  socket.disconnect();
32
31
  }
33
32
 
34
- // Socket.IO ignores connect() while its own reconnection waits out a backoff
35
- // delay or an attempt left hanging by a sleeping laptop. Closing that pending
36
- // attempt first makes connect() open a fresh transport immediately.
33
+ /**
34
+ * Socket.IO ignores connect() while its own reconnection waits out a backoff delay or an attempt left hanging by a
35
+ * sleeping laptop. Closing that pending attempt first makes connect() open a fresh transport immediately.
36
+ * @param {import("./types.js").RealtimeSocket} socket
37
+ */
37
38
  function reconnectSocketIoClient(socket) {
38
- if (!socket || socket.connected || typeof socket.connect !== "function") {
39
+ if (socket.connected) {
39
40
  return;
40
41
  }
41
42
  if (socket.active) {
@@ -0,0 +1,46 @@
1
+ // The values realtime's client hands out and receives across files, for its own modules and for the packages that use
2
+ // the application's socket or the `client.realtime` capability.
3
+
4
+ /**
5
+ * The application's socket as client code uses it: Socket.IO's own, or `NO_REALTIME_SOCKET` in an application without
6
+ * the realtime provider.
7
+ * @typedef {Pick<import("socket.io-client").Socket, "active" | "connected" | "connect" | "disconnect" | "emit" | "timeout" | "on" | "off" | "onAny" | "offAny">} RealtimeSocket
8
+ */
9
+
10
+ /**
11
+ * What a listener receives for one socket event.
12
+ * @typedef {object} RealtimeEventContext
13
+ * @property {string} event
14
+ * @property {any} payload
15
+ * @property {RealtimeSocket} socket
16
+ */
17
+
18
+ /**
19
+ * What `useRealtimeEvent()` listens for.
20
+ * @typedef {object} RealtimeEventOptions
21
+ * @property {import("vue").MaybeRef<string>} [event] One event's name; every event when it is `"*"` or empty.
22
+ * @property {import("vue").MaybeRef<boolean>} [enabled]
23
+ * @property {(context: RealtimeEventContext) => boolean} [matches] Only an event this returns true for is handled.
24
+ * @property {(context: RealtimeEventContext) => unknown} onEvent
25
+ */
26
+
27
+ /**
28
+ * The part of the optional `client.mobile` capability realtime reads.
29
+ * @typedef {object} RealtimeMobile
30
+ * @property {{ available?: boolean }} [adapter]
31
+ */
32
+
33
+ /** @typedef {ReturnType<typeof import("./RealtimeClientProvider.js").resolveRealtimeClientConfig>} RealtimeClientConfig */
34
+
35
+ /**
36
+ * The `client.realtime` capability.
37
+ * @typedef {object} RealtimeClient
38
+ * @property {RealtimeClientConfig} config
39
+ * @property {() => void} dispose
40
+ * @property {(vueApp: import("@jskit-ai/kernel/client/types").ClientVueApp) => void} initialize
41
+ * @property {(listener: (buildId: string) => void) => () => void} onServedClientBuild Calls the listener with each client build a server names, and at once with the latest one; returns the unsubscribe.
42
+ * @property {(prepare: () => unknown) => () => void} setBeforeReconnect Sets the step recovery runs before reconnecting; returns the function that removes it.
43
+ * @property {import("socket.io-client").Socket} socket
44
+ */
45
+
46
+ export {};
@@ -61,13 +61,6 @@ test("createSocketIoClient supports url-less connection with fixed socket path",
61
61
  ]);
62
62
  });
63
63
 
64
- test("createSocketIoClient rejects invalid connect function", () => {
65
- assert.throws(
66
- () => createSocketIoClient({ connect: null }),
67
- /requires a valid socket\.io client connect function/
68
- );
69
- });
70
-
71
64
  test("disconnectSocketIoClient calls socket.disconnect when available", () => {
72
65
  let disconnected = false;
73
66
  disconnectSocketIoClient({
@@ -78,11 +71,13 @@ test("disconnectSocketIoClient calls socket.disconnect when available", () => {
78
71
  assert.equal(disconnected, true);
79
72
  });
80
73
 
81
- test("disconnectSocketIoClient is a no-op for missing socket", () => {
82
- disconnectSocketIoClient(null);
83
- disconnectSocketIoClient({});
84
- assert.equal(true, true);
85
- });
74
+ function prepareNothing() {}
75
+
76
+ // Moves the mocked clock, then lets a retry that fired finish awaiting its prepare step.
77
+ async function advance(t, milliseconds) {
78
+ t.mock.timers.tick(milliseconds);
79
+ await new Promise((resolve) => setImmediate(resolve));
80
+ }
86
81
 
87
82
  function recoverySocket(t) {
88
83
  t.mock.timers.enable({ apis: ["setTimeout"] });
@@ -92,28 +87,28 @@ function recoverySocket(t) {
92
87
  connect: t.mock.fn(),
93
88
  io: { reconnection: () => true }
94
89
  });
95
- const detach = attachSocketConnectionRecovery(socket);
90
+ const detach = attachSocketConnectionRecovery(socket, { prepareReconnect: prepareNothing });
96
91
  t.after(detach);
97
92
  return { socket, detach };
98
93
  }
99
94
 
100
- test("server disconnect recovery backs off middleware rejection and resets after connection", (t) => {
95
+ test("server disconnect recovery backs off middleware rejection and resets after connection", async (t) => {
101
96
  const { socket } = recoverySocket(t);
102
97
  socket.emit("disconnect", "io server disconnect");
103
98
  for (const [index, delay] of [1_000, 2_000, 4_000, 8_000, 16_000, 30_000, 30_000].entries()) {
104
- t.mock.timers.tick(delay - 1);
99
+ await advance(t, delay - 1);
105
100
  assert.equal(socket.connect.mock.callCount(), index);
106
- t.mock.timers.tick(1);
101
+ await advance(t, 1);
107
102
  assert.equal(socket.connect.mock.callCount(), index + 1);
108
103
  socket.emit("connect_error", new Error("Authentication required"));
109
104
  }
110
105
  socket.connected = true;
111
106
  socket.emit("connect");
112
- t.mock.timers.tick(30_000);
107
+ await advance(t, 30_000);
113
108
  assert.equal(socket.connect.mock.callCount(), 7);
114
109
  socket.connected = false;
115
110
  socket.emit("disconnect", "io server disconnect");
116
- t.mock.timers.tick(1_000);
111
+ await advance(t, 1_000);
117
112
  assert.equal(socket.connect.mock.callCount(), 8);
118
113
  });
119
114
 
@@ -138,42 +133,42 @@ test("recovery runs its prepare step, such as a session refresh, before reconnec
138
133
  assert.equal(socket.connect.mock.callCount(), 1);
139
134
  });
140
135
 
141
- test("recovery leaves transport retries and intentional disconnects to Socket.IO", (t) => {
136
+ test("recovery leaves transport retries and intentional disconnects to Socket.IO", async (t) => {
142
137
  const { socket, detach } = recoverySocket(t);
143
138
  socket.active = true;
144
139
  socket.emit("disconnect", "transport close");
145
140
  socket.emit("connect_error", new Error("Temporary transport error"));
146
- t.mock.timers.tick(30_000);
141
+ await advance(t, 30_000);
147
142
  assert.equal(socket.connect.mock.callCount(), 0);
148
143
  socket.active = false;
149
144
  socket.emit("disconnect", "io server disconnect");
150
145
  socket.emit("disconnect", "io client disconnect");
151
- t.mock.timers.tick(30_000);
146
+ await advance(t, 30_000);
152
147
  assert.equal(socket.connect.mock.callCount(), 0);
153
148
  socket.emit("disconnect", "io server disconnect");
154
149
  detach();
155
- t.mock.timers.tick(30_000);
150
+ await advance(t, 30_000);
156
151
  assert.equal(socket.connect.mock.callCount(), 0);
157
152
  assert.equal(socket.eventNames().length, 0);
158
153
  });
159
154
 
160
- test("recovery respects reconnection disabled at startup or while a retry is pending", (t) => {
155
+ test("recovery respects reconnection disabled at startup or while a retry is pending", async (t) => {
161
156
  const { socket } = recoverySocket(t);
162
157
  const client = createSocketIoClient({ options: { autoConnect: false, reconnection: false } });
163
158
  socket.io = client.io;
164
159
  t.after(() => client.disconnect());
165
160
  socket.emit("disconnect", "io server disconnect");
166
161
  socket.emit("connect_error", new Error("Rejected"));
167
- t.mock.timers.tick(30_000);
162
+ await advance(t, 30_000);
168
163
  assert.equal(socket.connect.mock.callCount(), 0);
169
164
  socket.io.reconnection(true);
170
165
  socket.emit("connect_error", new Error("Rejected"));
171
166
  socket.io.reconnection(false);
172
- t.mock.timers.tick(30_000);
167
+ await advance(t, 30_000);
173
168
  assert.equal(socket.connect.mock.callCount(), 0);
174
169
  });
175
170
 
176
- test("hidden or offline pages resume recovery when available and remove their listeners on teardown", (t) => {
171
+ test("hidden or offline pages resume recovery when available and remove their listeners on teardown", async (t) => {
177
172
  const previousDocument = globalThis.document;
178
173
  const previousWindow = globalThis.window;
179
174
  const document = Object.assign(new EventTarget(), { hidden: true });
@@ -188,7 +183,7 @@ test("hidden or offline pages resume recovery when available and remove their li
188
183
  });
189
184
  const { socket, detach } = recoverySocket(t);
190
185
  socket.emit("disconnect", "io server disconnect");
191
- t.mock.timers.tick(30_000);
186
+ await advance(t, 30_000);
192
187
  assert.equal(socket.connect.mock.callCount(), 0);
193
188
  document.hidden = false;
194
189
  window.navigator.onLine = false;
@@ -201,7 +196,7 @@ test("hidden or offline pages resume recovery when available and remove their li
201
196
  detach();
202
197
  window.dispatchEvent(new Event("online"));
203
198
  document.dispatchEvent(new Event("visibilitychange"));
204
- t.mock.timers.tick(30_000);
199
+ await advance(t, 30_000);
205
200
  assert.equal(socket.connect.mock.callCount(), 1);
206
201
  });
207
202
 
@@ -217,7 +212,7 @@ test("a real server-forced disconnect reconnects through a fresh authenticated h
217
212
  http.listen(0, "127.0.0.1");
218
213
  await once(http, "listening");
219
214
  const client = createSocketIoClient({ url: `http://127.0.0.1:${http.address().port}` });
220
- const detach = attachSocketConnectionRecovery(client);
215
+ const detach = attachSocketConnectionRecovery(client, { prepareReconnect: prepareNothing });
221
216
  t.after(async () => {
222
217
  detach();
223
218
  client.disconnect();
@@ -2,14 +2,53 @@ import assert from "node:assert/strict";
2
2
  import { EventEmitter } from "node:events";
3
3
  import test from "node:test";
4
4
  import { createRenderer, effectScope, h, nextTick, ref } from "vue";
5
- import { useRealtimeEvent } from "../src/client/composables/useRealtimeEvent.js";
5
+ import { RealtimeConnectionIndicator } from "../src/client/components/RealtimeConnectionIndicator.js";
6
+ import {
7
+ NO_REALTIME_SOCKET,
8
+ REALTIME_SOCKET_KEY,
9
+ useRealtimeEvent,
10
+ useRealtimeSocket
11
+ } from "../src/client/composables/useRealtimeEvent.js";
12
+ import { createSocketIoClient, reconnectSocketIoClient } from "../src/client/runtime.js";
6
13
 
7
14
  const renderer = createRenderer({
8
- createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
9
- setElementText() {}, setText() {}, insert() {}, remove() {}, patchProp() {},
15
+ createElement: () => ({ props: {} }), createText: () => ({}), createComment: () => ({}),
16
+ setElementText() {}, setText() {}, insert(element, parent) { parent.child ??= element; }, remove() {},
17
+ patchProp(element, name, _previous, next) { element.props[name] = next; },
10
18
  parentNode() {}, nextSibling() {}
11
19
  });
12
20
 
21
+ // Mounts setup() in an application that has the given socket, or none.
22
+ function mountWith(socket, setup) {
23
+ const app = renderer.createApp({ setup() {
24
+ setup();
25
+ return () => h("div");
26
+ } });
27
+ if (socket) app.provide(REALTIME_SOCKET_KEY, socket);
28
+ app.mount({});
29
+ return app;
30
+ }
31
+
32
+ function mountIndicator(socket) {
33
+ const root = {};
34
+ const app = renderer.createApp(RealtimeConnectionIndicator);
35
+ if (socket) app.provide(REALTIME_SOCKET_KEY, socket);
36
+ app.mount(root);
37
+ return { app, button: () => root.child.props };
38
+ }
39
+
40
+ // The socket's event surface as an EventEmitter gives it, with Socket.IO's catch-all listeners.
41
+ function anySocket() {
42
+ const socket = new EventEmitter();
43
+ const anyListeners = new Set();
44
+ return Object.assign(socket, {
45
+ onAny(listener) { anyListeners.add(listener); },
46
+ offAny(listener) { anyListeners.delete(listener); },
47
+ receive(event, payload) { for (const listener of [...anyListeners]) listener(event, payload); },
48
+ anyListeners
49
+ });
50
+ }
51
+
13
52
  test("a component listener detaches on unmount", () => {
14
53
  const socket = new EventEmitter();
15
54
  const received = [];
@@ -63,3 +102,98 @@ test("a retained scope keeps its listener after screen unmount and releases it w
63
102
  await nextTick();
64
103
  assert.equal(socket.listenerCount("completed"), 0);
65
104
  });
105
+
106
+ test("an application without realtime receives the disabled socket, and listening stays inactive", () => {
107
+ let socket;
108
+ let listener;
109
+ const app = mountWith(null, () => {
110
+ socket = useRealtimeSocket();
111
+ listener = useRealtimeEvent({ event: "reply", onEvent() {} });
112
+ });
113
+ assert.equal(socket, NO_REALTIME_SOCKET);
114
+ assert.equal(listener.active.value, false);
115
+ app.unmount();
116
+ });
117
+
118
+ test("the disabled socket has every member of the real one, and asking it to do anything does nothing", (t) => {
119
+ const real = createSocketIoClient({ options: { autoConnect: false } });
120
+ t.after(() => real.disconnect());
121
+ for (const member of ["active", "connected", "connect", "disconnect", "emit", "timeout", "on", "off", "onAny", "offAny"]) {
122
+ assert.equal(typeof NO_REALTIME_SOCKET[member], typeof real[member], member);
123
+ }
124
+ assert.equal(NO_REALTIME_SOCKET.connected, false);
125
+ assert.equal(NO_REALTIME_SOCKET.active, false);
126
+ assert.equal(NO_REALTIME_SOCKET.timeout(1_000), NO_REALTIME_SOCKET);
127
+ reconnectSocketIoClient(NO_REALTIME_SOCKET);
128
+ });
129
+
130
+ test("a listener for every event hears all of them through the socket's catch-all and releases it", () => {
131
+ const socket = anySocket();
132
+ const received = [];
133
+ let listener;
134
+ const app = mountWith(socket, () => {
135
+ listener = useRealtimeEvent({ onEvent: ({ event, payload }) => received.push([event, payload]) });
136
+ });
137
+ assert.equal(listener.active.value, true);
138
+ socket.receive("reply", "first");
139
+ socket.receive("completed", "second");
140
+ assert.deepEqual(received, [["reply", "first"], ["completed", "second"]]);
141
+ app.unmount();
142
+ assert.equal(socket.anyListeners.size, 0);
143
+ assert.equal(listener.active.value, false);
144
+ });
145
+
146
+ test("matches decides which events reach the handler; without it every event does", () => {
147
+ const socket = new EventEmitter();
148
+ const filtered = [];
149
+ const unfiltered = [];
150
+ const app = mountWith(socket, () => {
151
+ useRealtimeEvent({
152
+ event: "reply",
153
+ matches: ({ event, payload, socket: received }) => event === "reply" && received === socket && payload === "wanted",
154
+ onEvent: ({ payload }) => filtered.push(payload)
155
+ });
156
+ useRealtimeEvent({ event: "reply", onEvent: ({ payload }) => unfiltered.push(payload) });
157
+ });
158
+ socket.emit("reply", "unwanted");
159
+ socket.emit("reply", "wanted");
160
+ app.unmount();
161
+ assert.deepEqual(filtered, ["wanted"]);
162
+ assert.deepEqual(unfiltered, ["unwanted", "wanted"]);
163
+ });
164
+
165
+ test("the connection indicator follows its socket, offers a reconnect and releases its listeners", () => {
166
+ const socket = Object.assign(new EventEmitter(), { connected: false, active: false, connect() { socket.connected = true; } });
167
+ const { app, button } = mountIndicator(socket);
168
+ assert.equal(socket.listenerCount("connect"), 1);
169
+ assert.equal(button().disabled, false);
170
+ button().onClick();
171
+ assert.equal(socket.connected, true);
172
+ app.unmount();
173
+ for (const event of ["connect", "disconnect", "connect_error"]) {
174
+ assert.equal(socket.listenerCount(event), 0, event);
175
+ }
176
+ });
177
+
178
+ test("the connection indicator reports each change of the socket's state", async () => {
179
+ const socket = Object.assign(new EventEmitter(), { connected: true, active: true });
180
+ const { app, button } = mountIndicator(socket);
181
+ assert.equal(button().disabled, true);
182
+ socket.emit("connect_error", new Error("Refused"));
183
+ await nextTick();
184
+ assert.equal(button().disabled, false);
185
+ socket.emit("connect");
186
+ await nextTick();
187
+ assert.equal(button().disabled, true);
188
+ socket.emit("disconnect", "transport close");
189
+ await nextTick();
190
+ assert.equal(button().disabled, false);
191
+ app.unmount();
192
+ });
193
+
194
+ test("the connection indicator stays disabled in an application without realtime", () => {
195
+ const { app, button } = mountIndicator(null);
196
+ assert.equal(button().disabled, true);
197
+ assert.equal(button().title, "Realtime is unavailable. Live updates are disabled for this page.");
198
+ app.unmount();
199
+ });