@monorise/react 8.1.0 → 8.3.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";
@@ -390,9 +365,41 @@ var getTransactionOperationRequestKey = (op) => {
390
365
  return getEntityRequestKey("adjust", op.entityType, op.entityId);
391
366
  case "deleteEntity":
392
367
  return getEntityRequestKey("delete", op.entityType, op.entityId);
368
+ // Same keys the standalone createMutual / editMutual / deleteMutual calls
369
+ // use, so a component watching one sees the transaction's loading/error.
370
+ case "createMutual":
371
+ return getMutualRequestKey(
372
+ "create",
373
+ op.byEntityType,
374
+ op.entityType,
375
+ op.byEntityId
376
+ );
377
+ case "updateMutual":
378
+ return getMutualRequestKey(
379
+ "update",
380
+ op.byEntityType,
381
+ op.entityType,
382
+ op.byEntityId,
383
+ op.entityId
384
+ );
385
+ case "deleteMutual":
386
+ return getMutualRequestKey(
387
+ "delete",
388
+ op.byEntityType,
389
+ op.entityType,
390
+ op.byEntityId,
391
+ op.entityId
392
+ );
393
393
  }
394
394
  };
395
- var getTransactionCallRequestKey = (operations) => `transaction/${operations.map(getTransactionOperationRequestKey).join("|")}`;
395
+ var getTransactionOperationCallSegment = (op) => op.operation === "createMutual" ? getMutualRequestKey(
396
+ "create",
397
+ op.byEntityType,
398
+ op.entityType,
399
+ op.byEntityId,
400
+ op.entityId
401
+ ) : getTransactionOperationRequestKey(op);
402
+ var getTransactionCallRequestKey = (operations) => `transaction/${operations.map(getTransactionOperationCallSegment).join("|")}`;
396
403
  var transactional = {
397
404
  createEntity: (entityType, payload) => {
398
405
  const _a = payload, { entityId } = _a, rest = __objRest(_a, ["entityId"]);
@@ -424,6 +431,30 @@ var transactional = {
424
431
  operation: "deleteEntity",
425
432
  entityType,
426
433
  entityId
434
+ }),
435
+ // Same argument order as the standalone createMutual / editMutual /
436
+ // deleteMutual actions.
437
+ createMutual: (byEntityType, entityType, byEntityId2, entityId, payload) => __spreadValues({
438
+ operation: "createMutual",
439
+ byEntityType,
440
+ byEntityId: byEntityId2,
441
+ entityType,
442
+ entityId
443
+ }, payload !== void 0 && { payload }),
444
+ updateMutual: (byEntityType, entityType, byEntityId2, entityId, payload) => ({
445
+ operation: "updateMutual",
446
+ byEntityType,
447
+ byEntityId: byEntityId2,
448
+ entityType,
449
+ entityId,
450
+ payload
451
+ }),
452
+ deleteMutual: (byEntityType, entityType, byEntityId2, entityId) => ({
453
+ operation: "deleteMutual",
454
+ byEntityType,
455
+ byEntityId: byEntityId2,
456
+ entityType,
457
+ entityId
427
458
  })
428
459
  };
429
460
 
@@ -1019,18 +1050,66 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1019
1050
  monoriseStore.setState(
1020
1051
  produce4((state) => {
1021
1052
  data.results.forEach((entry, index) => {
1022
- var _a2, _b2, _c2;
1053
+ var _a2, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l;
1023
1054
  const { entityType, entityId } = entry;
1024
1055
  if (entry.operation === "deleteEntity") {
1025
1056
  deleteEntityFromStores(state, entityType, entityId);
1026
1057
  deletedEntities.push({ entityType, entityId });
1027
1058
  return;
1028
1059
  }
1060
+ if (entry.operation === "createMutual" || entry.operation === "updateMutual" || entry.operation === "deleteMutual") {
1061
+ const byEntityType = entry.byEntityType;
1062
+ const byEntityId2 = entry.byEntityId;
1063
+ const bySide = getMutualStateKey(
1064
+ byEntityType,
1065
+ byEntityId2,
1066
+ entityType
1067
+ );
1068
+ const side = getMutualStateKey(
1069
+ entityType,
1070
+ entityId,
1071
+ byEntityType
1072
+ );
1073
+ if (entry.operation === "deleteMutual") {
1074
+ (_a2 = state.mutual[bySide]) == null ? void 0 : _a2.dataMap.delete(entityId);
1075
+ (_b2 = state.mutual[side]) == null ? void 0 : _b2.dataMap.delete(byEntityId2);
1076
+ return;
1077
+ }
1078
+ if (entry.operation === "updateMutual" && !entry.mutualData) {
1079
+ return;
1080
+ }
1081
+ const mutual = {
1082
+ byEntityType,
1083
+ byEntityId: byEntityId2,
1084
+ entityType,
1085
+ entityId,
1086
+ mutualId: entry.mutualId,
1087
+ data: (_c2 = entry.data) != null ? _c2 : {},
1088
+ mutualData: (_d2 = entry.mutualData) != null ? _d2 : {},
1089
+ createdAt: entry.createdAt,
1090
+ updatedAt: entry.updatedAt,
1091
+ mutualUpdatedAt: entry.mutualUpdatedAt
1092
+ };
1093
+ if (!state.mutual[bySide]) {
1094
+ state.mutual[bySide] = { dataMap: /* @__PURE__ */ new Map() };
1095
+ }
1096
+ state.mutual[bySide].dataMap = new Map(
1097
+ (_e = state.mutual[bySide]) == null ? void 0 : _e.dataMap
1098
+ ).set(entityId, mutual);
1099
+ if (!state.mutual[side]) {
1100
+ state.mutual[side] = { dataMap: /* @__PURE__ */ new Map() };
1101
+ }
1102
+ const byEntityData = (_h = (_g = (_f = state.entity[byEntityType]) == null ? void 0 : _f.dataMap.get(byEntityId2)) == null ? void 0 : _g.data) != null ? _h : {};
1103
+ state.mutual[side].dataMap = new Map(
1104
+ (_i = state.mutual[side]) == null ? void 0 : _i.dataMap
1105
+ ).set(byEntityId2, flipMutual(mutual, byEntityData));
1106
+ return;
1107
+ }
1029
1108
  if (entry.operation === "createEntity") {
1030
1109
  const createdEntity = {
1031
1110
  entityId,
1032
1111
  entityType,
1033
- data: (_a2 = entry.data) != null ? _a2 : {},
1112
+ data: (_j = entry.data) != null ? _j : {},
1034
1113
  createdAt: entry.createdAt,
1035
1114
  updatedAt: entry.updatedAt
1036
1115
  };
@@ -1050,7 +1129,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1050
1129
  );
1051
1130
  return;
1052
1131
  }
1053
- const existing = (_b2 = state.entity[entityType]) == null ? void 0 : _b2.dataMap.get(entityId);
1132
+ const existing = (_k = state.entity[entityType]) == null ? void 0 : _k.dataMap.get(entityId);
1054
1133
  if (!existing && !entry.data) return;
1055
1134
  if (!entry.data) {
1056
1135
  if (entry.updatedAt) {
@@ -1062,7 +1141,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1062
1141
  }
1063
1142
  const updated = __spreadProps(__spreadValues({}, existing != null ? existing : { entityId, entityType }), {
1064
1143
  data: entry.data,
1065
- updatedAt: (_c2 = entry.updatedAt) != null ? _c2 : existing == null ? void 0 : existing.updatedAt
1144
+ updatedAt: (_l = entry.updatedAt) != null ? _l : existing == null ? void 0 : existing.updatedAt
1066
1145
  });
1067
1146
  state.entity[entityType].dataMap.set(entityId, updated);
1068
1147
  propagateEntityDataToMutuals(state, entityType, entityId, updated.data);
@@ -1447,16 +1526,15 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1447
1526
  );
1448
1527
  monoriseStore.setState(
1449
1528
  produce4((state) => {
1529
+ var _a2, _b;
1450
1530
  const bySide = getMutualStateKey(
1451
1531
  byEntityType,
1452
1532
  byEntityId2,
1453
1533
  entityType
1454
1534
  );
1455
1535
  const side = getMutualStateKey(entityType, entityId, byEntityType);
1456
- state.mutual[bySide].dataMap.delete(data.entityId);
1457
- if (state.mutual[side]) {
1458
- state.mutual[side].dataMap.delete(data.byEntityId);
1459
- }
1536
+ (_a2 = state.mutual[bySide]) == null ? void 0 : _a2.dataMap.delete(data.entityId);
1537
+ (_b = state.mutual[side]) == null ? void 0 : _b.dataMap.delete(data.byEntityId);
1460
1538
  }),
1461
1539
  void 0,
1462
1540
  `mr/mutual/delete/${getMutualStateKey(byEntityType, byEntityId2, entityType, entityId)}`
@@ -1980,6 +2058,575 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1980
2058
  };
1981
2059
  };
1982
2060
 
2061
+ // actions/websocket.action.ts
2062
+ import { useCallback, useEffect as useEffect3, useRef, useState as useState3 } from "react";
2063
+ import { produce as produce5 } from "immer";
2064
+ var globalWsManager = null;
2065
+ var wsEndpoint;
2066
+ var initializeWebSocketManager = (WebSocketManagerClass, endpoint, token) => {
2067
+ if (globalWsManager) return globalWsManager;
2068
+ wsEndpoint = endpoint;
2069
+ globalWsManager = new WebSocketManagerClass(endpoint, token || "");
2070
+ globalWsManager.connect();
2071
+ return globalWsManager;
2072
+ };
2073
+ var getWebSocketManager = () => globalWsManager;
2074
+ var initWebSocketActions = (monoriseStore, httpActions) => {
2075
+ const useEntitySocket2 = (entityType, opts = {}) => {
2076
+ const { limit = 20, skipInitialFetch = false } = opts;
2077
+ const [isLoading, setIsLoading] = useState3(!skipInitialFetch);
2078
+ const [isFetchingMore, setIsFetchingMore] = useState3(false);
2079
+ const [isRefreshing, setIsRefreshing] = useState3(false);
2080
+ const [isSubscribed, setIsSubscribed] = useState3(false);
2081
+ const [error, setError2] = useState3(null);
2082
+ const [hasMore, setHasMore] = useState3(true);
2083
+ const lastKeyRef = useRef(void 0);
2084
+ const isFirstFetchRef = useRef(true);
2085
+ const entities = monoriseStore((state) => {
2086
+ var _a;
2087
+ const entityState = state.entity[entityType];
2088
+ return Array.from(((_a = entityState == null ? void 0 : entityState.dataMap) == null ? void 0 : _a.values()) || []);
2089
+ });
2090
+ const fetchData = async (type) => {
2091
+ if (!httpActions) return;
2092
+ if (type === "more") {
2093
+ setIsFetchingMore(true);
2094
+ } else if (type === "refresh") {
2095
+ setIsRefreshing(true);
2096
+ } else {
2097
+ setIsLoading(true);
2098
+ }
2099
+ setError2(null);
2100
+ try {
2101
+ const fetchLastKey = type === "refresh" ? void 0 : lastKeyRef.current;
2102
+ const result = await httpActions.listEntities(entityType, {
2103
+ limit,
2104
+ lastKey: fetchLastKey
2105
+ });
2106
+ monoriseStore.setState(
2107
+ produce5((state) => {
2108
+ if (type === "refresh") {
2109
+ state.entity[entityType].dataMap.clear();
2110
+ }
2111
+ for (const entity of result.data) {
2112
+ state.entity[entityType].dataMap.set(entity.entityId, entity);
2113
+ }
2114
+ state.entity[entityType].isFirstFetched = true;
2115
+ state.entity[entityType].lastKey = result.lastKey;
2116
+ })
2117
+ );
2118
+ lastKeyRef.current = result.lastKey;
2119
+ setHasMore(!!result.lastKey);
2120
+ } catch (err) {
2121
+ setError2(err instanceof Error ? err : new Error("Failed to fetch"));
2122
+ } finally {
2123
+ setIsLoading(false);
2124
+ setIsFetchingMore(false);
2125
+ setIsRefreshing(false);
2126
+ }
2127
+ };
2128
+ useEffect3(() => {
2129
+ if (skipInitialFetch) return;
2130
+ fetchData("initial");
2131
+ }, [entityType, limit, skipInitialFetch]);
2132
+ useEffect3(() => {
2133
+ if (!globalWsManager) {
2134
+ setIsSubscribed(false);
2135
+ return;
2136
+ }
2137
+ const subKey = globalWsManager.subscribeEntityType(entityType);
2138
+ setIsSubscribed(true);
2139
+ let wasConnected = false;
2140
+ const unsubscribeState = globalWsManager.onStateChange((state) => {
2141
+ if (state === "connected" && wasConnected === false && !isFirstFetchRef.current) {
2142
+ fetchData("refresh");
2143
+ }
2144
+ wasConnected = state === "connected";
2145
+ isFirstFetchRef.current = false;
2146
+ });
2147
+ const unsubscribeMessage = globalWsManager.onMessage(
2148
+ (msg) => {
2149
+ if (msg.type === "entity.created" || msg.type === "entity.updated" || msg.type === "entity.deleted") {
2150
+ const payload = msg.payload;
2151
+ if (payload.entityType !== entityType) return;
2152
+ if (msg.type === "entity.created" || msg.type === "entity.updated") {
2153
+ if (payload.data) {
2154
+ monoriseStore.setState(
2155
+ produce5((state) => {
2156
+ const key = entityType;
2157
+ if (!state.entity[key]) {
2158
+ state.entity[key] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
2159
+ }
2160
+ state.entity[key].dataMap.set(
2161
+ payload.entityId,
2162
+ payload.data
2163
+ );
2164
+ })
2165
+ );
2166
+ }
2167
+ } else if (msg.type === "entity.deleted") {
2168
+ monoriseStore.setState(
2169
+ produce5((state) => {
2170
+ var _a;
2171
+ const key = entityType;
2172
+ if ((_a = state.entity[key]) == null ? void 0 : _a.dataMap) {
2173
+ state.entity[key].dataMap.delete(payload.entityId);
2174
+ }
2175
+ })
2176
+ );
2177
+ }
2178
+ }
2179
+ }
2180
+ );
2181
+ return () => {
2182
+ globalWsManager == null ? void 0 : globalWsManager.unsubscribeEntityType(subKey);
2183
+ unsubscribeState();
2184
+ unsubscribeMessage();
2185
+ setIsSubscribed(false);
2186
+ };
2187
+ }, [entityType]);
2188
+ const fetchMore = async () => {
2189
+ if (!hasMore || isFetchingMore) return;
2190
+ await fetchData("more");
2191
+ };
2192
+ return {
2193
+ entities,
2194
+ isLoading,
2195
+ isFetchingMore,
2196
+ isSubscribed,
2197
+ error,
2198
+ isRefreshing,
2199
+ fetchMore,
2200
+ hasMore
2201
+ };
2202
+ };
2203
+ const useMutualSocket2 = (byEntityType, byEntityId2, mutualEntityType, opts = {}) => {
2204
+ const { limit = 20, skipInitialFetch = false } = opts;
2205
+ const [isLoading, setIsLoading] = useState3(
2206
+ !skipInitialFetch && !!byEntityId2
2207
+ );
2208
+ const [isFetchingMore, setIsFetchingMore] = useState3(false);
2209
+ const [isRefreshing, setIsRefreshing] = useState3(false);
2210
+ const [isSubscribed, setIsSubscribed] = useState3(false);
2211
+ const [error, setError2] = useState3(null);
2212
+ const [hasMore, setHasMore] = useState3(true);
2213
+ const lastKeyRef = useRef(void 0);
2214
+ const isFirstFetchRef = useRef(true);
2215
+ const mutualKey = byEntityId2 ? `${byEntityType}/${byEntityId2}/${mutualEntityType}` : "";
2216
+ const mutuals = monoriseStore((state) => {
2217
+ var _a, _b;
2218
+ return Array.from(((_b = (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.values()) || []);
2219
+ });
2220
+ const fetchData = async (type) => {
2221
+ if (!byEntityId2 || !httpActions) return;
2222
+ if (type === "more") {
2223
+ setIsFetchingMore(true);
2224
+ } else if (type === "refresh") {
2225
+ setIsRefreshing(true);
2226
+ } else {
2227
+ setIsLoading(true);
2228
+ }
2229
+ setError2(null);
2230
+ try {
2231
+ const fetchLastKey = type === "refresh" ? void 0 : lastKeyRef.current;
2232
+ const result = await httpActions.listEntitiesByEntity(
2233
+ byEntityType,
2234
+ byEntityId2,
2235
+ mutualEntityType,
2236
+ { limit, lastKey: fetchLastKey }
2237
+ );
2238
+ monoriseStore.setState(
2239
+ produce5((state) => {
2240
+ if (!state.mutual[mutualKey]) {
2241
+ state.mutual[mutualKey] = {
2242
+ dataMap: /* @__PURE__ */ new Map(),
2243
+ isFirstFetched: true,
2244
+ lastKey: void 0
2245
+ };
2246
+ }
2247
+ if (type === "refresh") {
2248
+ state.mutual[mutualKey].dataMap.clear();
2249
+ }
2250
+ for (const entity of result.entities) {
2251
+ const e = entity;
2252
+ state.mutual[mutualKey].dataMap.set(e.entityId, entity);
2253
+ }
2254
+ state.mutual[mutualKey].lastKey = result.lastKey;
2255
+ })
2256
+ );
2257
+ lastKeyRef.current = result.lastKey;
2258
+ setHasMore(!!result.lastKey);
2259
+ } catch (err) {
2260
+ setError2(err instanceof Error ? err : new Error("Failed to fetch"));
2261
+ } finally {
2262
+ setIsLoading(false);
2263
+ setIsFetchingMore(false);
2264
+ setIsRefreshing(false);
2265
+ }
2266
+ };
2267
+ useEffect3(() => {
2268
+ if (skipInitialFetch || !byEntityId2) {
2269
+ setIsLoading(false);
2270
+ return;
2271
+ }
2272
+ lastKeyRef.current = void 0;
2273
+ setHasMore(true);
2274
+ isFirstFetchRef.current = true;
2275
+ fetchData("initial");
2276
+ }, [byEntityType, byEntityId2, mutualEntityType, limit, skipInitialFetch]);
2277
+ useEffect3(() => {
2278
+ if (!globalWsManager || !byEntityId2) {
2279
+ setIsSubscribed(false);
2280
+ return;
2281
+ }
2282
+ const subKey = globalWsManager.subscribeMutualType(
2283
+ byEntityType,
2284
+ byEntityId2,
2285
+ mutualEntityType
2286
+ );
2287
+ setIsSubscribed(true);
2288
+ let wasConnected = false;
2289
+ const unsubscribeState = globalWsManager.onStateChange((state) => {
2290
+ if (state === "connected" && wasConnected === false && !isFirstFetchRef.current) {
2291
+ fetchData("refresh");
2292
+ }
2293
+ wasConnected = state === "connected";
2294
+ isFirstFetchRef.current = false;
2295
+ });
2296
+ const unsubscribeMessage = globalWsManager.onMessage(
2297
+ (msg) => {
2298
+ if (msg.type === "mutual.created" || msg.type === "mutual.updated" || msg.type === "mutual.deleted") {
2299
+ const payload = msg.payload;
2300
+ if (payload.byEntityType !== byEntityType || payload.byEntityId !== byEntityId2 || payload.mutualEntityType !== mutualEntityType) {
2301
+ return;
2302
+ }
2303
+ if (msg.type === "mutual.created" || msg.type === "mutual.updated") {
2304
+ if (payload.data) {
2305
+ monoriseStore.setState(
2306
+ produce5((state) => {
2307
+ if (!state.mutual[mutualKey]) {
2308
+ state.mutual[mutualKey] = {
2309
+ dataMap: /* @__PURE__ */ new Map(),
2310
+ isFirstFetched: true,
2311
+ lastKey: void 0
2312
+ };
2313
+ }
2314
+ state.mutual[mutualKey].dataMap.set(
2315
+ payload.entityId,
2316
+ payload.data
2317
+ );
2318
+ })
2319
+ );
2320
+ }
2321
+ } else if (msg.type === "mutual.deleted") {
2322
+ monoriseStore.setState(
2323
+ produce5((state) => {
2324
+ var _a;
2325
+ (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap.delete(payload.entityId);
2326
+ })
2327
+ );
2328
+ }
2329
+ }
2330
+ }
2331
+ );
2332
+ return () => {
2333
+ globalWsManager == null ? void 0 : globalWsManager.unsubscribeMutualType(subKey);
2334
+ unsubscribeState();
2335
+ unsubscribeMessage();
2336
+ setIsSubscribed(false);
2337
+ };
2338
+ }, [byEntityType, byEntityId2, mutualEntityType, mutualKey]);
2339
+ const fetchMore = async () => {
2340
+ if (!hasMore || isFetchingMore) return;
2341
+ await fetchData("more");
2342
+ };
2343
+ return {
2344
+ mutuals,
2345
+ isLoading,
2346
+ isFetchingMore,
2347
+ isSubscribed,
2348
+ error,
2349
+ isRefreshing,
2350
+ fetchMore,
2351
+ hasMore
2352
+ };
2353
+ };
2354
+ const useEphemeralSocket2 = (channel, opts) => {
2355
+ const [isSubscribed, setIsSubscribed] = useState3(false);
2356
+ useEffect3(() => {
2357
+ if (!globalWsManager || !channel) {
2358
+ setIsSubscribed(false);
2359
+ return;
2360
+ }
2361
+ const subKey = globalWsManager.subscribeEphemeral(channel);
2362
+ setIsSubscribed(true);
2363
+ const unsubscribeMessage = globalWsManager.onMessage(
2364
+ (msg) => {
2365
+ var _a;
2366
+ if (msg.type === "ephemeral") {
2367
+ const payload = msg.payload;
2368
+ if (payload.channel !== channel) return;
2369
+ (_a = opts == null ? void 0 : opts.onMessage) == null ? void 0 : _a.call(opts, payload.data, payload.senderId);
2370
+ }
2371
+ }
2372
+ );
2373
+ return () => {
2374
+ globalWsManager == null ? void 0 : globalWsManager.unsubscribeEphemeral(subKey);
2375
+ unsubscribeMessage();
2376
+ setIsSubscribed(false);
2377
+ };
2378
+ }, [channel]);
2379
+ const send = useCallback(
2380
+ (data) => {
2381
+ if (!globalWsManager || !channel) return;
2382
+ globalWsManager.sendEphemeral(channel, data);
2383
+ },
2384
+ [channel]
2385
+ );
2386
+ return { isSubscribed, send };
2387
+ };
2388
+ const useEntityFeed2 = (opts) => {
2389
+ const { entityType, entityId, ticketEndpoint } = opts;
2390
+ const [isConnected, setIsConnected] = useState3(false);
2391
+ const [error, setError2] = useState3(null);
2392
+ const refreshTimerRef = useRef(null);
2393
+ const hasConnectedOnceRef = useRef(false);
2394
+ const resyncFromHttp = async () => {
2395
+ var _a, _b;
2396
+ if (!httpActions) return;
2397
+ const snapshot = monoriseStore.getState();
2398
+ const keys = Object.keys((_a = snapshot.mutual) != null ? _a : {});
2399
+ for (const key of keys) {
2400
+ const parsed = parseMutualStateKey(key);
2401
+ if (parsed.entityId) continue;
2402
+ if (parsed.byEntityId !== entityId) continue;
2403
+ if (!((_b = snapshot.mutual[key]) == null ? void 0 : _b.isFirstFetched)) continue;
2404
+ try {
2405
+ const result = await httpActions.listEntitiesByEntity(
2406
+ parsed.byEntity,
2407
+ parsed.byEntityId,
2408
+ parsed.entity
2409
+ );
2410
+ if (!isMountedRef.current) return;
2411
+ monoriseStore.setState(
2412
+ produce5((draft) => {
2413
+ const slice = draft.mutual[key];
2414
+ if (!slice) return;
2415
+ slice.dataMap.clear();
2416
+ for (const mutual of result.entities) {
2417
+ slice.dataMap.set(mutual.entityId, mutual);
2418
+ }
2419
+ slice.lastKey = result.lastKey;
2420
+ })
2421
+ );
2422
+ } catch (e) {
2423
+ }
2424
+ }
2425
+ };
2426
+ const wsManagerRef = useRef(null);
2427
+ const isMountedRef = useRef(true);
2428
+ const connectingRef = useRef(false);
2429
+ const reconnectCountRef = useRef(0);
2430
+ const connectRef = useRef(() => {
2431
+ });
2432
+ const lastConnectedAtRef = useRef(0);
2433
+ const fetchTicket = useCallback(async () => {
2434
+ try {
2435
+ const url = ticketEndpoint || `/api/core/ws/ticket/${entityType}/${entityId}`;
2436
+ const fetchOpts = {
2437
+ method: "POST",
2438
+ headers: { "Content-Type": "application/json" }
2439
+ };
2440
+ if (ticketEndpoint) {
2441
+ fetchOpts.body = JSON.stringify({ entityType, entityId });
2442
+ }
2443
+ const response = await fetch(url, fetchOpts);
2444
+ if (response.status === 401 || response.status === 403) {
2445
+ return { error: { code: "TICKET_UNAUTHORIZED", message: "Unauthorized" } };
2446
+ }
2447
+ if (!response.ok) {
2448
+ return { error: { code: "TICKET_FAILED", message: `HTTP ${response.status}` } };
2449
+ }
2450
+ const data = await response.json();
2451
+ return { data };
2452
+ } catch (err) {
2453
+ return { error: { code: "TICKET_FAILED", message: err.message } };
2454
+ }
2455
+ }, [entityType, entityId, ticketEndpoint]);
2456
+ const connectWithTicket = useCallback(async () => {
2457
+ if (connectingRef.current) return;
2458
+ connectingRef.current = true;
2459
+ let result = null;
2460
+ const maxRetries = 3;
2461
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2462
+ result = await fetchTicket();
2463
+ if (!isMountedRef.current) {
2464
+ connectingRef.current = false;
2465
+ return;
2466
+ }
2467
+ if (!result.error) break;
2468
+ if (result.error.code === "TICKET_UNAUTHORIZED") break;
2469
+ if (attempt < maxRetries) {
2470
+ await new Promise((r) => setTimeout(r, 1e3 * Math.pow(2, attempt)));
2471
+ if (!isMountedRef.current) {
2472
+ connectingRef.current = false;
2473
+ return;
2474
+ }
2475
+ }
2476
+ }
2477
+ if (result.error) {
2478
+ setError2(result.error);
2479
+ setIsConnected(false);
2480
+ connectingRef.current = false;
2481
+ return;
2482
+ }
2483
+ setError2(null);
2484
+ const { ticket, wsUrl, expiresIn } = result.data;
2485
+ if (wsManagerRef.current) {
2486
+ wsManagerRef.current.disconnect();
2487
+ }
2488
+ const { WebSocketManager: WsManagerClass } = await import("./websocket-34W2HQLH.js");
2489
+ const wsUrlWithTicket = `${wsUrl}?ticket=${encodeURIComponent(ticket)}`;
2490
+ const manager = new WsManagerClass(wsUrlWithTicket, "");
2491
+ manager.disableAutoReconnect = true;
2492
+ wsManagerRef.current = manager;
2493
+ manager.onStateChange((state) => {
2494
+ if (!isMountedRef.current) return;
2495
+ if (wsManagerRef.current !== manager) return;
2496
+ if (state === "connected") {
2497
+ connectingRef.current = false;
2498
+ reconnectCountRef.current = 0;
2499
+ lastConnectedAtRef.current = Date.now();
2500
+ setIsConnected(true);
2501
+ setError2(null);
2502
+ if (hasConnectedOnceRef.current) {
2503
+ void resyncFromHttp();
2504
+ }
2505
+ hasConnectedOnceRef.current = true;
2506
+ } else if (state === "disconnected") {
2507
+ connectingRef.current = false;
2508
+ setIsConnected(false);
2509
+ const wasStable = hasConnectedOnceRef.current && Date.now() - lastConnectedAtRef.current > 5e3;
2510
+ if (wasStable && reconnectCountRef.current < 5) {
2511
+ reconnectCountRef.current++;
2512
+ const delay = 2e3 * Math.pow(2, reconnectCountRef.current - 1);
2513
+ setTimeout(() => {
2514
+ if (isMountedRef.current && !connectingRef.current) {
2515
+ connectRef.current();
2516
+ }
2517
+ }, delay);
2518
+ }
2519
+ }
2520
+ });
2521
+ manager.onMessage((msg) => {
2522
+ if (!isMountedRef.current) return;
2523
+ if (msg.type === "entity.created" || msg.type === "entity.updated") {
2524
+ const payload = msg.payload;
2525
+ if (payload.data) {
2526
+ monoriseStore.setState(
2527
+ produce5((state) => {
2528
+ const key = payload.entityType;
2529
+ if (!state.entity[key]) {
2530
+ state.entity[key] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
2531
+ }
2532
+ state.entity[key].dataMap.set(payload.entityId, payload.data);
2533
+ })
2534
+ );
2535
+ }
2536
+ } else if (msg.type === "entity.deleted") {
2537
+ const payload = msg.payload;
2538
+ monoriseStore.setState(
2539
+ produce5((state) => {
2540
+ var _a, _b;
2541
+ (_b = (_a = state.entity[payload.entityType]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.delete(payload.entityId);
2542
+ })
2543
+ );
2544
+ } else if (msg.type === "mutual.created" || msg.type === "mutual.updated") {
2545
+ const payload = msg.payload;
2546
+ if (payload.data) {
2547
+ const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;
2548
+ monoriseStore.setState(
2549
+ produce5((state) => {
2550
+ if (!state.mutual[mutualKey]) {
2551
+ state.mutual[mutualKey] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
2552
+ }
2553
+ state.mutual[mutualKey].dataMap.set(payload.entityId, payload.data);
2554
+ })
2555
+ );
2556
+ }
2557
+ } else if (msg.type === "mutual.deleted") {
2558
+ const payload = msg.payload;
2559
+ const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;
2560
+ monoriseStore.setState(
2561
+ produce5((state) => {
2562
+ var _a, _b;
2563
+ (_b = (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.delete(payload.entityId);
2564
+ })
2565
+ );
2566
+ }
2567
+ });
2568
+ manager.connect();
2569
+ if (refreshTimerRef.current) {
2570
+ clearTimeout(refreshTimerRef.current);
2571
+ }
2572
+ const refreshMs = Math.max((expiresIn - 120) * 1e3, 6e4);
2573
+ refreshTimerRef.current = setTimeout(() => {
2574
+ if (isMountedRef.current) {
2575
+ connectRef.current();
2576
+ }
2577
+ }, refreshMs);
2578
+ }, [fetchTicket]);
2579
+ connectRef.current = connectWithTicket;
2580
+ useEffect3(() => {
2581
+ isMountedRef.current = true;
2582
+ if (entityId) {
2583
+ connectRef.current();
2584
+ }
2585
+ let lastCheckTime = Date.now();
2586
+ const sleepCheckInterval = setInterval(() => {
2587
+ const now = Date.now();
2588
+ const elapsed = now - lastCheckTime;
2589
+ lastCheckTime = now;
2590
+ if (elapsed > 3e4 && wsManagerRef.current) {
2591
+ wsManagerRef.current.disconnect();
2592
+ wsManagerRef.current = null;
2593
+ connectingRef.current = false;
2594
+ reconnectCountRef.current = 0;
2595
+ connectRef.current();
2596
+ }
2597
+ }, 5e3);
2598
+ const handleOnline = () => {
2599
+ var _a;
2600
+ if (!isMountedRef.current) return;
2601
+ if (((_a = wsManagerRef.current) == null ? void 0 : _a.getState()) === "connected") return;
2602
+ if (connectingRef.current) return;
2603
+ reconnectCountRef.current = 0;
2604
+ connectRef.current();
2605
+ };
2606
+ window.addEventListener("online", handleOnline);
2607
+ return () => {
2608
+ isMountedRef.current = false;
2609
+ clearInterval(sleepCheckInterval);
2610
+ window.removeEventListener("online", handleOnline);
2611
+ if (refreshTimerRef.current) {
2612
+ clearTimeout(refreshTimerRef.current);
2613
+ }
2614
+ if (wsManagerRef.current) {
2615
+ wsManagerRef.current.disconnect();
2616
+ wsManagerRef.current = null;
2617
+ }
2618
+ };
2619
+ }, [entityType, entityId]);
2620
+ return { isConnected, error };
2621
+ };
2622
+ return {
2623
+ useEntitySocket: useEntitySocket2,
2624
+ useMutualSocket: useMutualSocket2,
2625
+ useEphemeralSocket: useEphemeralSocket2,
2626
+ useEntityFeed: useEntityFeed2
2627
+ };
2628
+ };
2629
+
1983
2630
  // lib/api.ts
1984
2631
  import request from "axios";
1985
2632
  var initAxiosInterceptor = (store2, appActions) => {
@@ -2655,6 +3302,19 @@ var initMonorise = () => {
2655
3302
  const coreService2 = core_service_default(store2, axios2);
2656
3303
  const authActions = initAuthActions(store2, authService2);
2657
3304
  const coreActions = initCoreActions(store2, appActions, coreService2);
3305
+ const websocketActions = initWebSocketActions(store2, {
3306
+ listEntities: async (entityType, params) => {
3307
+ const { data } = await coreService2.makeEntityService(entityType).listEntities({ limit: params == null ? void 0 : params.limit, lastKey: params == null ? void 0 : params.lastKey });
3308
+ return { data: data.data, lastKey: data.lastKey };
3309
+ },
3310
+ listEntitiesByEntity: async (byEntityType, byEntityId2, entityType, params) => {
3311
+ const { data } = await coreService2.makeMutualService(byEntityType, entityType).listEntitiesByEntity(byEntityId2, {
3312
+ limit: params == null ? void 0 : params.limit,
3313
+ params: { lastKey: params == null ? void 0 : params.lastKey }
3314
+ });
3315
+ return { entities: data.entities, lastKey: data.lastKey };
3316
+ }
3317
+ });
2658
3318
  const axiosInterceptor = injectAxiosInterceptor(
2659
3319
  appActions,
2660
3320
  authActions,
@@ -2680,14 +3340,14 @@ var initMonorise = () => {
2680
3340
  onApiSuccess: opts.onApiSuccess
2681
3341
  });
2682
3342
  };
2683
- return __spreadValues(__spreadValues(__spreadValues(__spreadValues({
3343
+ return __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
2684
3344
  config,
2685
3345
  store: store2,
2686
3346
  axios: axios2,
2687
3347
  authService: authService2,
2688
3348
  filestoreService: filestoreService2,
2689
3349
  coreService: coreService2
2690
- }, configActions), appActions), authActions), coreActions);
3350
+ }, configActions), appActions), authActions), coreActions), websocketActions);
2691
3351
  };
2692
3352
  var Monorise = initMonorise();
2693
3353
  var {
@@ -2740,10 +3400,15 @@ var {
2740
3400
  useEntityState,
2741
3401
  getEntity,
2742
3402
  updateLocalTaggedEntity,
2743
- deleteLocalTaggedEntity
3403
+ deleteLocalTaggedEntity,
3404
+ useEntitySocket,
3405
+ useMutualSocket,
3406
+ useEphemeralSocket,
3407
+ useEntityFeed
2744
3408
  } = Monorise;
2745
3409
  var index_default = Monorise;
2746
3410
  export {
3411
+ WebSocketManager,
2747
3412
  adjustEntity,
2748
3413
  authService,
2749
3414
  axios,
@@ -2772,6 +3437,8 @@ export {
2772
3437
  getProfile,
2773
3438
  getTagRequestKey,
2774
3439
  getUniqueFieldRequestKey,
3440
+ getWebSocketManager,
3441
+ initializeWebSocketManager,
2775
3442
  listMoreEntities,
2776
3443
  logout,
2777
3444
  openModal,
@@ -2790,13 +3457,17 @@ export {
2790
3457
  useEntities,
2791
3458
  useEntity,
2792
3459
  useEntityByUniqueField,
3460
+ useEntityFeed,
3461
+ useEntitySocket,
2793
3462
  useEntityState,
3463
+ useEphemeralSocket,
2794
3464
  useErrorStore,
2795
3465
  useInterruptiveLoadStore,
2796
3466
  useIsUnauthorized,
2797
3467
  useLoadStore,
2798
3468
  useModalStore,
2799
3469
  useMutual,
3470
+ useMutualSocket,
2800
3471
  useMutuals,
2801
3472
  useProfile,
2802
3473
  useTaggedEntities