@monorise/react 5.0.0-dev.6 → 5.0.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,9 +1,34 @@
1
- import {
2
- WebSocketManager,
3
- __objRest,
4
- __spreadProps,
5
- __spreadValues
6
- } from "./chunk-BIXAYYE4.js";
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
+ };
7
32
 
8
33
  // actions/app.action.ts
9
34
  import { produce } from "immer";
@@ -289,13 +314,12 @@ var constructMutual = (byEntityType, byEntityId2, entityType, entityId, mutualDa
289
314
  mutualUpdatedAt: (/* @__PURE__ */ new Date()).toISOString()
290
315
  };
291
316
  };
292
- var flipMutual = (mutual, byEntityData) => {
317
+ var flipMutual = (mutual) => {
293
318
  return __spreadProps(__spreadValues({}, mutual), {
294
319
  entityId: mutual.byEntityId,
295
320
  entityType: mutual.byEntityType,
296
321
  byEntityId: mutual.entityId,
297
- byEntityType: mutual.entityType,
298
- data: byEntityData
322
+ byEntityType: mutual.entityType
299
323
  });
300
324
  };
301
325
  var byEntityId = (a, b) => {
@@ -726,61 +750,6 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
726
750
  return { error };
727
751
  }
728
752
  };
729
- const reconcileTaggedEntityStore = (state, entityType, id, data) => {
730
- var _a;
731
- const tagConfigs = (_a = state.config[entityType]) == null ? void 0 : _a.tags;
732
- if (!tagConfigs) return;
733
- for (const tagConfig of tagConfigs) {
734
- const { name, processor } = tagConfig;
735
- const processorResults = processor(data);
736
- for (const tagKey of Object.keys(state.tag)) {
737
- const [tagEntityType, tagName, ...paramParts] = tagKey.split("/");
738
- if (tagEntityType !== entityType || tagName !== name) {
739
- continue;
740
- }
741
- const slice = state.tag[tagKey];
742
- if (!(slice == null ? void 0 : slice.dataMap)) {
743
- continue;
744
- }
745
- const keyParams = {};
746
- for (const part of paramParts) {
747
- const colonIdx = part.indexOf(":");
748
- if (colonIdx > 0) {
749
- keyParams[part.substring(0, colonIdx)] = part.substring(
750
- colonIdx + 1
751
- );
752
- }
753
- }
754
- if (keyParams.query) {
755
- if (slice.dataMap.has(id)) {
756
- slice.dataMap.set(id, data);
757
- }
758
- continue;
759
- }
760
- const matches = processorResults.some(
761
- (result) => {
762
- if (keyParams.group && result.group !== keyParams.group) {
763
- return false;
764
- }
765
- if (keyParams.start && (!result.sortValue || result.sortValue < keyParams.start)) {
766
- return false;
767
- }
768
- if (keyParams.end && (!result.sortValue || result.sortValue > keyParams.end)) {
769
- return false;
770
- }
771
- return true;
772
- }
773
- );
774
- if (matches) {
775
- if (slice.isFirstFetched || slice.dataMap.has(id)) {
776
- slice.dataMap.set(id, data);
777
- }
778
- } else if (slice.dataMap.has(id)) {
779
- slice.dataMap.delete(id);
780
- }
781
- }
782
- }
783
- };
784
753
  const editEntity2 = async (entityType, id, entity, opts = {}) => {
785
754
  var _a;
786
755
  const entityService = makeEntityService(entityType);
@@ -789,6 +758,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
789
758
  const { data } = await entityService.editEntity(id, entity, opts);
790
759
  monoriseStore.setState(
791
760
  produce4((state) => {
761
+ var _a2, _b;
792
762
  state.entity[entityType].dataMap.set(data.entityId, data);
793
763
  for (const key of Object.keys(state.mutual)) {
794
764
  const [_byEntity, _byId, _entityType] = key.split("/");
@@ -811,12 +781,14 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
811
781
  state.mutual[key].dataMap = newDataMap;
812
782
  }
813
783
  }
814
- reconcileTaggedEntityStore(
815
- state,
816
- entityType,
817
- id,
818
- data
819
- );
784
+ for (const tagKey of Object.keys(state.tag)) {
785
+ const [tagEntityType] = tagKey.split("/");
786
+ if (tagEntityType === entityType) {
787
+ if ((_b = (_a2 = state.tag[tagKey]) == null ? void 0 : _a2.dataMap) == null ? void 0 : _b.has(id)) {
788
+ state.tag[tagKey].dataMap.set(id, data);
789
+ }
790
+ }
791
+ }
820
792
  }),
821
793
  void 0,
822
794
  `mr/entity/edit/${entityType}/${id}`
@@ -836,6 +808,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
836
808
  const { data } = await entityService.adjustEntity(id, adjustments, opts);
837
809
  monoriseStore.setState(
838
810
  produce4((state) => {
811
+ var _a2, _b2;
839
812
  state.entity[entityType].dataMap.set(data.entityId, data);
840
813
  for (const key of Object.keys(state.mutual)) {
841
814
  const [_byEntity, _byId, _entityType] = key.split("/");
@@ -858,12 +831,14 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
858
831
  state.mutual[key].dataMap = newDataMap;
859
832
  }
860
833
  }
861
- reconcileTaggedEntityStore(
862
- state,
863
- entityType,
864
- id,
865
- data
866
- );
834
+ for (const tagKey of Object.keys(state.tag)) {
835
+ const [tagEntityType] = tagKey.split("/");
836
+ if (tagEntityType === entityType) {
837
+ if ((_b2 = (_a2 = state.tag[tagKey]) == null ? void 0 : _a2.dataMap) == null ? void 0 : _b2.has(id)) {
838
+ state.tag[tagKey].dataMap.set(id, data);
839
+ }
840
+ }
841
+ }
867
842
  }),
868
843
  void 0,
869
844
  `mr/entity/adjust/${entityType}/${id}`
@@ -1087,7 +1062,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1087
1062
  );
1088
1063
  monoriseStore.setState(
1089
1064
  produce4((state) => {
1090
- var _a2, _b, _c, _d, _e;
1065
+ var _a2, _b;
1091
1066
  const bySide = getMutualStateKey(
1092
1067
  byEntityType,
1093
1068
  byEntityId2,
@@ -1107,10 +1082,9 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1107
1082
  dataMap: /* @__PURE__ */ new Map()
1108
1083
  };
1109
1084
  }
1110
- const byEntityData = (_d = (_c = (_b = state.entity[mutual.byEntityType]) == null ? void 0 : _b.dataMap.get(mutual.byEntityId)) == null ? void 0 : _c.data) != null ? _d : {};
1111
- state.mutual[side].dataMap = new Map((_e = state.mutual[side]) == null ? void 0 : _e.dataMap).set(
1085
+ state.mutual[side].dataMap = new Map((_b = state.mutual[side]) == null ? void 0 : _b.dataMap).set(
1112
1086
  mutual.byEntityId,
1113
- flipMutual(mutual, byEntityData)
1087
+ flipMutual(mutual)
1114
1088
  );
1115
1089
  }),
1116
1090
  void 0,
@@ -1134,7 +1108,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1134
1108
  );
1135
1109
  monoriseStore.setState(
1136
1110
  produce4((state) => {
1137
- var _a, _b, _c, _d, _e;
1111
+ var _a, _b;
1138
1112
  const bySide = getMutualStateKey(byEntityType, byEntityId2, entityType);
1139
1113
  const side = getMutualStateKey(entityType, entityId, byEntityType);
1140
1114
  if (!state.mutual[bySide]) {
@@ -1150,10 +1124,9 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1150
1124
  dataMap: /* @__PURE__ */ new Map()
1151
1125
  };
1152
1126
  }
1153
- const byEntityData = (_d = (_c = (_b = state.entity[mutual.byEntityType]) == null ? void 0 : _b.dataMap.get(mutual.byEntityId)) == null ? void 0 : _c.data) != null ? _d : {};
1154
- state.mutual[side].dataMap = new Map((_e = state.mutual[side]) == null ? void 0 : _e.dataMap).set(
1127
+ state.mutual[side].dataMap = new Map((_b = state.mutual[side]) == null ? void 0 : _b.dataMap).set(
1155
1128
  mutual.byEntityId,
1156
- flipMutual(mutual, byEntityData)
1129
+ flipMutual(mutual)
1157
1130
  );
1158
1131
  }),
1159
1132
  void 0,
@@ -1181,7 +1154,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1181
1154
  );
1182
1155
  monoriseStore.setState(
1183
1156
  produce4((state) => {
1184
- var _a, _b, _c, _d, _e;
1157
+ var _a, _b;
1185
1158
  const bySide = getMutualStateKey(byEntityType, byEntityId2, entityType);
1186
1159
  const side = getMutualStateKey(entityType, entityId, byEntityType);
1187
1160
  if (!state.mutual[bySide]) {
@@ -1197,10 +1170,9 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1197
1170
  dataMap: /* @__PURE__ */ new Map()
1198
1171
  };
1199
1172
  }
1200
- const byEntityData = (_d = (_c = (_b = state.entity[mutual.byEntityType]) == null ? void 0 : _b.dataMap.get(mutual.byEntityId)) == null ? void 0 : _c.data) != null ? _d : {};
1201
- state.mutual[side].dataMap = new Map((_e = state.mutual[side]) == null ? void 0 : _e.dataMap).set(
1173
+ state.mutual[side].dataMap = new Map((_b = state.mutual[side]) == null ? void 0 : _b.dataMap).set(
1202
1174
  byEntityId2,
1203
- flipMutual(mutual, byEntityData)
1175
+ flipMutual(mutual)
1204
1176
  );
1205
1177
  }),
1206
1178
  void 0,
@@ -1220,7 +1192,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1220
1192
  );
1221
1193
  monoriseStore.setState(
1222
1194
  produce4((state) => {
1223
- var _a2, _b, _c, _d, _e;
1195
+ var _a2, _b;
1224
1196
  const bySide = getMutualStateKey(
1225
1197
  byEntityType,
1226
1198
  byEntityId2,
@@ -1240,10 +1212,9 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1240
1212
  dataMap: /* @__PURE__ */ new Map()
1241
1213
  };
1242
1214
  }
1243
- const byEntityData = (_d = (_c = (_b = state.entity[mutual.byEntityType]) == null ? void 0 : _b.dataMap.get(mutual.byEntityId)) == null ? void 0 : _c.data) != null ? _d : {};
1244
- state.mutual[side].dataMap = new Map((_e = state.mutual[side]) == null ? void 0 : _e.dataMap).set(
1215
+ state.mutual[side].dataMap = new Map((_b = state.mutual[side]) == null ? void 0 : _b.dataMap).set(
1245
1216
  mutual.byEntityId,
1246
- flipMutual(mutual, byEntityData)
1217
+ flipMutual(mutual)
1247
1218
  );
1248
1219
  }),
1249
1220
  void 0,
@@ -1484,16 +1455,11 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1484
1455
  return () => queryTimeout && clearTimeout(queryTimeout);
1485
1456
  }, [entityType, query]);
1486
1457
  useEffect2(() => {
1487
- if (!query) {
1488
- const dataMapArray = Array.from(dataMap.values()).sort(
1489
- byEntityId
1458
+ if (!query && dataMap.size !== (entities == null ? void 0 : entities.length)) {
1459
+ setIsSearching(false);
1460
+ setEntities(
1461
+ Array.from(dataMap.values()).sort(byEntityId)
1490
1462
  );
1491
- if (dataMap.size !== (entities == null ? void 0 : entities.length) || dataMapArray.some(
1492
- (item, index) => JSON.stringify(item) !== JSON.stringify(entities == null ? void 0 : entities[index])
1493
- )) {
1494
- setIsSearching(false);
1495
- setEntities(dataMapArray);
1496
- }
1497
1463
  }
1498
1464
  if (query) {
1499
1465
  setEntities(searchResults);
@@ -1501,7 +1467,6 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1501
1467
  }, [
1502
1468
  dataMap,
1503
1469
  dataMap.size,
1504
- entities,
1505
1470
  entities == null ? void 0 : entities.length,
1506
1471
  query,
1507
1472
  searchResults,
@@ -1664,20 +1629,6 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1664
1629
  }
1665
1630
  });
1666
1631
  };
1667
- const sortTaggedEntitiesLikeServer = (arr, entityType, tagName, group) => {
1668
- var _a, _b;
1669
- const tagConfig = (_b = (_a = monoriseStore.getState().config[entityType]) == null ? void 0 : _a.tags) == null ? void 0 : _b.find((t) => t.name === tagName);
1670
- const keyOf = (entity) => {
1671
- let sortValue;
1672
- if (tagConfig == null ? void 0 : tagConfig.processor) {
1673
- const results = tagConfig.processor(entity);
1674
- const match = group ? results.find((r) => r.group === group) : results[0];
1675
- sortValue = match == null ? void 0 : match.sortValue;
1676
- }
1677
- return `${sortValue ? `${sortValue}#` : ""}${entityType}#${entity.entityId}`;
1678
- };
1679
- return arr.map((entity) => ({ entity, key: keyOf(entity) })).sort((a, b) => a.key === b.key ? 0 : a.key < b.key ? 1 : -1).map((x) => x.entity);
1680
- };
1681
1632
  const useTaggedEntities2 = (entityType, tagName, opts = {}) => {
1682
1633
  const { params } = opts || {};
1683
1634
  const stateKey = getTagStateKey(entityType, tagName, params);
@@ -1695,12 +1646,7 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1695
1646
  }
1696
1647
  }, [entityType, opts, tagName, params, opts == null ? void 0 : opts.forceFetch]);
1697
1648
  useEffect2(() => {
1698
- const dataMapArray = sortTaggedEntitiesLikeServer(
1699
- Array.from(dataMap.values()),
1700
- entityType,
1701
- tagName,
1702
- params == null ? void 0 : params.group
1703
- );
1649
+ const dataMapArray = Array.from(dataMap.values());
1704
1650
  if (dataMap.size !== (entities == null ? void 0 : entities.length) || dataMapArray.some(
1705
1651
  (item, index) => JSON.stringify(item) !== JSON.stringify(entities[index])
1706
1652
  )) {
@@ -1800,539 +1746,6 @@ var initCoreActions = (monoriseStore, appActions, coreService2) => {
1800
1746
  };
1801
1747
  };
1802
1748
 
1803
- // actions/websocket.action.ts
1804
- import { useCallback, useEffect as useEffect3, useRef, useState as useState3 } from "react";
1805
- import { produce as produce5 } from "immer";
1806
- var globalWsManager = null;
1807
- var wsEndpoint;
1808
- var initializeWebSocketManager = (WebSocketManagerClass, endpoint, token) => {
1809
- if (globalWsManager) return globalWsManager;
1810
- wsEndpoint = endpoint;
1811
- globalWsManager = new WebSocketManagerClass(endpoint, token || "");
1812
- globalWsManager.connect();
1813
- return globalWsManager;
1814
- };
1815
- var getWebSocketManager = () => globalWsManager;
1816
- var initWebSocketActions = (monoriseStore, httpActions) => {
1817
- const useEntitySocket2 = (entityType, opts = {}) => {
1818
- const { limit = 20, skipInitialFetch = false } = opts;
1819
- const [isLoading, setIsLoading] = useState3(!skipInitialFetch);
1820
- const [isFetchingMore, setIsFetchingMore] = useState3(false);
1821
- const [isRefreshing, setIsRefreshing] = useState3(false);
1822
- const [isSubscribed, setIsSubscribed] = useState3(false);
1823
- const [error, setError2] = useState3(null);
1824
- const [hasMore, setHasMore] = useState3(true);
1825
- const lastKeyRef = useRef(void 0);
1826
- const isFirstFetchRef = useRef(true);
1827
- const entities = monoriseStore((state) => {
1828
- var _a;
1829
- const entityState = state.entity[entityType];
1830
- return Array.from(((_a = entityState == null ? void 0 : entityState.dataMap) == null ? void 0 : _a.values()) || []);
1831
- });
1832
- const fetchData = async (type) => {
1833
- if (!httpActions) return;
1834
- if (type === "more") {
1835
- setIsFetchingMore(true);
1836
- } else if (type === "refresh") {
1837
- setIsRefreshing(true);
1838
- } else {
1839
- setIsLoading(true);
1840
- }
1841
- setError2(null);
1842
- try {
1843
- const fetchLastKey = type === "refresh" ? void 0 : lastKeyRef.current;
1844
- const result = await httpActions.listEntities(entityType, {
1845
- limit,
1846
- lastKey: fetchLastKey
1847
- });
1848
- monoriseStore.setState(
1849
- produce5((state) => {
1850
- if (type === "refresh") {
1851
- state.entity[entityType].dataMap.clear();
1852
- }
1853
- for (const entity of result.data) {
1854
- state.entity[entityType].dataMap.set(entity.entityId, entity);
1855
- }
1856
- state.entity[entityType].isFirstFetched = true;
1857
- state.entity[entityType].lastKey = result.lastKey;
1858
- })
1859
- );
1860
- lastKeyRef.current = result.lastKey;
1861
- setHasMore(!!result.lastKey);
1862
- } catch (err) {
1863
- setError2(err instanceof Error ? err : new Error("Failed to fetch"));
1864
- } finally {
1865
- setIsLoading(false);
1866
- setIsFetchingMore(false);
1867
- setIsRefreshing(false);
1868
- }
1869
- };
1870
- useEffect3(() => {
1871
- if (skipInitialFetch) return;
1872
- fetchData("initial");
1873
- }, [entityType, limit, skipInitialFetch]);
1874
- useEffect3(() => {
1875
- if (!globalWsManager) {
1876
- setIsSubscribed(false);
1877
- return;
1878
- }
1879
- const subKey = globalWsManager.subscribeEntityType(entityType);
1880
- setIsSubscribed(true);
1881
- let wasConnected = false;
1882
- const unsubscribeState = globalWsManager.onStateChange((state) => {
1883
- if (state === "connected" && wasConnected === false && !isFirstFetchRef.current) {
1884
- fetchData("refresh");
1885
- }
1886
- wasConnected = state === "connected";
1887
- isFirstFetchRef.current = false;
1888
- });
1889
- const unsubscribeMessage = globalWsManager.onMessage(
1890
- (msg) => {
1891
- if (msg.type === "entity.created" || msg.type === "entity.updated" || msg.type === "entity.deleted") {
1892
- const payload = msg.payload;
1893
- if (payload.entityType !== entityType) return;
1894
- if (msg.type === "entity.created" || msg.type === "entity.updated") {
1895
- if (payload.data) {
1896
- monoriseStore.setState(
1897
- produce5((state) => {
1898
- const key = entityType;
1899
- if (!state.entity[key]) {
1900
- state.entity[key] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
1901
- }
1902
- state.entity[key].dataMap.set(
1903
- payload.entityId,
1904
- payload.data
1905
- );
1906
- })
1907
- );
1908
- }
1909
- } else if (msg.type === "entity.deleted") {
1910
- monoriseStore.setState(
1911
- produce5((state) => {
1912
- var _a;
1913
- const key = entityType;
1914
- if ((_a = state.entity[key]) == null ? void 0 : _a.dataMap) {
1915
- state.entity[key].dataMap.delete(payload.entityId);
1916
- }
1917
- })
1918
- );
1919
- }
1920
- }
1921
- }
1922
- );
1923
- return () => {
1924
- globalWsManager == null ? void 0 : globalWsManager.unsubscribeEntityType(subKey);
1925
- unsubscribeState();
1926
- unsubscribeMessage();
1927
- setIsSubscribed(false);
1928
- };
1929
- }, [entityType]);
1930
- const fetchMore = async () => {
1931
- if (!hasMore || isFetchingMore) return;
1932
- await fetchData("more");
1933
- };
1934
- return {
1935
- entities,
1936
- isLoading,
1937
- isFetchingMore,
1938
- isSubscribed,
1939
- error,
1940
- isRefreshing,
1941
- fetchMore,
1942
- hasMore
1943
- };
1944
- };
1945
- const useMutualSocket2 = (byEntityType, byEntityId2, mutualEntityType, opts = {}) => {
1946
- const { limit = 20, skipInitialFetch = false } = opts;
1947
- const [isLoading, setIsLoading] = useState3(
1948
- !skipInitialFetch && !!byEntityId2
1949
- );
1950
- const [isFetchingMore, setIsFetchingMore] = useState3(false);
1951
- const [isRefreshing, setIsRefreshing] = useState3(false);
1952
- const [isSubscribed, setIsSubscribed] = useState3(false);
1953
- const [error, setError2] = useState3(null);
1954
- const [hasMore, setHasMore] = useState3(true);
1955
- const lastKeyRef = useRef(void 0);
1956
- const isFirstFetchRef = useRef(true);
1957
- const mutualKey = byEntityId2 ? `${byEntityType}/${byEntityId2}/${mutualEntityType}` : "";
1958
- const mutuals = monoriseStore((state) => {
1959
- var _a, _b;
1960
- return Array.from(((_b = (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.values()) || []);
1961
- });
1962
- const fetchData = async (type) => {
1963
- if (!byEntityId2 || !httpActions) return;
1964
- if (type === "more") {
1965
- setIsFetchingMore(true);
1966
- } else if (type === "refresh") {
1967
- setIsRefreshing(true);
1968
- } else {
1969
- setIsLoading(true);
1970
- }
1971
- setError2(null);
1972
- try {
1973
- const fetchLastKey = type === "refresh" ? void 0 : lastKeyRef.current;
1974
- const result = await httpActions.listEntitiesByEntity(
1975
- byEntityType,
1976
- byEntityId2,
1977
- mutualEntityType,
1978
- { limit, lastKey: fetchLastKey }
1979
- );
1980
- monoriseStore.setState(
1981
- produce5((state) => {
1982
- if (!state.mutual[mutualKey]) {
1983
- state.mutual[mutualKey] = {
1984
- dataMap: /* @__PURE__ */ new Map(),
1985
- isFirstFetched: true,
1986
- lastKey: void 0
1987
- };
1988
- }
1989
- if (type === "refresh") {
1990
- state.mutual[mutualKey].dataMap.clear();
1991
- }
1992
- for (const entity of result.entities) {
1993
- const e = entity;
1994
- state.mutual[mutualKey].dataMap.set(e.entityId, entity);
1995
- }
1996
- state.mutual[mutualKey].lastKey = result.lastKey;
1997
- })
1998
- );
1999
- lastKeyRef.current = result.lastKey;
2000
- setHasMore(!!result.lastKey);
2001
- } catch (err) {
2002
- setError2(err instanceof Error ? err : new Error("Failed to fetch"));
2003
- } finally {
2004
- setIsLoading(false);
2005
- setIsFetchingMore(false);
2006
- setIsRefreshing(false);
2007
- }
2008
- };
2009
- useEffect3(() => {
2010
- if (skipInitialFetch || !byEntityId2) {
2011
- setIsLoading(false);
2012
- return;
2013
- }
2014
- lastKeyRef.current = void 0;
2015
- setHasMore(true);
2016
- isFirstFetchRef.current = true;
2017
- fetchData("initial");
2018
- }, [byEntityType, byEntityId2, mutualEntityType, limit, skipInitialFetch]);
2019
- useEffect3(() => {
2020
- if (!globalWsManager || !byEntityId2) {
2021
- setIsSubscribed(false);
2022
- return;
2023
- }
2024
- const subKey = globalWsManager.subscribeMutualType(
2025
- byEntityType,
2026
- byEntityId2,
2027
- mutualEntityType
2028
- );
2029
- setIsSubscribed(true);
2030
- let wasConnected = false;
2031
- const unsubscribeState = globalWsManager.onStateChange((state) => {
2032
- if (state === "connected" && wasConnected === false && !isFirstFetchRef.current) {
2033
- fetchData("refresh");
2034
- }
2035
- wasConnected = state === "connected";
2036
- isFirstFetchRef.current = false;
2037
- });
2038
- const unsubscribeMessage = globalWsManager.onMessage(
2039
- (msg) => {
2040
- if (msg.type === "mutual.created" || msg.type === "mutual.updated" || msg.type === "mutual.deleted") {
2041
- const payload = msg.payload;
2042
- if (payload.byEntityType !== byEntityType || payload.byEntityId !== byEntityId2 || payload.mutualEntityType !== mutualEntityType) {
2043
- return;
2044
- }
2045
- if (msg.type === "mutual.created" || msg.type === "mutual.updated") {
2046
- if (payload.data) {
2047
- monoriseStore.setState(
2048
- produce5((state) => {
2049
- if (!state.mutual[mutualKey]) {
2050
- state.mutual[mutualKey] = {
2051
- dataMap: /* @__PURE__ */ new Map(),
2052
- isFirstFetched: true,
2053
- lastKey: void 0
2054
- };
2055
- }
2056
- state.mutual[mutualKey].dataMap.set(
2057
- payload.entityId,
2058
- payload.data
2059
- );
2060
- })
2061
- );
2062
- }
2063
- } else if (msg.type === "mutual.deleted") {
2064
- monoriseStore.setState(
2065
- produce5((state) => {
2066
- var _a;
2067
- (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap.delete(payload.entityId);
2068
- })
2069
- );
2070
- }
2071
- }
2072
- }
2073
- );
2074
- return () => {
2075
- globalWsManager == null ? void 0 : globalWsManager.unsubscribeMutualType(subKey);
2076
- unsubscribeState();
2077
- unsubscribeMessage();
2078
- setIsSubscribed(false);
2079
- };
2080
- }, [byEntityType, byEntityId2, mutualEntityType, mutualKey]);
2081
- const fetchMore = async () => {
2082
- if (!hasMore || isFetchingMore) return;
2083
- await fetchData("more");
2084
- };
2085
- return {
2086
- mutuals,
2087
- isLoading,
2088
- isFetchingMore,
2089
- isSubscribed,
2090
- error,
2091
- isRefreshing,
2092
- fetchMore,
2093
- hasMore
2094
- };
2095
- };
2096
- const useEphemeralSocket2 = (channel, opts) => {
2097
- const [isSubscribed, setIsSubscribed] = useState3(false);
2098
- useEffect3(() => {
2099
- if (!globalWsManager || !channel) {
2100
- setIsSubscribed(false);
2101
- return;
2102
- }
2103
- const subKey = globalWsManager.subscribeEphemeral(channel);
2104
- setIsSubscribed(true);
2105
- const unsubscribeMessage = globalWsManager.onMessage(
2106
- (msg) => {
2107
- var _a;
2108
- if (msg.type === "ephemeral") {
2109
- const payload = msg.payload;
2110
- if (payload.channel !== channel) return;
2111
- (_a = opts == null ? void 0 : opts.onMessage) == null ? void 0 : _a.call(opts, payload.data, payload.senderId);
2112
- }
2113
- }
2114
- );
2115
- return () => {
2116
- globalWsManager == null ? void 0 : globalWsManager.unsubscribeEphemeral(subKey);
2117
- unsubscribeMessage();
2118
- setIsSubscribed(false);
2119
- };
2120
- }, [channel]);
2121
- const send = useCallback(
2122
- (data) => {
2123
- if (!globalWsManager || !channel) return;
2124
- globalWsManager.sendEphemeral(channel, data);
2125
- },
2126
- [channel]
2127
- );
2128
- return { isSubscribed, send };
2129
- };
2130
- const useEntityFeed2 = (opts) => {
2131
- const { entityType, entityId, ticketEndpoint } = opts;
2132
- const [isConnected, setIsConnected] = useState3(false);
2133
- const [error, setError2] = useState3(null);
2134
- const refreshTimerRef = useRef(null);
2135
- const wsManagerRef = useRef(null);
2136
- const isMountedRef = useRef(true);
2137
- const connectingRef = useRef(false);
2138
- const reconnectCountRef = useRef(0);
2139
- const connectRef = useRef(() => {
2140
- });
2141
- const lastConnectedAtRef = useRef(0);
2142
- const fetchTicket = useCallback(async () => {
2143
- try {
2144
- const url = ticketEndpoint || `/api/core/ws/ticket/${entityType}/${entityId}`;
2145
- const fetchOpts = {
2146
- method: "POST",
2147
- headers: { "Content-Type": "application/json" }
2148
- };
2149
- if (ticketEndpoint) {
2150
- fetchOpts.body = JSON.stringify({ entityType, entityId });
2151
- }
2152
- const response = await fetch(url, fetchOpts);
2153
- if (response.status === 401 || response.status === 403) {
2154
- return { error: { code: "TICKET_UNAUTHORIZED", message: "Unauthorized" } };
2155
- }
2156
- if (!response.ok) {
2157
- return { error: { code: "TICKET_FAILED", message: `HTTP ${response.status}` } };
2158
- }
2159
- const data = await response.json();
2160
- return { data };
2161
- } catch (err) {
2162
- return { error: { code: "TICKET_FAILED", message: err.message } };
2163
- }
2164
- }, [entityType, entityId, ticketEndpoint]);
2165
- const connectWithTicket = useCallback(async () => {
2166
- if (connectingRef.current) return;
2167
- connectingRef.current = true;
2168
- let result = null;
2169
- const maxRetries = 3;
2170
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
2171
- result = await fetchTicket();
2172
- if (!isMountedRef.current) {
2173
- connectingRef.current = false;
2174
- return;
2175
- }
2176
- if (!result.error) break;
2177
- if (result.error.code === "TICKET_UNAUTHORIZED") break;
2178
- if (attempt < maxRetries) {
2179
- await new Promise((r) => setTimeout(r, 1e3 * Math.pow(2, attempt)));
2180
- if (!isMountedRef.current) {
2181
- connectingRef.current = false;
2182
- return;
2183
- }
2184
- }
2185
- }
2186
- if (result.error) {
2187
- setError2(result.error);
2188
- setIsConnected(false);
2189
- connectingRef.current = false;
2190
- return;
2191
- }
2192
- setError2(null);
2193
- const { ticket, wsUrl, expiresIn } = result.data;
2194
- if (wsManagerRef.current) {
2195
- wsManagerRef.current.disconnect();
2196
- }
2197
- const { WebSocketManager: WsManagerClass } = await import("./websocket-7MZ3ENOC.js");
2198
- const wsUrlWithTicket = `${wsUrl}?ticket=${encodeURIComponent(ticket)}`;
2199
- const manager = new WsManagerClass(wsUrlWithTicket, "");
2200
- manager.disableAutoReconnect = true;
2201
- wsManagerRef.current = manager;
2202
- globalWsManager = manager;
2203
- manager.onStateChange((state) => {
2204
- if (!isMountedRef.current) return;
2205
- if (wsManagerRef.current !== manager) return;
2206
- if (state === "connected") {
2207
- connectingRef.current = false;
2208
- reconnectCountRef.current = 0;
2209
- lastConnectedAtRef.current = Date.now();
2210
- setIsConnected(true);
2211
- setError2(null);
2212
- } else if (state === "disconnected") {
2213
- connectingRef.current = false;
2214
- setIsConnected(false);
2215
- const wasStable = Date.now() - lastConnectedAtRef.current > 5e3;
2216
- if (wasStable && reconnectCountRef.current < 5) {
2217
- reconnectCountRef.current++;
2218
- const delay = 2e3 * Math.pow(2, reconnectCountRef.current - 1);
2219
- setTimeout(() => {
2220
- if (isMountedRef.current && !connectingRef.current) {
2221
- connectRef.current();
2222
- }
2223
- }, delay);
2224
- }
2225
- }
2226
- });
2227
- manager.onMessage((msg) => {
2228
- if (!isMountedRef.current) return;
2229
- if (msg.type === "entity.created" || msg.type === "entity.updated") {
2230
- const payload = msg.payload;
2231
- if (payload.data) {
2232
- monoriseStore.setState(
2233
- produce5((state) => {
2234
- const key = payload.entityType;
2235
- if (!state.entity[key]) {
2236
- state.entity[key] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
2237
- }
2238
- state.entity[key].dataMap.set(payload.entityId, payload.data);
2239
- })
2240
- );
2241
- }
2242
- } else if (msg.type === "entity.deleted") {
2243
- const payload = msg.payload;
2244
- monoriseStore.setState(
2245
- produce5((state) => {
2246
- var _a, _b;
2247
- (_b = (_a = state.entity[payload.entityType]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.delete(payload.entityId);
2248
- })
2249
- );
2250
- } else if (msg.type === "mutual.created" || msg.type === "mutual.updated") {
2251
- const payload = msg.payload;
2252
- if (payload.data) {
2253
- const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;
2254
- monoriseStore.setState(
2255
- produce5((state) => {
2256
- if (!state.mutual[mutualKey]) {
2257
- state.mutual[mutualKey] = { dataMap: /* @__PURE__ */ new Map(), isFirstFetched: false, lastKey: void 0 };
2258
- }
2259
- state.mutual[mutualKey].dataMap.set(payload.entityId, payload.data);
2260
- })
2261
- );
2262
- }
2263
- } else if (msg.type === "mutual.deleted") {
2264
- const payload = msg.payload;
2265
- const mutualKey = `${payload.byEntityType}/${payload.byEntityId}/${payload.mutualEntityType}`;
2266
- monoriseStore.setState(
2267
- produce5((state) => {
2268
- var _a, _b;
2269
- (_b = (_a = state.mutual[mutualKey]) == null ? void 0 : _a.dataMap) == null ? void 0 : _b.delete(payload.entityId);
2270
- })
2271
- );
2272
- }
2273
- });
2274
- manager.connect();
2275
- if (refreshTimerRef.current) {
2276
- clearTimeout(refreshTimerRef.current);
2277
- }
2278
- const refreshMs = Math.max((expiresIn - 120) * 1e3, 6e4);
2279
- refreshTimerRef.current = setTimeout(() => {
2280
- if (isMountedRef.current) {
2281
- connectRef.current();
2282
- }
2283
- }, refreshMs);
2284
- }, [fetchTicket]);
2285
- connectRef.current = connectWithTicket;
2286
- useEffect3(() => {
2287
- isMountedRef.current = true;
2288
- if (entityId) {
2289
- connectRef.current();
2290
- }
2291
- let lastCheckTime = Date.now();
2292
- const sleepCheckInterval = setInterval(() => {
2293
- const now = Date.now();
2294
- const elapsed = now - lastCheckTime;
2295
- lastCheckTime = now;
2296
- if (elapsed > 3e4 && wsManagerRef.current) {
2297
- wsManagerRef.current.disconnect();
2298
- wsManagerRef.current = null;
2299
- connectingRef.current = false;
2300
- reconnectCountRef.current = 0;
2301
- connectRef.current();
2302
- }
2303
- }, 5e3);
2304
- const handleOnline = () => {
2305
- var _a;
2306
- if (!isMountedRef.current) return;
2307
- if (((_a = wsManagerRef.current) == null ? void 0 : _a.getState()) === "connected") return;
2308
- if (connectingRef.current) return;
2309
- reconnectCountRef.current = 0;
2310
- connectRef.current();
2311
- };
2312
- window.addEventListener("online", handleOnline);
2313
- return () => {
2314
- isMountedRef.current = false;
2315
- clearInterval(sleepCheckInterval);
2316
- window.removeEventListener("online", handleOnline);
2317
- if (refreshTimerRef.current) {
2318
- clearTimeout(refreshTimerRef.current);
2319
- }
2320
- if (wsManagerRef.current) {
2321
- wsManagerRef.current.disconnect();
2322
- wsManagerRef.current = null;
2323
- }
2324
- };
2325
- }, [entityType, entityId]);
2326
- return { isConnected, error };
2327
- };
2328
- return {
2329
- useEntitySocket: useEntitySocket2,
2330
- useMutualSocket: useMutualSocket2,
2331
- useEphemeralSocket: useEphemeralSocket2,
2332
- useEntityFeed: useEntityFeed2
2333
- };
2334
- };
2335
-
2336
1749
  // lib/api.ts
2337
1750
  import request from "axios";
2338
1751
  var initAxiosInterceptor = (store2, appActions) => {
@@ -2451,7 +1864,6 @@ var auth_service_default = initAuthService;
2451
1864
  var ENTITY_API_BASE_URL = "/api/core/entity";
2452
1865
  var MUTUAL_API_BASE_URL = "/api/core/mutual";
2453
1866
  var TAG_API_BASE_URL = "/api/core/tag";
2454
- var TRANSACTION_API_BASE_URL = "/api/core/transaction";
2455
1867
  var initCoreService = (monoriseStore, axios2, opts) => {
2456
1868
  let options = opts || {};
2457
1869
  const listEntities = (entityType, payload, opts2 = {}) => {
@@ -2568,10 +1980,9 @@ var initCoreService = (monoriseStore, axios2, opts) => {
2568
1980
  var _a;
2569
1981
  const { entityApiBaseUrl = ENTITY_API_BASE_URL } = options;
2570
1982
  const entityConfig = monoriseStore.getState().config;
2571
- const body = opts2.condition ? __spreadProps(__spreadValues({}, adjustments), { $condition: opts2.condition }) : adjustments;
2572
1983
  return axios2.post(
2573
1984
  opts2.customUrl || `${entityApiBaseUrl}/${entityType}/${id}/adjust`,
2574
- body,
1985
+ adjustments,
2575
1986
  {
2576
1987
  requestKey: getEntityRequestKey("adjust", entityType, id),
2577
1988
  isInterruptive: (_a = opts2.isInterruptive) != null ? _a : true,
@@ -2598,22 +2009,6 @@ var initCoreService = (monoriseStore, axios2, opts) => {
2598
2009
  }
2599
2010
  );
2600
2011
  };
2601
- const transaction = (operations, opts2 = {}) => {
2602
- var _a;
2603
- const { transactionApiBaseUrl = TRANSACTION_API_BASE_URL } = options;
2604
- return axios2.post(
2605
- opts2.customUrl || transactionApiBaseUrl,
2606
- { operations },
2607
- {
2608
- requestKey: "transaction",
2609
- isInterruptive: (_a = opts2.isInterruptive) != null ? _a : true,
2610
- feedback: __spreadValues({
2611
- loading: "Processing transaction",
2612
- success: "Transaction completed"
2613
- }, opts2.feedback || {})
2614
- }
2615
- );
2616
- };
2617
2012
  const listEntitiesByEntity = (byEntityType, entityType, byEntityId2, opts2 = {}, chainEntityQuery) => {
2618
2013
  const { mutualApiBaseUrl = MUTUAL_API_BASE_URL } = options;
2619
2014
  return axios2.get(
@@ -2757,7 +2152,6 @@ var initCoreService = (monoriseStore, axios2, opts) => {
2757
2152
  return {
2758
2153
  makeEntityService,
2759
2154
  makeMutualService,
2760
- transaction,
2761
2155
  setOptions
2762
2156
  };
2763
2157
  };
@@ -2988,7 +2382,6 @@ var initMonoriseStore = () => {
2988
2382
  };
2989
2383
 
2990
2384
  // index.ts
2991
- import { transactional } from "@monorise/base";
2992
2385
  var initMonorise = () => {
2993
2386
  const { monoriseStore: store2, setOptions: setMonoriseOptions } = initMonoriseStore();
2994
2387
  const appActions = initAppActions(store2);
@@ -2999,7 +2392,6 @@ var initMonorise = () => {
2999
2392
  const coreService2 = core_service_default(store2, axios2);
3000
2393
  const authActions = initAuthActions(store2, authService2);
3001
2394
  const coreActions = initCoreActions(store2, appActions, coreService2);
3002
- const websocketActions = initWebSocketActions(store2);
3003
2395
  const axiosInterceptor = injectAxiosInterceptor(
3004
2396
  appActions,
3005
2397
  authActions,
@@ -3025,14 +2417,14 @@ var initMonorise = () => {
3025
2417
  onApiSuccess: opts.onApiSuccess
3026
2418
  });
3027
2419
  };
3028
- return __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
2420
+ return __spreadValues(__spreadValues(__spreadValues(__spreadValues({
3029
2421
  config,
3030
2422
  store: store2,
3031
2423
  axios: axios2,
3032
2424
  authService: authService2,
3033
2425
  filestoreService: filestoreService2,
3034
2426
  coreService: coreService2
3035
- }, configActions), appActions), authActions), coreActions), websocketActions);
2427
+ }, configActions), appActions), authActions), coreActions);
3036
2428
  };
3037
2429
  var Monorise = initMonorise();
3038
2430
  var {
@@ -3084,15 +2476,10 @@ var {
3084
2476
  useEntityState,
3085
2477
  getEntity,
3086
2478
  updateLocalTaggedEntity,
3087
- deleteLocalTaggedEntity,
3088
- useEntitySocket,
3089
- useMutualSocket,
3090
- useEphemeralSocket,
3091
- useEntityFeed
2479
+ deleteLocalTaggedEntity
3092
2480
  } = Monorise;
3093
2481
  var index_default = Monorise;
3094
2482
  export {
3095
- WebSocketManager,
3096
2483
  adjustEntity,
3097
2484
  authService,
3098
2485
  axios,
@@ -3120,8 +2507,6 @@ export {
3120
2507
  getProfile,
3121
2508
  getTagRequestKey,
3122
2509
  getUniqueFieldRequestKey,
3123
- getWebSocketManager,
3124
- initializeWebSocketManager,
3125
2510
  listMoreEntities,
3126
2511
  logout,
3127
2512
  openModal,
@@ -3131,7 +2516,6 @@ export {
3131
2516
  setIsUnauthorized,
3132
2517
  startLoading,
3133
2518
  store,
3134
- transactional,
3135
2519
  updateLocalEntity,
3136
2520
  updateLocalTaggedEntity,
3137
2521
  upsertEntity,
@@ -3140,17 +2524,13 @@ export {
3140
2524
  useEntities,
3141
2525
  useEntity,
3142
2526
  useEntityByUniqueField,
3143
- useEntityFeed,
3144
- useEntitySocket,
3145
2527
  useEntityState,
3146
- useEphemeralSocket,
3147
2528
  useErrorStore,
3148
2529
  useInterruptiveLoadStore,
3149
2530
  useIsUnauthorized,
3150
2531
  useLoadStore,
3151
2532
  useModalStore,
3152
2533
  useMutual,
3153
- useMutualSocket,
3154
2534
  useMutuals,
3155
2535
  useProfile,
3156
2536
  useTaggedEntities