@monorise/react 8.1.0 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,34 +1,9 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target[prop] = source[prop];
29
- }
30
- return target;
31
- };
1
+ import {
2
+ WebSocketManager,
3
+ __objRest,
4
+ __spreadProps,
5
+ __spreadValues
6
+ } from "./chunk-CQQYJW4K.js";
32
7
 
33
8
  // actions/app.action.ts
34
9
  import { produce } from "immer";
@@ -1980,6 +1955,575 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1980
1955
  };
1981
1956
  };
1982
1957
 
1958
+ // actions/websocket.action.ts
1959
+ import { useCallback, useEffect as useEffect3, useRef, useState as useState3 } from "react";
1960
+ import { produce as produce5 } from "immer";
1961
+ var globalWsManager = null;
1962
+ var wsEndpoint;
1963
+ var initializeWebSocketManager = (WebSocketManagerClass, endpoint, token) => {
1964
+ if (globalWsManager) return globalWsManager;
1965
+ wsEndpoint = endpoint;
1966
+ globalWsManager = new WebSocketManagerClass(endpoint, token || "");
1967
+ globalWsManager.connect();
1968
+ return globalWsManager;
1969
+ };
1970
+ var getWebSocketManager = () => globalWsManager;
1971
+ var initWebSocketActions = (monoriseStore, httpActions) => {
1972
+ const useEntitySocket2 = (entityType, opts = {}) => {
1973
+ const { limit = 20, skipInitialFetch = false } = opts;
1974
+ const [isLoading, setIsLoading] = useState3(!skipInitialFetch);
1975
+ const [isFetchingMore, setIsFetchingMore] = useState3(false);
1976
+ const [isRefreshing, setIsRefreshing] = useState3(false);
1977
+ const [isSubscribed, setIsSubscribed] = useState3(false);
1978
+ const [error, setError2] = useState3(null);
1979
+ const [hasMore, setHasMore] = useState3(true);
1980
+ const lastKeyRef = useRef(void 0);
1981
+ const isFirstFetchRef = useRef(true);
1982
+ const entities = monoriseStore((state) => {
1983
+ var _a;
1984
+ const entityState = state.entity[entityType];
1985
+ return Array.from(((_a = entityState == null ? void 0 : entityState.dataMap) == null ? void 0 : _a.values()) || []);
1986
+ });
1987
+ const fetchData = async (type) => {
1988
+ if (!httpActions) return;
1989
+ if (type === "more") {
1990
+ setIsFetchingMore(true);
1991
+ } else if (type === "refresh") {
1992
+ setIsRefreshing(true);
1993
+ } else {
1994
+ setIsLoading(true);
1995
+ }
1996
+ setError2(null);
1997
+ try {
1998
+ const fetchLastKey = type === "refresh" ? void 0 : lastKeyRef.current;
1999
+ const result = await httpActions.listEntities(entityType, {
2000
+ limit,
2001
+ lastKey: fetchLastKey
2002
+ });
2003
+ monoriseStore.setState(
2004
+ produce5((state) => {
2005
+ if (type === "refresh") {
2006
+ state.entity[entityType].dataMap.clear();
2007
+ }
2008
+ for (const entity of result.data) {
2009
+ state.entity[entityType].dataMap.set(entity.entityId, entity);
2010
+ }
2011
+ state.entity[entityType].isFirstFetched = true;
2012
+ state.entity[entityType].lastKey = result.lastKey;
2013
+ })
2014
+ );
2015
+ lastKeyRef.current = result.lastKey;
2016
+ setHasMore(!!result.lastKey);
2017
+ } catch (err) {
2018
+ setError2(err instanceof Error ? err : new Error("Failed to fetch"));
2019
+ } finally {
2020
+ setIsLoading(false);
2021
+ setIsFetchingMore(false);
2022
+ setIsRefreshing(false);
2023
+ }
2024
+ };
2025
+ useEffect3(() => {
2026
+ if (skipInitialFetch) return;
2027
+ fetchData("initial");
2028
+ }, [entityType, limit, skipInitialFetch]);
2029
+ useEffect3(() => {
2030
+ if (!globalWsManager) {
2031
+ setIsSubscribed(false);
2032
+ return;
2033
+ }
2034
+ const subKey = globalWsManager.subscribeEntityType(entityType);
2035
+ setIsSubscribed(true);
2036
+ let wasConnected = false;
2037
+ const unsubscribeState = globalWsManager.onStateChange((state) => {
2038
+ if (state === "connected" && wasConnected === false && !isFirstFetchRef.current) {
2039
+ fetchData("refresh");
2040
+ }
2041
+ wasConnected = state === "connected";
2042
+ isFirstFetchRef.current = false;
2043
+ });
2044
+ const unsubscribeMessage = globalWsManager.onMessage(
2045
+ (msg) => {
2046
+ if (msg.type === "entity.created" || msg.type === "entity.updated" || msg.type === "entity.deleted") {
2047
+ const payload = msg.payload;
2048
+ if (payload.entityType !== entityType) return;
2049
+ if (msg.type === "entity.created" || msg.type === "entity.updated") {
2050
+ if (payload.data) {
2051
+ monoriseStore.setState(
2052
+ produce5((state) => {
2053
+ const key = entityType;
2054
+ if (!state.entity[key]) {
2055
+ state.entity[key] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
2056
+ }
2057
+ state.entity[key].dataMap.set(
2058
+ payload.entityId,
2059
+ payload.data
2060
+ );
2061
+ })
2062
+ );
2063
+ }
2064
+ } else if (msg.type === "entity.deleted") {
2065
+ monoriseStore.setState(
2066
+ produce5((state) => {
2067
+ var _a;
2068
+ const key = entityType;
2069
+ if ((_a = state.entity[key]) == null ? void 0 : _a.dataMap) {
2070
+ state.entity[key].dataMap.delete(payload.entityId);
2071
+ }
2072
+ })
2073
+ );
2074
+ }
2075
+ }
2076
+ }
2077
+ );
2078
+ return () => {
2079
+ globalWsManager == null ? void 0 : globalWsManager.unsubscribeEntityType(subKey);
2080
+ unsubscribeState();
2081
+ unsubscribeMessage();
2082
+ setIsSubscribed(false);
2083
+ };
2084
+ }, [entityType]);
2085
+ const fetchMore = async () => {
2086
+ if (!hasMore || isFetchingMore) return;
2087
+ await fetchData("more");
2088
+ };
2089
+ return {
2090
+ entities,
2091
+ isLoading,
2092
+ isFetchingMore,
2093
+ isSubscribed,
2094
+ error,
2095
+ isRefreshing,
2096
+ fetchMore,
2097
+ hasMore
2098
+ };
2099
+ };
2100
+ const useMutualSocket2 = (byEntityType, byEntityId2, mutualEntityType, opts = {}) => {
2101
+ const { limit = 20, skipInitialFetch = false } = opts;
2102
+ const [isLoading, setIsLoading] = useState3(
2103
+ !skipInitialFetch && !!byEntityId2
2104
+ );
2105
+ const [isFetchingMore, setIsFetchingMore] = useState3(false);
2106
+ const [isRefreshing, setIsRefreshing] = useState3(false);
2107
+ const [isSubscribed, setIsSubscribed] = useState3(false);
2108
+ const [error, setError2] = useState3(null);
2109
+ const [hasMore, setHasMore] = useState3(true);
2110
+ const lastKeyRef = useRef(void 0);
2111
+ const isFirstFetchRef = useRef(true);
2112
+ const mutualKey = byEntityId2 ? `${byEntityType}/${byEntityId2}/${mutualEntityType}` : "";
2113
+ const mutuals = monoriseStore((state) => {
2114
+ var _a, _b;
2115
+ return Array.from(((_b = (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.values()) || []);
2116
+ });
2117
+ const fetchData = async (type) => {
2118
+ if (!byEntityId2 || !httpActions) return;
2119
+ if (type === "more") {
2120
+ setIsFetchingMore(true);
2121
+ } else if (type === "refresh") {
2122
+ setIsRefreshing(true);
2123
+ } else {
2124
+ setIsLoading(true);
2125
+ }
2126
+ setError2(null);
2127
+ try {
2128
+ const fetchLastKey = type === "refresh" ? void 0 : lastKeyRef.current;
2129
+ const result = await httpActions.listEntitiesByEntity(
2130
+ byEntityType,
2131
+ byEntityId2,
2132
+ mutualEntityType,
2133
+ { limit, lastKey: fetchLastKey }
2134
+ );
2135
+ monoriseStore.setState(
2136
+ produce5((state) => {
2137
+ if (!state.mutual[mutualKey]) {
2138
+ state.mutual[mutualKey] = {
2139
+ dataMap: /* @__PURE__ */ new Map(),
2140
+ isFirstFetched: true,
2141
+ lastKey: void 0
2142
+ };
2143
+ }
2144
+ if (type === "refresh") {
2145
+ state.mutual[mutualKey].dataMap.clear();
2146
+ }
2147
+ for (const entity of result.entities) {
2148
+ const e = entity;
2149
+ state.mutual[mutualKey].dataMap.set(e.entityId, entity);
2150
+ }
2151
+ state.mutual[mutualKey].lastKey = result.lastKey;
2152
+ })
2153
+ );
2154
+ lastKeyRef.current = result.lastKey;
2155
+ setHasMore(!!result.lastKey);
2156
+ } catch (err) {
2157
+ setError2(err instanceof Error ? err : new Error("Failed to fetch"));
2158
+ } finally {
2159
+ setIsLoading(false);
2160
+ setIsFetchingMore(false);
2161
+ setIsRefreshing(false);
2162
+ }
2163
+ };
2164
+ useEffect3(() => {
2165
+ if (skipInitialFetch || !byEntityId2) {
2166
+ setIsLoading(false);
2167
+ return;
2168
+ }
2169
+ lastKeyRef.current = void 0;
2170
+ setHasMore(true);
2171
+ isFirstFetchRef.current = true;
2172
+ fetchData("initial");
2173
+ }, [byEntityType, byEntityId2, mutualEntityType, limit, skipInitialFetch]);
2174
+ useEffect3(() => {
2175
+ if (!globalWsManager || !byEntityId2) {
2176
+ setIsSubscribed(false);
2177
+ return;
2178
+ }
2179
+ const subKey = globalWsManager.subscribeMutualType(
2180
+ byEntityType,
2181
+ byEntityId2,
2182
+ mutualEntityType
2183
+ );
2184
+ setIsSubscribed(true);
2185
+ let wasConnected = false;
2186
+ const unsubscribeState = globalWsManager.onStateChange((state) => {
2187
+ if (state === "connected" && wasConnected === false && !isFirstFetchRef.current) {
2188
+ fetchData("refresh");
2189
+ }
2190
+ wasConnected = state === "connected";
2191
+ isFirstFetchRef.current = false;
2192
+ });
2193
+ const unsubscribeMessage = globalWsManager.onMessage(
2194
+ (msg) => {
2195
+ if (msg.type === "mutual.created" || msg.type === "mutual.updated" || msg.type === "mutual.deleted") {
2196
+ const payload = msg.payload;
2197
+ if (payload.byEntityType !== byEntityType || payload.byEntityId !== byEntityId2 || payload.mutualEntityType !== mutualEntityType) {
2198
+ return;
2199
+ }
2200
+ if (msg.type === "mutual.created" || msg.type === "mutual.updated") {
2201
+ if (payload.data) {
2202
+ monoriseStore.setState(
2203
+ produce5((state) => {
2204
+ if (!state.mutual[mutualKey]) {
2205
+ state.mutual[mutualKey] = {
2206
+ dataMap: /* @__PURE__ */ new Map(),
2207
+ isFirstFetched: true,
2208
+ lastKey: void 0
2209
+ };
2210
+ }
2211
+ state.mutual[mutualKey].dataMap.set(
2212
+ payload.entityId,
2213
+ payload.data
2214
+ );
2215
+ })
2216
+ );
2217
+ }
2218
+ } else if (msg.type === "mutual.deleted") {
2219
+ monoriseStore.setState(
2220
+ produce5((state) => {
2221
+ var _a;
2222
+ (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap.delete(payload.entityId);
2223
+ })
2224
+ );
2225
+ }
2226
+ }
2227
+ }
2228
+ );
2229
+ return () => {
2230
+ globalWsManager == null ? void 0 : globalWsManager.unsubscribeMutualType(subKey);
2231
+ unsubscribeState();
2232
+ unsubscribeMessage();
2233
+ setIsSubscribed(false);
2234
+ };
2235
+ }, [byEntityType, byEntityId2, mutualEntityType, mutualKey]);
2236
+ const fetchMore = async () => {
2237
+ if (!hasMore || isFetchingMore) return;
2238
+ await fetchData("more");
2239
+ };
2240
+ return {
2241
+ mutuals,
2242
+ isLoading,
2243
+ isFetchingMore,
2244
+ isSubscribed,
2245
+ error,
2246
+ isRefreshing,
2247
+ fetchMore,
2248
+ hasMore
2249
+ };
2250
+ };
2251
+ const useEphemeralSocket2 = (channel, opts) => {
2252
+ const [isSubscribed, setIsSubscribed] = useState3(false);
2253
+ useEffect3(() => {
2254
+ if (!globalWsManager || !channel) {
2255
+ setIsSubscribed(false);
2256
+ return;
2257
+ }
2258
+ const subKey = globalWsManager.subscribeEphemeral(channel);
2259
+ setIsSubscribed(true);
2260
+ const unsubscribeMessage = globalWsManager.onMessage(
2261
+ (msg) => {
2262
+ var _a;
2263
+ if (msg.type === "ephemeral") {
2264
+ const payload = msg.payload;
2265
+ if (payload.channel !== channel) return;
2266
+ (_a = opts == null ? void 0 : opts.onMessage) == null ? void 0 : _a.call(opts, payload.data, payload.senderId);
2267
+ }
2268
+ }
2269
+ );
2270
+ return () => {
2271
+ globalWsManager == null ? void 0 : globalWsManager.unsubscribeEphemeral(subKey);
2272
+ unsubscribeMessage();
2273
+ setIsSubscribed(false);
2274
+ };
2275
+ }, [channel]);
2276
+ const send = useCallback(
2277
+ (data) => {
2278
+ if (!globalWsManager || !channel) return;
2279
+ globalWsManager.sendEphemeral(channel, data);
2280
+ },
2281
+ [channel]
2282
+ );
2283
+ return { isSubscribed, send };
2284
+ };
2285
+ const useEntityFeed2 = (opts) => {
2286
+ const { entityType, entityId, ticketEndpoint } = opts;
2287
+ const [isConnected, setIsConnected] = useState3(false);
2288
+ const [error, setError2] = useState3(null);
2289
+ const refreshTimerRef = useRef(null);
2290
+ const hasConnectedOnceRef = useRef(false);
2291
+ const resyncFromHttp = async () => {
2292
+ var _a, _b;
2293
+ if (!httpActions) return;
2294
+ const snapshot = monoriseStore.getState();
2295
+ const keys = Object.keys((_a = snapshot.mutual) != null ? _a : {});
2296
+ for (const key of keys) {
2297
+ const parsed = parseMutualStateKey(key);
2298
+ if (parsed.entityId) continue;
2299
+ if (parsed.byEntityId !== entityId) continue;
2300
+ if (!((_b = snapshot.mutual[key]) == null ? void 0 : _b.isFirstFetched)) continue;
2301
+ try {
2302
+ const result = await httpActions.listEntitiesByEntity(
2303
+ parsed.byEntity,
2304
+ parsed.byEntityId,
2305
+ parsed.entity
2306
+ );
2307
+ if (!isMountedRef.current) return;
2308
+ monoriseStore.setState(
2309
+ produce5((draft) => {
2310
+ const slice = draft.mutual[key];
2311
+ if (!slice) return;
2312
+ slice.dataMap.clear();
2313
+ for (const mutual of result.entities) {
2314
+ slice.dataMap.set(mutual.entityId, mutual);
2315
+ }
2316
+ slice.lastKey = result.lastKey;
2317
+ })
2318
+ );
2319
+ } catch (e) {
2320
+ }
2321
+ }
2322
+ };
2323
+ const wsManagerRef = useRef(null);
2324
+ const isMountedRef = useRef(true);
2325
+ const connectingRef = useRef(false);
2326
+ const reconnectCountRef = useRef(0);
2327
+ const connectRef = useRef(() => {
2328
+ });
2329
+ const lastConnectedAtRef = useRef(0);
2330
+ const fetchTicket = useCallback(async () => {
2331
+ try {
2332
+ const url = ticketEndpoint || `/api/core/ws/ticket/${entityType}/${entityId}`;
2333
+ const fetchOpts = {
2334
+ method: "POST",
2335
+ headers: { "Content-Type": "application/json" }
2336
+ };
2337
+ if (ticketEndpoint) {
2338
+ fetchOpts.body = JSON.stringify({ entityType, entityId });
2339
+ }
2340
+ const response = await fetch(url, fetchOpts);
2341
+ if (response.status === 401 || response.status === 403) {
2342
+ return { error: { code: "TICKET_UNAUTHORIZED", message: "Unauthorized" } };
2343
+ }
2344
+ if (!response.ok) {
2345
+ return { error: { code: "TICKET_FAILED", message: `HTTP ${response.status}` } };
2346
+ }
2347
+ const data = await response.json();
2348
+ return { data };
2349
+ } catch (err) {
2350
+ return { error: { code: "TICKET_FAILED", message: err.message } };
2351
+ }
2352
+ }, [entityType, entityId, ticketEndpoint]);
2353
+ const connectWithTicket = useCallback(async () => {
2354
+ if (connectingRef.current) return;
2355
+ connectingRef.current = true;
2356
+ let result = null;
2357
+ const maxRetries = 3;
2358
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2359
+ result = await fetchTicket();
2360
+ if (!isMountedRef.current) {
2361
+ connectingRef.current = false;
2362
+ return;
2363
+ }
2364
+ if (!result.error) break;
2365
+ if (result.error.code === "TICKET_UNAUTHORIZED") break;
2366
+ if (attempt < maxRetries) {
2367
+ await new Promise((r) => setTimeout(r, 1e3 * Math.pow(2, attempt)));
2368
+ if (!isMountedRef.current) {
2369
+ connectingRef.current = false;
2370
+ return;
2371
+ }
2372
+ }
2373
+ }
2374
+ if (result.error) {
2375
+ setError2(result.error);
2376
+ setIsConnected(false);
2377
+ connectingRef.current = false;
2378
+ return;
2379
+ }
2380
+ setError2(null);
2381
+ const { ticket, wsUrl, expiresIn } = result.data;
2382
+ if (wsManagerRef.current) {
2383
+ wsManagerRef.current.disconnect();
2384
+ }
2385
+ const { WebSocketManager: WsManagerClass } = await import("./websocket-34W2HQLH.js");
2386
+ const wsUrlWithTicket = `${wsUrl}?ticket=${encodeURIComponent(ticket)}`;
2387
+ const manager = new WsManagerClass(wsUrlWithTicket, "");
2388
+ manager.disableAutoReconnect = true;
2389
+ wsManagerRef.current = manager;
2390
+ manager.onStateChange((state) => {
2391
+ if (!isMountedRef.current) return;
2392
+ if (wsManagerRef.current !== manager) return;
2393
+ if (state === "connected") {
2394
+ connectingRef.current = false;
2395
+ reconnectCountRef.current = 0;
2396
+ lastConnectedAtRef.current = Date.now();
2397
+ setIsConnected(true);
2398
+ setError2(null);
2399
+ if (hasConnectedOnceRef.current) {
2400
+ void resyncFromHttp();
2401
+ }
2402
+ hasConnectedOnceRef.current = true;
2403
+ } else if (state === "disconnected") {
2404
+ connectingRef.current = false;
2405
+ setIsConnected(false);
2406
+ const wasStable = hasConnectedOnceRef.current && Date.now() - lastConnectedAtRef.current > 5e3;
2407
+ if (wasStable && reconnectCountRef.current < 5) {
2408
+ reconnectCountRef.current++;
2409
+ const delay = 2e3 * Math.pow(2, reconnectCountRef.current - 1);
2410
+ setTimeout(() => {
2411
+ if (isMountedRef.current && !connectingRef.current) {
2412
+ connectRef.current();
2413
+ }
2414
+ }, delay);
2415
+ }
2416
+ }
2417
+ });
2418
+ manager.onMessage((msg) => {
2419
+ if (!isMountedRef.current) return;
2420
+ if (msg.type === "entity.created" || msg.type === "entity.updated") {
2421
+ const payload = msg.payload;
2422
+ if (payload.data) {
2423
+ monoriseStore.setState(
2424
+ produce5((state) => {
2425
+ const key = payload.entityType;
2426
+ if (!state.entity[key]) {
2427
+ state.entity[key] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
2428
+ }
2429
+ state.entity[key].dataMap.set(payload.entityId, payload.data);
2430
+ })
2431
+ );
2432
+ }
2433
+ } else if (msg.type === "entity.deleted") {
2434
+ const payload = msg.payload;
2435
+ monoriseStore.setState(
2436
+ produce5((state) => {
2437
+ var _a, _b;
2438
+ (_b = (_a = state.entity[payload.entityType]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.delete(payload.entityId);
2439
+ })
2440
+ );
2441
+ } else if (msg.type === "mutual.created" || msg.type === "mutual.updated") {
2442
+ const payload = msg.payload;
2443
+ if (payload.data) {
2444
+ const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;
2445
+ monoriseStore.setState(
2446
+ produce5((state) => {
2447
+ if (!state.mutual[mutualKey]) {
2448
+ state.mutual[mutualKey] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
2449
+ }
2450
+ state.mutual[mutualKey].dataMap.set(payload.entityId, payload.data);
2451
+ })
2452
+ );
2453
+ }
2454
+ } else if (msg.type === "mutual.deleted") {
2455
+ const payload = msg.payload;
2456
+ const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;
2457
+ monoriseStore.setState(
2458
+ produce5((state) => {
2459
+ var _a, _b;
2460
+ (_b = (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.delete(payload.entityId);
2461
+ })
2462
+ );
2463
+ }
2464
+ });
2465
+ manager.connect();
2466
+ if (refreshTimerRef.current) {
2467
+ clearTimeout(refreshTimerRef.current);
2468
+ }
2469
+ const refreshMs = Math.max((expiresIn - 120) * 1e3, 6e4);
2470
+ refreshTimerRef.current = setTimeout(() => {
2471
+ if (isMountedRef.current) {
2472
+ connectRef.current();
2473
+ }
2474
+ }, refreshMs);
2475
+ }, [fetchTicket]);
2476
+ connectRef.current = connectWithTicket;
2477
+ useEffect3(() => {
2478
+ isMountedRef.current = true;
2479
+ if (entityId) {
2480
+ connectRef.current();
2481
+ }
2482
+ let lastCheckTime = Date.now();
2483
+ const sleepCheckInterval = setInterval(() => {
2484
+ const now = Date.now();
2485
+ const elapsed = now - lastCheckTime;
2486
+ lastCheckTime = now;
2487
+ if (elapsed > 3e4 && wsManagerRef.current) {
2488
+ wsManagerRef.current.disconnect();
2489
+ wsManagerRef.current = null;
2490
+ connectingRef.current = false;
2491
+ reconnectCountRef.current = 0;
2492
+ connectRef.current();
2493
+ }
2494
+ }, 5e3);
2495
+ const handleOnline = () => {
2496
+ var _a;
2497
+ if (!isMountedRef.current) return;
2498
+ if (((_a = wsManagerRef.current) == null ? void 0 : _a.getState()) === "connected") return;
2499
+ if (connectingRef.current) return;
2500
+ reconnectCountRef.current = 0;
2501
+ connectRef.current();
2502
+ };
2503
+ window.addEventListener("online", handleOnline);
2504
+ return () => {
2505
+ isMountedRef.current = false;
2506
+ clearInterval(sleepCheckInterval);
2507
+ window.removeEventListener("online", handleOnline);
2508
+ if (refreshTimerRef.current) {
2509
+ clearTimeout(refreshTimerRef.current);
2510
+ }
2511
+ if (wsManagerRef.current) {
2512
+ wsManagerRef.current.disconnect();
2513
+ wsManagerRef.current = null;
2514
+ }
2515
+ };
2516
+ }, [entityType, entityId]);
2517
+ return { isConnected, error };
2518
+ };
2519
+ return {
2520
+ useEntitySocket: useEntitySocket2,
2521
+ useMutualSocket: useMutualSocket2,
2522
+ useEphemeralSocket: useEphemeralSocket2,
2523
+ useEntityFeed: useEntityFeed2
2524
+ };
2525
+ };
2526
+
1983
2527
  // lib/api.ts
1984
2528
  import request from "axios";
1985
2529
  var initAxiosInterceptor = (store2, appActions) => {
@@ -2655,6 +3199,19 @@ var initMonorise = () => {
2655
3199
  const coreService2 = core_service_default(store2, axios2);
2656
3200
  const authActions = initAuthActions(store2, authService2);
2657
3201
  const coreActions = initCoreActions(store2, appActions, coreService2);
3202
+ const websocketActions = initWebSocketActions(store2, {
3203
+ listEntities: async (entityType, params) => {
3204
+ const { data } = await coreService2.makeEntityService(entityType).listEntities({ limit: params == null ? void 0 : params.limit, lastKey: params == null ? void 0 : params.lastKey });
3205
+ return { data: data.data, lastKey: data.lastKey };
3206
+ },
3207
+ listEntitiesByEntity: async (byEntityType, byEntityId2, entityType, params) => {
3208
+ const { data } = await coreService2.makeMutualService(byEntityType, entityType).listEntitiesByEntity(byEntityId2, {
3209
+ limit: params == null ? void 0 : params.limit,
3210
+ params: { lastKey: params == null ? void 0 : params.lastKey }
3211
+ });
3212
+ return { entities: data.entities, lastKey: data.lastKey };
3213
+ }
3214
+ });
2658
3215
  const axiosInterceptor = injectAxiosInterceptor(
2659
3216
  appActions,
2660
3217
  authActions,
@@ -2680,14 +3237,14 @@ var initMonorise = () => {
2680
3237
  onApiSuccess: opts.onApiSuccess
2681
3238
  });
2682
3239
  };
2683
- return __spreadValues(__spreadValues(__spreadValues(__spreadValues({
3240
+ return __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
2684
3241
  config,
2685
3242
  store: store2,
2686
3243
  axios: axios2,
2687
3244
  authService: authService2,
2688
3245
  filestoreService: filestoreService2,
2689
3246
  coreService: coreService2
2690
- }, configActions), appActions), authActions), coreActions);
3247
+ }, configActions), appActions), authActions), coreActions), websocketActions);
2691
3248
  };
2692
3249
  var Monorise = initMonorise();
2693
3250
  var {
@@ -2740,10 +3297,15 @@ var {
2740
3297
  useEntityState,
2741
3298
  getEntity,
2742
3299
  updateLocalTaggedEntity,
2743
- deleteLocalTaggedEntity
3300
+ deleteLocalTaggedEntity,
3301
+ useEntitySocket,
3302
+ useMutualSocket,
3303
+ useEphemeralSocket,
3304
+ useEntityFeed
2744
3305
  } = Monorise;
2745
3306
  var index_default = Monorise;
2746
3307
  export {
3308
+ WebSocketManager,
2747
3309
  adjustEntity,
2748
3310
  authService,
2749
3311
  axios,
@@ -2772,6 +3334,8 @@ export {
2772
3334
  getProfile,
2773
3335
  getTagRequestKey,
2774
3336
  getUniqueFieldRequestKey,
3337
+ getWebSocketManager,
3338
+ initializeWebSocketManager,
2775
3339
  listMoreEntities,
2776
3340
  logout,
2777
3341
  openModal,
@@ -2790,13 +3354,17 @@ export {
2790
3354
  useEntities,
2791
3355
  useEntity,
2792
3356
  useEntityByUniqueField,
3357
+ useEntityFeed,
3358
+ useEntitySocket,
2793
3359
  useEntityState,
3360
+ useEphemeralSocket,
2794
3361
  useErrorStore,
2795
3362
  useInterruptiveLoadStore,
2796
3363
  useIsUnauthorized,
2797
3364
  useLoadStore,
2798
3365
  useModalStore,
2799
3366
  useMutual,
3367
+ useMutualSocket,
2800
3368
  useMutuals,
2801
3369
  useProfile,
2802
3370
  useTaggedEntities