akeyless-client-commons 1.1.21 → 1.1.23

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.
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ function _array_like_to_array(arr, len) {
3
+ if (len == null || len > arr.length) len = arr.length;
4
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
+ return arr2;
6
+ }
7
+ function _array_with_holes(arr) {
8
+ if (Array.isArray(arr)) return arr;
9
+ }
10
+ function _array_without_holes(arr) {
11
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
12
+ }
2
13
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
3
14
  try {
4
15
  var info = gen[key](arg);
@@ -28,6 +39,25 @@ function _async_to_generator(fn) {
28
39
  });
29
40
  };
30
41
  }
42
+ function _class_call_check(instance, Constructor) {
43
+ if (!(instance instanceof Constructor)) {
44
+ throw new TypeError("Cannot call a class as a function");
45
+ }
46
+ }
47
+ function _defineProperties(target, props) {
48
+ for(var i = 0; i < props.length; i++){
49
+ var descriptor = props[i];
50
+ descriptor.enumerable = descriptor.enumerable || false;
51
+ descriptor.configurable = true;
52
+ if ("value" in descriptor) descriptor.writable = true;
53
+ Object.defineProperty(target, descriptor.key, descriptor);
54
+ }
55
+ }
56
+ function _create_class(Constructor, protoProps, staticProps) {
57
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
58
+ if (staticProps) _defineProperties(Constructor, staticProps);
59
+ return Constructor;
60
+ }
31
61
  function _define_property(obj, key, value) {
32
62
  if (key in obj) {
33
63
  Object.defineProperty(obj, key, {
@@ -41,6 +71,39 @@ function _define_property(obj, key, value) {
41
71
  }
42
72
  return obj;
43
73
  }
74
+ function _iterable_to_array(iter) {
75
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
76
+ }
77
+ function _iterable_to_array_limit(arr, i) {
78
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
79
+ if (_i == null) return;
80
+ var _arr = [];
81
+ var _n = true;
82
+ var _d = false;
83
+ var _s, _e;
84
+ try {
85
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
86
+ _arr.push(_s.value);
87
+ if (i && _arr.length === i) break;
88
+ }
89
+ } catch (err) {
90
+ _d = true;
91
+ _e = err;
92
+ } finally{
93
+ try {
94
+ if (!_n && _i["return"] != null) _i["return"]();
95
+ } finally{
96
+ if (_d) throw _e;
97
+ }
98
+ }
99
+ return _arr;
100
+ }
101
+ function _non_iterable_rest() {
102
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
103
+ }
104
+ function _non_iterable_spread() {
105
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
106
+ }
44
107
  function _object_spread(target) {
45
108
  for(var i = 1; i < arguments.length; i++){
46
109
  var source = arguments[i] != null ? arguments[i] : {};
@@ -80,10 +143,24 @@ function _object_spread_props(target, source) {
80
143
  }
81
144
  return target;
82
145
  }
146
+ function _sliced_to_array(arr, i) {
147
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
148
+ }
149
+ function _to_consumable_array(arr) {
150
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
151
+ }
83
152
  function _type_of(obj) {
84
153
  "@swc/helpers - typeof";
85
154
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
86
155
  }
156
+ function _unsupported_iterable_to_array(o, minLen) {
157
+ if (!o) return;
158
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
159
+ var n = Object.prototype.toString.call(o).slice(8, -1);
160
+ if (n === "Object" && o.constructor) n = o.constructor.name;
161
+ if (n === "Map" || n === "Set") return Array.from(n);
162
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
163
+ }
87
164
  function _ts_generator(thisArg, body) {
88
165
  var f, y, t, g, _ = {
89
166
  label: 0,
@@ -240,6 +317,9 @@ var __toCommonJS = function(mod) {
240
317
  // src/hooks/index.ts
241
318
  var index_exports = {};
242
319
  __export(index_exports, {
320
+ useDbSnapshots: function() {
321
+ return useDbSnapshots;
322
+ },
243
323
  useDeepCompareEffect: function() {
244
324
  return useDeepCompareEffect;
245
325
  },
@@ -255,14 +335,17 @@ __export(index_exports, {
255
335
  useSetUserCountry: function() {
256
336
  return useSetUserCountry;
257
337
  },
258
- useSnapshotBulk: function() {
259
- return useSnapshotBulk;
338
+ useSmartSnapshots: function() {
339
+ return useSmartSnapshots;
340
+ },
341
+ useSocketSnapshots: function() {
342
+ return useSocketSnapshots;
260
343
  }
261
344
  });
262
345
  module.exports = __toCommonJS(index_exports);
263
346
  // src/hooks/global.ts
264
347
  var import_akeyless_types_commons2 = require("akeyless-types-commons");
265
- var import_react3 = require("react");
348
+ var import_react2 = require("react");
266
349
  // src/helpers/firebase.ts
267
350
  var import_moment = __toESM(require("moment"));
268
351
  var import_app = require("firebase/app");
@@ -367,6 +450,50 @@ var simpleExtractData = function(doc2) {
367
450
  id: doc2.id
368
451
  });
369
452
  };
453
+ var get_document_by_id = /*#__PURE__*/ function() {
454
+ var _ref = _async_to_generator(function(collection_path, doc_id) {
455
+ var doc_ref, doc_snap, error;
456
+ return _ts_generator(this, function(_state) {
457
+ switch(_state.label){
458
+ case 0:
459
+ _state.trys.push([
460
+ 0,
461
+ 2,
462
+ ,
463
+ 3
464
+ ]);
465
+ doc_ref = (0, import_firestore.doc)(db, collection_path, doc_id);
466
+ return [
467
+ 4,
468
+ (0, import_firestore.getDoc)(doc_ref)
469
+ ];
470
+ case 1:
471
+ doc_snap = _state.sent();
472
+ if (!doc_snap.exists()) {
473
+ throw new Error("Document not found, document id: " + doc_id);
474
+ }
475
+ return [
476
+ 2,
477
+ simpleExtractData(doc_snap)
478
+ ];
479
+ case 2:
480
+ error = _state.sent();
481
+ console.error("Error from get_document_by_id", error);
482
+ return [
483
+ 2,
484
+ null
485
+ ];
486
+ case 3:
487
+ return [
488
+ 2
489
+ ];
490
+ }
491
+ });
492
+ });
493
+ return function get_document_by_id(collection_path, doc_id) {
494
+ return _ref.apply(this, arguments);
495
+ };
496
+ }();
370
497
  var snapshot = function(config, snapshotsFirstTime, settings) {
371
498
  var resolvePromise;
372
499
  var isResolved = false;
@@ -392,11 +519,11 @@ var snapshot = function(config, snapshotsFirstTime, settings) {
392
519
  collectionRef = (0, import_firestore.query)(collectionRef, (0, import_firestore.orderBy)(order.fieldName, order.direction));
393
520
  });
394
521
  }
395
- var unsubscribe = (0, import_firestore.onSnapshot)(collectionRef, function(snapshot2) {
522
+ var unsubscribe = (0, import_firestore.onSnapshot)(collectionRef, function(snapshot3) {
396
523
  if (!snapshotsFirstTime.includes(config.collectionName)) {
397
524
  var _config_onFirstTime, _config_extraParsers;
398
525
  snapshotsFirstTime.push(config.collectionName);
399
- var documents = snapshot2.docs.map(function(doc2) {
526
+ var documents = snapshot3.docs.map(function(doc2) {
400
527
  return simpleExtractData(doc2);
401
528
  });
402
529
  (_config_onFirstTime = config.onFirstTime) === null || _config_onFirstTime === void 0 ? void 0 : _config_onFirstTime.call(config, documents, config);
@@ -410,7 +537,7 @@ var snapshot = function(config, snapshotsFirstTime, settings) {
410
537
  var addedDocs = [];
411
538
  var modifiedDocs = [];
412
539
  var removedDocs = [];
413
- snapshot2.docChanges().forEach(function(change) {
540
+ snapshot3.docChanges().forEach(function(change) {
414
541
  if (change.type === "added") {
415
542
  addedDocs.push(simpleExtractData(change.doc));
416
543
  } else if (change.type === "modified") {
@@ -514,11 +641,363 @@ var biDomain = isLocal ? "http://localhost:9002/api/bi" : baseDomain + "/bi";
514
641
  var notificationsDomain = isLocal ? "http://localhost:9006/api/notifications" : baseDomain + "/notifications";
515
642
  var callCenterGeoDomain = isLocal ? "http://localhost:9007/api/call-center/geo" : baseDomain + "/call-center/geo";
516
643
  var callCenterEventsDomain = isLocal ? "http://localhost:9008/api/call-center/events" : baseDomain + "/call-center/events";
644
+ var dataSocketDomain = isLocal ? "http://localhost:9009/api/data-socket" : baseDomain + "/data-socket";
645
+ var dataSyncDomain = isLocal ? "http://localhost:9010/api/data-sync" : baseDomain + "/data-sync";
646
+ // src/helpers/emails.ts
647
+ var import_axios3 = __toESM(require("axios"));
648
+ // src/helpers/socket.ts
649
+ var import_socket = require("socket.io-client");
650
+ var SESSION_STORAGE_KEY = "sessionId";
651
+ var SocketService = /*#__PURE__*/ function() {
652
+ "use strict";
653
+ function _SocketService() {
654
+ _class_call_check(this, _SocketService);
655
+ this.socket = null;
656
+ this.connectCallbacks = [];
657
+ this.disconnectCallbacks = [];
658
+ this.authToken = null;
659
+ }
660
+ _create_class(_SocketService, [
661
+ {
662
+ /// Initialize the socket connection
663
+ key: "initSocket",
664
+ value: function initSocket() {
665
+ var _this = this;
666
+ if (!this.socket) {
667
+ var socketUrl = isLocal ? "http://localhost:9009" : mode === "qa" ? "https://nx-api.xyz" : "https://nx-api.info";
668
+ this.socket = (0, import_socket.io)(socketUrl, {
669
+ path: "/api/data-socket/connect",
670
+ auth: function(cb) {
671
+ var sessionId = localStorage.getItem(SESSION_STORAGE_KEY) || void 0;
672
+ var token = _this.authToken;
673
+ var authPayload = {};
674
+ if (token) authPayload.token = token;
675
+ if (sessionId) authPayload.sessionId = sessionId;
676
+ cb(authPayload);
677
+ },
678
+ transports: [
679
+ "websocket"
680
+ ],
681
+ reconnection: true,
682
+ reconnectionAttempts: 30,
683
+ reconnectionDelay: 2 * 1e3
684
+ });
685
+ this.socket.on("connect", function() {
686
+ var _this_socket, _this_socket1;
687
+ console.log("\uD83D\uDFE2 Socket connected: ".concat((_this_socket = _this.socket) === null || _this_socket === void 0 ? void 0 : _this_socket.id, " (recovered - ").concat((_this_socket1 = _this.socket) === null || _this_socket1 === void 0 ? void 0 : _this_socket1.recovered, ")"));
688
+ _this.connectCallbacks.forEach(function(cb) {
689
+ return cb();
690
+ });
691
+ });
692
+ this.socket.on("disconnect", function(reason) {
693
+ console.log("Socket disconnected:", reason);
694
+ _this.disconnectCallbacks.forEach(function(cb) {
695
+ return cb();
696
+ });
697
+ });
698
+ this.socket.on("session", function(param) {
699
+ var session_id = param.session_id;
700
+ if (session_id) {
701
+ localStorage.setItem(SESSION_STORAGE_KEY, session_id);
702
+ }
703
+ });
704
+ this.socket.on("connect_error", function(error) {
705
+ console.error("Socket connection error:", error);
706
+ });
707
+ }
708
+ }
709
+ },
710
+ {
711
+ /// get socket instance
712
+ key: "getSocketInstance",
713
+ value: function getSocketInstance() {
714
+ if (!this.socket) {
715
+ this.initSocket();
716
+ }
717
+ if (!this.socket) {
718
+ throw new Error("Socket not initialized");
719
+ }
720
+ if (!this.socket.connected) {
721
+ this.socket.connect();
722
+ }
723
+ return this.socket;
724
+ }
725
+ },
726
+ {
727
+ /// connection management methods
728
+ key: "startSession",
729
+ value: function startSession(token) {
730
+ this.setAuthToken(token);
731
+ this.initSocket();
732
+ }
733
+ },
734
+ {
735
+ key: "onConnect",
736
+ value: function onConnect(callback) {
737
+ var _this = this;
738
+ var _this_socket;
739
+ if (!this.connectCallbacks.includes(callback)) {
740
+ this.connectCallbacks.push(callback);
741
+ }
742
+ if ((_this_socket = this.socket) === null || _this_socket === void 0 ? void 0 : _this_socket.connected) {
743
+ callback();
744
+ }
745
+ return function() {
746
+ return _this.offConnect(callback);
747
+ };
748
+ }
749
+ },
750
+ {
751
+ key: "offConnect",
752
+ value: function offConnect(callback) {
753
+ this.connectCallbacks = this.connectCallbacks.filter(function(cb) {
754
+ return cb !== callback;
755
+ });
756
+ }
757
+ },
758
+ {
759
+ key: "onDisconnect",
760
+ value: function onDisconnect(callback) {
761
+ var _this = this;
762
+ if (!this.disconnectCallbacks.includes(callback)) {
763
+ this.disconnectCallbacks.push(callback);
764
+ }
765
+ if (this.socket && !this.socket.connected) {
766
+ callback();
767
+ }
768
+ return function() {
769
+ return _this.offDisconnect(callback);
770
+ };
771
+ }
772
+ },
773
+ {
774
+ key: "offDisconnect",
775
+ value: function offDisconnect(callback) {
776
+ this.disconnectCallbacks = this.disconnectCallbacks.filter(function(cb) {
777
+ return cb !== callback;
778
+ });
779
+ }
780
+ },
781
+ {
782
+ key: "isConnected",
783
+ value: function isConnected() {
784
+ var _this_socket;
785
+ return ((_this_socket = this.socket) === null || _this_socket === void 0 ? void 0 : _this_socket.connected) || false;
786
+ }
787
+ },
788
+ {
789
+ key: "setAuthToken",
790
+ value: function setAuthToken(token) {
791
+ this.authToken = token;
792
+ if (this.socket) {
793
+ this.socket.connect();
794
+ }
795
+ }
796
+ },
797
+ {
798
+ key: "disconnectSocket",
799
+ value: function disconnectSocket() {
800
+ if (this.socket) {
801
+ this.socket.io.engine.close();
802
+ }
803
+ }
804
+ },
805
+ {
806
+ /// subscribe to collections
807
+ key: "subscribeToCollections",
808
+ value: function subscribeToCollections(config) {
809
+ var _this = this;
810
+ if (config.length === 0) {
811
+ return function() {};
812
+ }
813
+ var s = this.getSocketInstance();
814
+ var collectionsNames = config.map(function(c) {
815
+ return c.collectionName;
816
+ });
817
+ var eventHandlers = [];
818
+ config.forEach(function(configuration) {
819
+ var collectionName = configuration.collectionName, onAdd = configuration.onAdd, onFirstTime = configuration.onFirstTime, onModify = configuration.onModify, onRemove = configuration.onRemove, extraParsers = configuration.extraParsers, conditions = configuration.conditions, orderBy2 = configuration.orderBy;
820
+ var attach = function(eventName, handler) {
821
+ _this.socket.off(eventName, handler);
822
+ _this.socket.on(eventName, handler);
823
+ eventHandlers.push({
824
+ eventName: eventName,
825
+ handler: handler
826
+ });
827
+ };
828
+ attach("initial:".concat(collectionName), onFirstTime);
829
+ attach("add:".concat(collectionName), onAdd);
830
+ attach("update:".concat(collectionName), onModify);
831
+ attach("delete:".concat(collectionName), onRemove);
832
+ extraParsers === null || extraParsers === void 0 ? void 0 : extraParsers.forEach(function(parsers) {
833
+ var extraOnAdd = parsers.onAdd, extraOnFirstTime = parsers.onFirstTime, extraOnModify = parsers.onModify, extraOnRemove = parsers.onRemove;
834
+ attach("initial:".concat(collectionName), extraOnFirstTime);
835
+ attach("add:".concat(collectionName), extraOnAdd);
836
+ attach("update:".concat(collectionName), extraOnModify);
837
+ attach("delete:".concat(collectionName), extraOnRemove);
838
+ });
839
+ });
840
+ s.emit("subscribe_collections", collectionsNames, function(callback) {
841
+ if (callback.success) {
842
+ console.log("Successfully subscribed to: ".concat(collectionsNames.join(", ")));
843
+ } else {
844
+ console.error("Failed to subscribe to ".concat(config.join(", "), ": ").concat(callback.message));
845
+ }
846
+ });
847
+ return function() {
848
+ console.log("Cleaning up subscriptions for: ".concat(collectionsNames.join(", ")));
849
+ s.emit("unsubscribe_collections", collectionsNames);
850
+ eventHandlers.forEach(function(eh) {
851
+ s.off(eh.eventName, eh.handler);
852
+ });
853
+ };
854
+ }
855
+ },
856
+ {
857
+ /// set data
858
+ key: "setData",
859
+ value: function setData(payload) {
860
+ var s = this.getSocketInstance();
861
+ return new Promise(function(resolve, reject) {
862
+ s.emit("set_data", payload, function(callback) {
863
+ if (callback.success) {
864
+ console.log("Data saved successfully:", payload);
865
+ console.log("ack", callback);
866
+ resolve(callback);
867
+ } else {
868
+ reject(new Error(callback.message || "Save operation failed"));
869
+ }
870
+ });
871
+ });
872
+ }
873
+ },
874
+ {
875
+ /// get data
876
+ key: "getCollectionData",
877
+ value: function getCollectionData(payload) {
878
+ var s = this.getSocketInstance();
879
+ s.emit("get_data", {
880
+ collection_name: payload.collection_name
881
+ }, function(socketCallback) {
882
+ if (socketCallback.success && socketCallback.data) {
883
+ payload.callback(socketCallback.data);
884
+ } else {
885
+ payload.callback(payload.defaultValue);
886
+ }
887
+ });
888
+ }
889
+ },
890
+ {
891
+ key: "getDocumentData",
892
+ value: function getDocumentData(payload) {
893
+ var s = this.getSocketInstance();
894
+ s.emit("get_data", {
895
+ collection_name: payload.collection_name,
896
+ key: payload.key
897
+ }, function(socketCallback) {
898
+ if (socketCallback.success && socketCallback.data) {
899
+ payload.callback(socketCallback.data);
900
+ } else {
901
+ payload.callback(payload.defaultValue);
902
+ }
903
+ });
904
+ }
905
+ },
906
+ {
907
+ /// delete data
908
+ key: "deleteData",
909
+ value: function deleteData(payload) {
910
+ var s = this.getSocketInstance();
911
+ return new Promise(function(resolve, reject) {
912
+ s.emit("delete_data", payload, function(callback) {
913
+ if (callback.success) {
914
+ console.log("Data deleted successfully:", payload);
915
+ console.log("delete ack", callback);
916
+ resolve(callback);
917
+ } else {
918
+ reject(new Error(callback.message || "Delete operation failed"));
919
+ }
920
+ });
921
+ });
922
+ }
923
+ },
924
+ {
925
+ key: "clearAllRedisData",
926
+ value: function clearAllRedisData() {
927
+ var s = this.getSocketInstance();
928
+ return new Promise(function(resolve, reject) {
929
+ s.emit("clear_all_redis_data", function(ack) {
930
+ if (ack.success) {
931
+ resolve(ack);
932
+ } else {
933
+ reject(new Error(ack.message || "Clear all Redis data operation failed"));
934
+ }
935
+ });
936
+ });
937
+ }
938
+ }
939
+ ], [
940
+ {
941
+ key: "getInstance",
942
+ value: function getInstance() {
943
+ if (!_SocketService.instance) {
944
+ _SocketService.instance = new _SocketService();
945
+ }
946
+ return _SocketService.instance;
947
+ }
948
+ }
949
+ ]);
950
+ return _SocketService;
951
+ }();
952
+ var socketServiceInstance = SocketService.getInstance();
953
+ // src/hooks/global.ts
954
+ var useDocumentTitle = function(title) {
955
+ (0, import_react2.useEffect)(function() {
956
+ document.title = title;
957
+ }, [
958
+ title
959
+ ]);
960
+ return null;
961
+ };
962
+ var useSetUserCountry = function(setUserCountry, changLang) {
963
+ (0, import_react2.useLayoutEffect)(function() {
964
+ var currentCountry = localStorage.getItem("userCountry");
965
+ if (!currentCountry) {
966
+ var updateCountry = /*#__PURE__*/ function() {
967
+ var _ref = _async_to_generator(function() {
968
+ var country;
969
+ return _ts_generator(this, function(_state) {
970
+ switch(_state.label){
971
+ case 0:
972
+ return [
973
+ 4,
974
+ getUserCountryByIp()
975
+ ];
976
+ case 1:
977
+ country = _state.sent();
978
+ changLang(country === import_akeyless_types_commons2.CountryOptions.IL ? "he" : "en");
979
+ setUserCountry(country);
980
+ localStorage.setItem("userCountry", country);
981
+ return [
982
+ 2
983
+ ];
984
+ }
985
+ });
986
+ });
987
+ return function updateCountry() {
988
+ return _ref.apply(this, arguments);
989
+ };
990
+ }();
991
+ updateCountry();
992
+ }
993
+ }, []);
994
+ return null;
995
+ };
517
996
  // src/hooks/react.ts
518
997
  var import_lodash2 = require("lodash");
519
- var import_react2 = require("react");
998
+ var import_react3 = require("react");
520
999
  function useSafeEffect(callback, dependencies, error_message) {
521
- (0, import_react2.useEffect)(function() {
1000
+ (0, import_react3.useEffect)(function() {
522
1001
  try {
523
1002
  callback();
524
1003
  } catch (error) {
@@ -527,37 +1006,32 @@ function useSafeEffect(callback, dependencies, error_message) {
527
1006
  }, dependencies);
528
1007
  }
529
1008
  var useDeepCompareMemo = function(factory, dependencies) {
530
- var previousDepsRef = (0, import_react2.useRef)([]);
1009
+ var previousDepsRef = (0, import_react3.useRef)([]);
531
1010
  if (!(0, import_lodash2.isEqual)(dependencies, previousDepsRef.current)) {
532
1011
  previousDepsRef.current = dependencies;
533
1012
  }
534
- return (0, import_react2.useMemo)(factory, previousDepsRef.current);
1013
+ return (0, import_react3.useMemo)(factory, previousDepsRef.current);
535
1014
  };
536
1015
  function useDeepCompareEffect(effect, dependencies) {
537
- var previousDepsRef = (0, import_react2.useRef)();
1016
+ var previousDepsRef = (0, import_react3.useRef)();
538
1017
  if (!(0, import_lodash2.isEqual)(previousDepsRef.current, dependencies)) {
539
1018
  previousDepsRef.current = dependencies;
540
1019
  }
541
- (0, import_react2.useEffect)(effect, [
1020
+ (0, import_react3.useEffect)(effect, [
542
1021
  previousDepsRef.current
543
1022
  ]);
544
1023
  }
545
- // src/hooks/global.ts
546
- var useDocumentTitle = function(title) {
547
- (0, import_react3.useEffect)(function() {
548
- document.title = title;
549
- }, [
550
- title
551
- ]);
552
- return null;
553
- };
554
- var useSnapshotBulk = function(configs, label, settings) {
555
- var snapshotsFirstTime = (0, import_react3.useRef)([]);
556
- var unsubscribeFunctions = (0, import_react3.useRef)([]);
1024
+ // src/hooks/WebWorker.ts
1025
+ var import_react4 = require("react");
1026
+ // src/hooks/snapshots.ts
1027
+ var import_react5 = require("react");
1028
+ var useDbSnapshots = function(configs, label, settings) {
1029
+ var snapshotsFirstTime = (0, import_react5.useRef)([]);
1030
+ var unsubscribeFunctions = (0, import_react5.useRef)([]);
557
1031
  useDeepCompareEffect(function() {
558
1032
  var start = performance.now();
559
- if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs)) {
560
- console.log("==> ".concat(label || "Custom snapshots", " started... "));
1033
+ if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs) && configs.length > 0) {
1034
+ console.log("==> ".concat(label || "DB snapshots", " started from db... "));
561
1035
  }
562
1036
  var snapshotResults = configs.map(function(config) {
563
1037
  return snapshot(config, snapshotsFirstTime.current, settings);
@@ -568,8 +1042,8 @@ var useSnapshotBulk = function(configs, label, settings) {
568
1042
  Promise.all(snapshotResults.map(function(result) {
569
1043
  return result.promise;
570
1044
  })).then(function() {
571
- if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs)) {
572
- console.log("==> ".concat(label || "Custom snapshots", " ended. It took ").concat((performance.now() - start).toFixed(2), " ms"));
1045
+ if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs) && configs.length > 0) {
1046
+ console.log("==> ".concat(label || "DB snapshots", " ended from db. It took ").concat((performance.now() - start).toFixed(2), " ms"));
573
1047
  }
574
1048
  });
575
1049
  if (settings === null || settings === void 0 ? void 0 : settings.cleanupForConfigChange) {
@@ -579,8 +1053,8 @@ var useSnapshotBulk = function(configs, label, settings) {
579
1053
  unsubscribe();
580
1054
  }
581
1055
  });
582
- if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs)) {
583
- console.log("==> ".concat(label || "Custom snapshots", " unsubscribed"));
1056
+ if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs) && configs.length > 0) {
1057
+ console.log("==> ".concat(label || "DB snapshots", " unsubscribed from db"));
584
1058
  }
585
1059
  };
586
1060
  }
@@ -589,7 +1063,7 @@ var useSnapshotBulk = function(configs, label, settings) {
589
1063
  label,
590
1064
  settings
591
1065
  ]);
592
- (0, import_react3.useEffect)(function() {
1066
+ (0, import_react5.useEffect)(function() {
593
1067
  return function() {
594
1068
  unsubscribeFunctions.current.forEach(function(unsubscribe) {
595
1069
  if (unsubscribe) {
@@ -597,54 +1071,135 @@ var useSnapshotBulk = function(configs, label, settings) {
597
1071
  }
598
1072
  });
599
1073
  if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs)) {
600
- console.log("==> ".concat(label || "Custom snapshots", " unsubscribed"));
1074
+ console.log("==> ".concat(label || "DB snapshots", " unsubscribed"));
601
1075
  }
602
1076
  };
603
1077
  }, []);
604
1078
  };
605
- var useSetUserCountry = function(setUserCountry, changLang) {
606
- (0, import_react3.useLayoutEffect)(function() {
607
- var currentCountry = localStorage.getItem("userCountry");
608
- if (!currentCountry) {
609
- var updateCountry = /*#__PURE__*/ function() {
610
- var _ref = _async_to_generator(function() {
611
- var country;
612
- return _ts_generator(this, function(_state) {
613
- switch(_state.label){
614
- case 0:
615
- return [
616
- 4,
617
- getUserCountryByIp()
618
- ];
619
- case 1:
620
- country = _state.sent();
621
- changLang(country === import_akeyless_types_commons2.CountryOptions.IL ? "he" : "en");
622
- setUserCountry(country);
623
- localStorage.setItem("userCountry", country);
624
- return [
625
- 2
626
- ];
627
- }
628
- });
629
- });
630
- return function updateCountry() {
631
- return _ref.apply(this, arguments);
632
- };
633
- }();
634
- updateCountry();
1079
+ var useSmartSnapshots = function(configs, label, settings) {
1080
+ var _ref = _sliced_to_array((0, import_react5.useState)(null), 2), cacheCollectionsConfig = _ref[0], setCacheCollectionsConfig = _ref[1];
1081
+ (0, import_react5.useEffect)(function() {
1082
+ get_document_by_id("nx-settings", "cache_collections_config").then(function(res) {
1083
+ return setCacheCollectionsConfig(res);
1084
+ });
1085
+ return function() {
1086
+ return setCacheCollectionsConfig(null);
1087
+ };
1088
+ }, []);
1089
+ var groupedConfig = (0, import_react5.useMemo)(function() {
1090
+ if (!cacheCollectionsConfig) {
1091
+ return {
1092
+ configForDb: [],
1093
+ configForCache: []
1094
+ };
635
1095
  }
1096
+ var configForDb = [];
1097
+ var configForCache = [];
1098
+ configs.forEach(function(cfg) {
1099
+ var collectionName = cfg.collectionName, _cfg_subscribeTo = cfg.subscribeTo, subscribeTo = _cfg_subscribeTo === void 0 ? "cache" : _cfg_subscribeTo;
1100
+ if (subscribeTo === "cache" && cacheCollectionsConfig[collectionName]) {
1101
+ configForCache.push(cfg);
1102
+ } else {
1103
+ configForDb.push(cfg);
1104
+ }
1105
+ });
1106
+ return {
1107
+ configForDb: configForDb,
1108
+ configForCache: configForCache
1109
+ };
1110
+ }, [
1111
+ configs,
1112
+ cacheCollectionsConfig
1113
+ ]);
1114
+ useDbSnapshots(groupedConfig.configForDb, label, settings);
1115
+ var socketConnected = useSocketSnapshots(groupedConfig.configForCache, label, settings).socketConnected;
1116
+ return {
1117
+ groupedConfig: groupedConfig,
1118
+ socketConnected: socketConnected
1119
+ };
1120
+ };
1121
+ var useSocketSnapshots = function(configs, label, settings) {
1122
+ var _auth_currentUser;
1123
+ var _ref = _sliced_to_array((0, import_react5.useState)(socketServiceInstance.isConnected()), 2), socketConnected = _ref[0], setSocketConnected = _ref[1];
1124
+ var _ref1 = _sliced_to_array((0, import_react5.useState)([]), 2), cleanupSubscriptions = _ref1[0], setCleanupSubscriptions = _ref1[1];
1125
+ var socketStarted = (0, import_react5.useRef)(false);
1126
+ useDeepCompareEffect(function() {
1127
+ if (!auth.currentUser) {
1128
+ return;
1129
+ }
1130
+ var subscribe = function() {
1131
+ if (configs.length === 0) {
1132
+ return;
1133
+ }
1134
+ var disposer = socketServiceInstance.subscribeToCollections(configs);
1135
+ setCleanupSubscriptions(function(prev) {
1136
+ return _to_consumable_array(prev).concat([
1137
+ disposer
1138
+ ]);
1139
+ });
1140
+ if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs)) {
1141
+ console.log("==> ".concat(label || "Cache snapshots", " subscribed to ").concat(configs.map(function(c) {
1142
+ return c.collectionName;
1143
+ }).join(", ")));
1144
+ }
1145
+ };
1146
+ if (socketServiceInstance.isConnected()) {
1147
+ setSocketConnected(true);
1148
+ subscribe();
1149
+ } else if (!socketStarted.current) {
1150
+ socketStarted.current = true;
1151
+ auth.currentUser.getIdToken().then(function(token) {
1152
+ socketServiceInstance.startSession(token);
1153
+ if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs)) {
1154
+ console.log("==> ".concat(label || "Cache snapshots", " started... "));
1155
+ }
1156
+ });
1157
+ }
1158
+ var offConnect = socketServiceInstance.onConnect(function() {
1159
+ setSocketConnected(true);
1160
+ socketStarted.current = false;
1161
+ subscribe();
1162
+ });
1163
+ var offDisconnect = socketServiceInstance.onDisconnect(function() {
1164
+ setSocketConnected(false);
1165
+ cleanupSubscriptions.forEach(function(cleanup) {
1166
+ return cleanup();
1167
+ });
1168
+ });
1169
+ return function() {
1170
+ cleanupSubscriptions.forEach(function(cleanup) {
1171
+ return cleanup();
1172
+ });
1173
+ offConnect === null || offConnect === void 0 ? void 0 : offConnect();
1174
+ offDisconnect === null || offDisconnect === void 0 ? void 0 : offDisconnect();
1175
+ if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogs) && configs.length > 0) {
1176
+ console.log("==> ".concat(label || "Cache snapshots", " unsubscribed. "));
1177
+ }
1178
+ };
1179
+ }, [
1180
+ configs,
1181
+ (_auth_currentUser = auth.currentUser) === null || _auth_currentUser === void 0 ? void 0 : _auth_currentUser.uid
1182
+ ]);
1183
+ (0, import_react5.useEffect)(function() {
1184
+ return function() {
1185
+ cleanupSubscriptions.forEach(function(cleanup) {
1186
+ return cleanup();
1187
+ });
1188
+ };
636
1189
  }, []);
637
- return null;
1190
+ return {
1191
+ socketConnected: socketConnected
1192
+ };
638
1193
  };
639
- // src/hooks/WebWorker.ts
640
- var import_react5 = require("react");
641
1194
  // Annotate the CommonJS export names for ESM import in node:
642
1195
  0 && (module.exports = {
1196
+ useDbSnapshots: useDbSnapshots,
643
1197
  useDeepCompareEffect: useDeepCompareEffect,
644
1198
  useDeepCompareMemo: useDeepCompareMemo,
645
1199
  useDocumentTitle: useDocumentTitle,
646
1200
  useSafeEffect: useSafeEffect,
647
1201
  useSetUserCountry: useSetUserCountry,
648
- useSnapshotBulk: useSnapshotBulk
1202
+ useSmartSnapshots: useSmartSnapshots,
1203
+ useSocketSnapshots: useSocketSnapshots
649
1204
  });
650
1205
  //# sourceMappingURL=index.js.map