akeyless-client-commons 1.1.17-test.9 → 1.1.19

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.
@@ -39,25 +39,6 @@ function _async_to_generator(fn) {
39
39
  });
40
40
  };
41
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
- }
61
42
  function _define_property(obj, key, value) {
62
43
  if (key in obj) {
63
44
  Object.defineProperty(obj, key, {
@@ -1846,8 +1827,6 @@ var biDomain = isLocal ? "http://localhost:9002/api/bi" : baseDomain + "/bi";
1846
1827
  var notificationsDomain = isLocal ? "http://localhost:9006/api/notifications" : baseDomain + "/notifications";
1847
1828
  var callCenterGeoDomain = isLocal ? "http://localhost:9007/api/call-center/geo" : baseDomain + "/call-center/geo";
1848
1829
  var callCenterEventsDomain = isLocal ? "http://localhost:9008/api/call-center/events" : baseDomain + "/call-center/events";
1849
- var dataSocketDomain = isLocal ? "http://localhost:9009/api/data-socket" : baseDomain + "/data-socket";
1850
- var dataSyncDomain = isLocal ? "http://localhost:9010/api/data-sync" : baseDomain + "/data-sync";
1851
1830
  var akeylessOnlineDomain = mode === "qa" ? "https://akeyless-online.xyz" : "https://akeyless-online.info";
1852
1831
  var nxApiCall = /*#__PURE__*/ function() {
1853
1832
  var _ref = _async_to_generator(function(serverName, method, url, data) {
@@ -1878,12 +1857,6 @@ var nxApiCall = /*#__PURE__*/ function() {
1878
1857
  case "call-center-geo":
1879
1858
  urlResult = "".concat(callCenterGeoDomain, "/").concat(url);
1880
1859
  break;
1881
- case "data-socket":
1882
- urlResult = "".concat(dataSocketDomain, "/").concat(url);
1883
- break;
1884
- case "data-sync":
1885
- urlResult = "".concat(dataSyncDomain, "/").concat(url);
1886
- break;
1887
1860
  default:
1888
1861
  break;
1889
1862
  }
@@ -1933,307 +1906,5 @@ var nxApiCall = /*#__PURE__*/ function() {
1933
1906
  return _ref.apply(this, arguments);
1934
1907
  };
1935
1908
  }();
1936
- // src/helpers/socket.ts
1937
- import { io } from "socket.io-client";
1938
- var SESSION_STORAGE_KEY = "sessionId";
1939
- var SocketService = /*#__PURE__*/ function() {
1940
- "use strict";
1941
- function _SocketService() {
1942
- _class_call_check(this, _SocketService);
1943
- this.socket = null;
1944
- this.connectCallbacks = [];
1945
- this.disconnectCallbacks = [];
1946
- this.authToken = null;
1947
- }
1948
- _create_class(_SocketService, [
1949
- {
1950
- /// Initialize the socket connection
1951
- key: "initSocket",
1952
- value: function initSocket() {
1953
- var _this = this;
1954
- if (!this.socket) {
1955
- var socketUrl = isLocal ? "http://localhost:9009" : mode === "qa" ? "https://nx-api.xyz" : "https://nx-api.info";
1956
- this.socket = io(socketUrl, {
1957
- path: "/api/data-socket/connect",
1958
- auth: function(cb) {
1959
- var sessionId = localStorage.getItem(SESSION_STORAGE_KEY) || void 0;
1960
- var token = _this.authToken;
1961
- var authPayload = {};
1962
- if (token) authPayload.token = token;
1963
- if (sessionId) authPayload.sessionId = sessionId;
1964
- cb(authPayload);
1965
- },
1966
- reconnection: true,
1967
- reconnectionAttempts: 30,
1968
- reconnectionDelay: 2 * 1e3
1969
- });
1970
- this.socket.on("connect", function() {
1971
- var _this_socket, _this_socket1;
1972
- 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, ")"));
1973
- _this.connectCallbacks.forEach(function(cb) {
1974
- return cb();
1975
- });
1976
- });
1977
- this.socket.on("disconnect", function(reason) {
1978
- console.log("Socket disconnected:", reason);
1979
- _this.disconnectCallbacks.forEach(function(cb) {
1980
- return cb();
1981
- });
1982
- });
1983
- this.socket.on("session", function(param) {
1984
- var sessionId = param.sessionId;
1985
- if (sessionId) {
1986
- localStorage.setItem(SESSION_STORAGE_KEY, sessionId);
1987
- }
1988
- });
1989
- this.socket.on("connect_error", function(error) {
1990
- console.error("Socket connection error:", error);
1991
- });
1992
- }
1993
- }
1994
- },
1995
- {
1996
- /// get socket instance
1997
- key: "getSocketInstance",
1998
- value: function getSocketInstance() {
1999
- if (!this.socket) {
2000
- this.initSocket();
2001
- }
2002
- if (!this.socket) {
2003
- throw new Error("Socket not initialized");
2004
- }
2005
- if (!this.socket.connected) {
2006
- this.socket.connect();
2007
- }
2008
- return this.socket;
2009
- }
2010
- },
2011
- {
2012
- /// connection management methods
2013
- key: "startSession",
2014
- value: function startSession(token) {
2015
- this.setAuthToken(token);
2016
- this.initSocket();
2017
- }
2018
- },
2019
- {
2020
- key: "onConnect",
2021
- value: function onConnect(callback) {
2022
- var _this = this;
2023
- var _this_socket;
2024
- if (!this.connectCallbacks.includes(callback)) {
2025
- this.connectCallbacks.push(callback);
2026
- }
2027
- if ((_this_socket = this.socket) === null || _this_socket === void 0 ? void 0 : _this_socket.connected) {
2028
- callback();
2029
- }
2030
- return function() {
2031
- return _this.offConnect(callback);
2032
- };
2033
- }
2034
- },
2035
- {
2036
- key: "offConnect",
2037
- value: function offConnect(callback) {
2038
- this.connectCallbacks = this.connectCallbacks.filter(function(cb) {
2039
- return cb !== callback;
2040
- });
2041
- }
2042
- },
2043
- {
2044
- key: "onDisconnect",
2045
- value: function onDisconnect(callback) {
2046
- var _this = this;
2047
- if (!this.disconnectCallbacks.includes(callback)) {
2048
- this.disconnectCallbacks.push(callback);
2049
- }
2050
- if (this.socket && !this.socket.connected) {
2051
- callback();
2052
- }
2053
- return function() {
2054
- return _this.offDisconnect(callback);
2055
- };
2056
- }
2057
- },
2058
- {
2059
- key: "offDisconnect",
2060
- value: function offDisconnect(callback) {
2061
- this.disconnectCallbacks = this.disconnectCallbacks.filter(function(cb) {
2062
- return cb !== callback;
2063
- });
2064
- }
2065
- },
2066
- {
2067
- key: "isConnected",
2068
- value: function isConnected() {
2069
- var _this_socket;
2070
- return ((_this_socket = this.socket) === null || _this_socket === void 0 ? void 0 : _this_socket.connected) || false;
2071
- }
2072
- },
2073
- {
2074
- key: "setAuthToken",
2075
- value: function setAuthToken(token) {
2076
- this.authToken = token;
2077
- if (this.socket) {
2078
- this.socket.connect();
2079
- }
2080
- }
2081
- },
2082
- {
2083
- key: "disconnectSocket",
2084
- value: function disconnectSocket() {
2085
- if (this.socket) {
2086
- this.socket.io.engine.close();
2087
- }
2088
- }
2089
- },
2090
- {
2091
- /// subscribe to collections
2092
- key: "subscribeToCollections",
2093
- value: function subscribeToCollections(config) {
2094
- var _this = this;
2095
- if (config.length === 0) {
2096
- return function() {};
2097
- }
2098
- var s = this.getSocketInstance();
2099
- var collectionsNames = config.map(function(c) {
2100
- return c.collectionName;
2101
- });
2102
- var eventHandlers = [];
2103
- config.forEach(function(configuration) {
2104
- 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;
2105
- var attach = function(eventName, handler) {
2106
- _this.socket.off(eventName, handler);
2107
- _this.socket.on(eventName, handler);
2108
- eventHandlers.push({
2109
- eventName: eventName,
2110
- handler: handler
2111
- });
2112
- };
2113
- attach("initial:".concat(collectionName), onFirstTime);
2114
- attach("add:".concat(collectionName), onAdd);
2115
- attach("update:".concat(collectionName), onModify);
2116
- attach("delete:".concat(collectionName), onRemove);
2117
- extraParsers === null || extraParsers === void 0 ? void 0 : extraParsers.forEach(function(parsers) {
2118
- var extraOnAdd = parsers.onAdd, extraOnFirstTime = parsers.onFirstTime, extraOnModify = parsers.onModify, extraOnRemove = parsers.onRemove;
2119
- attach("initial:".concat(collectionName), extraOnFirstTime);
2120
- attach("add:".concat(collectionName), extraOnAdd);
2121
- attach("update:".concat(collectionName), extraOnModify);
2122
- attach("delete:".concat(collectionName), extraOnRemove);
2123
- });
2124
- });
2125
- s.emit("subscribe_collections", collectionsNames, function(callback) {
2126
- if (callback.success) {
2127
- console.log("Successfully subscribed to: ".concat(collectionsNames.join(", ")));
2128
- } else {
2129
- console.error("Failed to subscribe to ".concat(config.join(", "), ": ").concat(callback.message));
2130
- }
2131
- });
2132
- return function() {
2133
- console.log("Cleaning up subscriptions for: ".concat(collectionsNames.join(", ")));
2134
- s.emit("unsubscribe_collections", collectionsNames);
2135
- eventHandlers.forEach(function(eh) {
2136
- s.off(eh.eventName, eh.handler);
2137
- });
2138
- };
2139
- }
2140
- },
2141
- {
2142
- /// set data
2143
- key: "setData",
2144
- value: function setData(payload) {
2145
- var s = this.getSocketInstance();
2146
- return new Promise(function(resolve, reject) {
2147
- s.emit("set_data", payload, function(callback) {
2148
- if (callback.success) {
2149
- console.log("Data saved successfully:", payload);
2150
- console.log("ack", callback);
2151
- resolve(callback);
2152
- } else {
2153
- reject(new Error(callback.message || "Save operation failed"));
2154
- }
2155
- });
2156
- });
2157
- }
2158
- },
2159
- {
2160
- /// get data
2161
- key: "getCollectionData",
2162
- value: function getCollectionData(payload) {
2163
- var s = this.getSocketInstance();
2164
- s.emit("get_data", {
2165
- collection_name: payload.collection_name
2166
- }, function(socketCallback) {
2167
- if (socketCallback.success && socketCallback.data) {
2168
- payload.callback(socketCallback.data);
2169
- } else {
2170
- payload.callback(payload.defaultValue);
2171
- }
2172
- });
2173
- }
2174
- },
2175
- {
2176
- key: "getDocumentData",
2177
- value: function getDocumentData(payload) {
2178
- var s = this.getSocketInstance();
2179
- s.emit("get_data", {
2180
- collection_name: payload.collection_name,
2181
- key: payload.key
2182
- }, function(socketCallback) {
2183
- if (socketCallback.success && socketCallback.data) {
2184
- payload.callback(socketCallback.data);
2185
- } else {
2186
- payload.callback(payload.defaultValue);
2187
- }
2188
- });
2189
- }
2190
- },
2191
- {
2192
- /// delete data
2193
- key: "deleteData",
2194
- value: function deleteData(payload) {
2195
- var s = this.getSocketInstance();
2196
- return new Promise(function(resolve, reject) {
2197
- s.emit("delete_data", payload, function(callback) {
2198
- if (callback.success) {
2199
- console.log("Data deleted successfully:", payload);
2200
- console.log("delete ack", callback);
2201
- resolve(callback);
2202
- } else {
2203
- reject(new Error(callback.message || "Delete operation failed"));
2204
- }
2205
- });
2206
- });
2207
- }
2208
- },
2209
- {
2210
- key: "clearAllRedisData",
2211
- value: function clearAllRedisData() {
2212
- var s = this.getSocketInstance();
2213
- return new Promise(function(resolve, reject) {
2214
- s.emit("clear_all_redis_data", function(ack) {
2215
- if (ack.success) {
2216
- resolve(ack);
2217
- } else {
2218
- reject(new Error(ack.message || "Clear all Redis data operation failed"));
2219
- }
2220
- });
2221
- });
2222
- }
2223
- }
2224
- ], [
2225
- {
2226
- key: "getInstance",
2227
- value: function getInstance() {
2228
- if (!_SocketService.instance) {
2229
- _SocketService.instance = new _SocketService();
2230
- }
2231
- return _SocketService.instance;
2232
- }
2233
- }
2234
- ]);
2235
- return _SocketService;
2236
- }();
2237
- var socketServiceInstance = SocketService.getInstance();
2238
- export { addAuditRecord, addLoginAudit, add_document, addressRegex, akeylessOnlineDomain, app, appCheck, auth, baseDomain, biDomain, calculateBearing, callCenterEventsDomain, callCenterGeoDomain, carsRegex, chartsRegex, checkUserPermissions, cleanNxSites, cn, collections, colorRegex, createSelectors, dataSocketDomain, dataSyncDomain, db, delete_document, devicesDomain, displayFormatPhoneNumber, durationToSeconds, emailRegex, extractAlertsData, extractBoardsData, extractCanbusData, extractCarsData, extractClientData, extractLocationData, extractSiteData, fire_base_TIME_TEMP, formatCarNumber, getAddressByGeo, getFixedNumber, getFormCheckboxValue, getFormElementValue, getLocationUrl, getUserByEmail, getUserByIdentifier, getUserByPhone, getUserCountryByIp, get_all_documents, get_document_by_id, get_international_phone_number, googleLoginProvider, handleChange, handleInvalid, handlePaste, initializeUserPermissions, international_israel_phone_format, isInternational, isInternationalIsraelPhone, isLocal, isNodeEnv, is_iccid, local_israel_phone_format, mode, multiStringFormat, notificationsDomain, numbersOnlyRegex, numbersRegex, nxApiCall, parseMultiSelectInput, parsePermissions, parseSnapshotAsArray, priceRegex, propsAreEqual, query_document, query_document_by_conditions, query_documents, query_documents_by_conditions, renderOnce, secondsToDuration, setFormElementValue, setState, set_document, simpleExtractData, snapshot, snapshotDocument, socketServiceInstance, sort_by_timestamp, storage, textNumbersRegex, textRegex, timestamp_to_millis, timestamp_to_string, useLoginWithGoogle, useStoreValues, useValidation, userNameFormat, validateAndCast, validateUserStatusAndPermissions };
1909
+ export { addAuditRecord, addLoginAudit, add_document, addressRegex, akeylessOnlineDomain, app, appCheck, auth, baseDomain, biDomain, calculateBearing, callCenterEventsDomain, callCenterGeoDomain, carsRegex, chartsRegex, checkUserPermissions, cleanNxSites, cn, collections, colorRegex, createSelectors, db, delete_document, devicesDomain, displayFormatPhoneNumber, durationToSeconds, emailRegex, extractAlertsData, extractBoardsData, extractCanbusData, extractCarsData, extractClientData, extractLocationData, extractSiteData, fire_base_TIME_TEMP, formatCarNumber, getAddressByGeo, getFixedNumber, getFormCheckboxValue, getFormElementValue, getLocationUrl, getUserByEmail, getUserByIdentifier, getUserByPhone, getUserCountryByIp, get_all_documents, get_document_by_id, get_international_phone_number, googleLoginProvider, handleChange, handleInvalid, handlePaste, initializeUserPermissions, international_israel_phone_format, isInternational, isInternationalIsraelPhone, isLocal, isNodeEnv, is_iccid, local_israel_phone_format, mode, multiStringFormat, notificationsDomain, numbersOnlyRegex, numbersRegex, nxApiCall, parseMultiSelectInput, parsePermissions, parseSnapshotAsArray, priceRegex, propsAreEqual, query_document, query_document_by_conditions, query_documents, query_documents_by_conditions, renderOnce, secondsToDuration, setFormElementValue, setState, set_document, simpleExtractData, snapshot, snapshotDocument, sort_by_timestamp, storage, textNumbersRegex, textRegex, timestamp_to_millis, timestamp_to_string, useLoginWithGoogle, useStoreValues, useValidation, userNameFormat, validateAndCast, validateUserStatusAndPermissions };
2239
1910
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["c:\\work\\akeyless\\commons\\client_commons\\dist\\helpers\\index.mjs"],"names":[],"mappings":"0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oCAA1B","sourcesContent":["// src/helpers/firebase.ts\nimport moment from \"moment\";\nimport { initializeApp } from \"firebase/app\";\nimport { getStorage } from \"firebase/storage\";\nimport { getAuth } from \"firebase/auth\";\nimport {\n addDoc,\n collection,\n deleteDoc,\n doc,\n getDoc,\n getDocs,\n query,\n setDoc,\n Timestamp,\n where,\n getFirestore,\n onSnapshot,\n orderBy\n} from \"firebase/firestore\";\n\n// src/helpers/cars.ts\nvar formatCarNumber = (car_number) => {\n var cn2 = car_number;\n if (cn2?.length == 8) return `${cn2[0]}${cn2[1]}${cn2[2]}-${cn2[3]}${cn2[4]}-${cn2[5]}${cn2[6]}${cn2[7]}`;\n if (cn2?.length == 7) return `${cn2[0]}${cn2[1]}-${cn2[2]}${cn2[3]}${cn2[4]}-${cn2[5]}${cn2[6]}`;\n if (cn2?.length == 6) return `${cn2[0]}${cn2[1]}-${cn2[2]}${cn2[3]}-${cn2[4]}${cn2[5]}`;\n if (cn2?.length == 5) return `${cn2[0]}-${cn2[1]}${cn2[2]}-${cn2[3]}${cn2[4]}`;\n return cn2;\n};\n\n// src/helpers/firebase.ts\nvar initApp = () => {\n const isNodeEnv2 = typeof process !== \"undefined\" && process.env;\n const firebaseConfig = {\n apiKey: isNodeEnv2 ? process.env.NEXT_PUBLIC_API_KEY : import.meta.env.VITE_API_KEY,\n authDomain: isNodeEnv2 ? process.env.NEXT_PUBLIC_AUTH_DOMAIN : import.meta.env.VITE_AUTH_DOMAIN,\n projectId: isNodeEnv2 ? process.env.NEXT_PUBLIC_PROJECT_ID : import.meta.env.VITE_PROJECT_ID,\n storageBucket: isNodeEnv2 ? process.env.NEXT_PUBLIC_STORAGE_BUCKET : import.meta.env.VITE_STORAGE_BUCKET,\n messagingSenderId: isNodeEnv2 ? process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID : import.meta.env.VITE_MESSAGING_SENDER_ID,\n appId: isNodeEnv2 ? process.env.NEXT_PUBLIC_APP_ID : import.meta.env.VITE_APP_ID\n };\n try {\n const app = initializeApp(firebaseConfig);\n const auth2 = getAuth(app);\n const db2 = getFirestore(app);\n const storage2 = getStorage(app);\n return { db: db2, auth: auth2, storage: storage2 };\n } catch (error) {\n console.error(\"Failed to initialize Firebase app:\", error);\n return {};\n }\n};\nvar { db, auth, storage } = initApp();\nvar collections = {\n clients: collection(db, \"nx-clients\"),\n sites: collection(db, \"nx-sites\"),\n cars: collection(db, \"units\"),\n users: collection(db, \"nx-users\"),\n lastLocations: collection(db, \"last_locations\"),\n ermEvents: collection(db, \"erm_events_general\"),\n erm2Events: collection(db, \"erm2_events_general\"),\n ruptelaEvents: collection(db, \"ruptela_events_general\"),\n polygons: collection(db, \"nx-polygons\"),\n polygonEvents: collection(db, \"polygon_events\"),\n polygonCars: collection(db, \"polygon_cars\"),\n canbus: collection(db, \"erm_canbus_parameters\"),\n states: collection(db, \"erm_states\"),\n app_pro_commands_queue: collection(db, \"app_pro_commands_queue\"),\n trips: collection(db, \"erm2_trip\"),\n tripsDetails: collection(db, \"erm2_trip_details\"),\n audit: collection(db, \"nx-audit\"),\n nx_settings: collection(db, \"nx-settings\"),\n settings: collection(db, \"settings\"),\n translations: collection(db, \"nx-translations\"),\n nx_cars: collection(db, \"nx-cars\"),\n boards: collection(db, \"boards\"),\n protection_types: collection(db, \"protectionTypes\"),\n board_types: collection(db, \"boardTypes\"),\n charge_capacities: collection(db, \"nx-charge-capacities\")\n};\nvar fire_base_TIME_TEMP = Timestamp.now;\nvar extractAlertsData = (doc2) => {\n const data = doc2.data();\n const { car_number, timestamp } = data;\n return {\n ...data,\n timestamp_seconds: timestamp.seconds,\n timestamp_ui: moment.unix(timestamp.seconds).format(\"DD/MM/YY HH:mm\"),\n car_number: formatCarNumber(car_number)\n };\n};\nvar simpleExtractData = (doc2) => {\n const docData = doc2.data();\n return {\n ...docData,\n id: doc2.id\n };\n};\nvar extractSiteData = (doc2) => {\n const data = doc2.data();\n const dateUpdated = new Date(data.updated?.seconds * 1e3 + data.updated.nanoseconds / 1e6);\n const dateCreated = new Date(data.created?.seconds * 1e3 + data.created.nanoseconds / 1e6);\n return {\n ...data,\n id: doc2.id,\n created: moment(dateCreated).format(\"DD.MM.YYYY - HH:mm\"),\n updated: moment(dateUpdated).format(\"DD.MM.YYYY - HH:mm\")\n };\n};\nvar extractClientData = (doc2) => {\n const data = doc2.data();\n const dateUpdated = new Date(data.updated?.seconds * 1e3 + data.updated.nanoseconds / 1e6);\n const dateCreated = new Date(data.created?.seconds * 1e3 + data.created.nanoseconds / 1e6);\n return {\n ...data,\n id: doc2.id,\n created: moment(dateCreated).format(\"HH:mm DD/MM/YY\"),\n updated: moment(dateUpdated).format(\"HH:mm DD/MM/YY\")\n };\n};\nvar extractBoardsData = (doc2) => {\n const data = doc2.data();\n const dateUploaded = typeof data.uploaded === \"string\" ? data.uploaded : moment.unix(data.uploaded?.seconds).format(\"DD/MM/YY HH:mm\");\n return {\n ...data,\n id: doc2.id,\n uploaded: dateUploaded\n };\n};\nvar extractCarsData = (doc2) => {\n const carData = doc2.data();\n let icon;\n const gov_info = carData.gov_info;\n if (gov_info) {\n if (carData.icon) {\n icon = carData.icon;\n } else if (gov_info.vehicle_type === \"atv\") {\n icon = \"truck\";\n } else if (gov_info.vehicle_type === \"motorcycle\") {\n icon = \"motorcycle\";\n } else {\n icon = \"car\";\n }\n } else {\n icon = \"car\";\n }\n return {\n ...carData,\n id: doc2.id,\n brand: carData.brand || carData.manufacturer,\n car_number: carData.carId,\n icon\n };\n};\nvar extractCanbusData = (doc2) => {\n const data = doc2.data();\n let newDate = null;\n if (data.timestamp && typeof data.timestamp.seconds === \"number\" && data.timestamp.seconds > 0) {\n newDate = new Date(data.timestamp.seconds * 1e3);\n }\n return {\n ...data,\n date_ui: newDate ? moment(newDate).format(\"DD/MM/YYYY - HH:mm\") : \"N/A\"\n };\n};\nvar extractLocationData = (doc2) => {\n const locationData = doc2.data();\n const { latitude, longitude, spd, timestamp, prev_latitude, prev_longitude } = locationData;\n return {\n ...locationData,\n id: doc2.id,\n lat: latitude,\n lng: longitude,\n prev_lat: prev_latitude,\n prev_lng: prev_longitude,\n timestamp: timestamp?.seconds,\n spd: Number(spd).toFixed(0)\n };\n};\nvar get_all_documents = async (collection_path) => {\n try {\n const snapshot2 = await getDocs(collection(db, collection_path));\n const documents = snapshot2.docs.map((doc2) => simpleExtractData(doc2));\n return documents;\n } catch (error) {\n return [];\n }\n};\nvar get_document_by_id = async (collection_path, doc_id) => {\n try {\n const doc_ref = doc(db, collection_path, doc_id);\n const doc_snap = await getDoc(doc_ref);\n if (!doc_snap.exists()) {\n throw new Error(\"Document not found, document id: \" + doc_id);\n }\n return simpleExtractData(doc_snap);\n } catch (error) {\n console.error(\"Error from get_document_by_id\", error);\n return null;\n }\n};\nvar set_document = async (collection_path, doc_id, data) => {\n try {\n const doc_ref = doc(db, collection_path, doc_id);\n await setDoc(doc_ref, data, { merge: true });\n return true;\n } catch (error) {\n console.error(`Failed to create document by id: ${doc_id} in collection: ${collection_path}`, { error, data });\n return false;\n }\n};\nvar add_document = async (collection_path, data, include_id = false) => {\n try {\n const col_ref = collection(db, collection_path);\n const doc_ref = await addDoc(col_ref, data);\n if (include_id) {\n await setDoc(doc_ref, { ...data, id: doc_ref.id }, { merge: true });\n }\n return true;\n } catch (error) {\n console.error(`Failed to create document in collection: ${collection_path}`, error);\n return false;\n }\n};\nvar delete_document = async (collection_path, doc_id) => {\n try {\n const doc_ref = doc(db, collection_path, doc_id);\n await deleteDoc(doc_ref);\n return true;\n } catch (error) {\n console.error(`Failed to delete document with id ${doc_id} from collection ${collection_path}`, error);\n return false;\n }\n};\nvar query_document = async (collection_path, field_name, operator, value, ignore_log = false) => {\n try {\n const q = query(collection(db, collection_path), where(field_name, operator, value));\n const query_snapshot = await getDocs(q);\n const documents = query_snapshot.docs.map((doc2) => simpleExtractData(doc2));\n if (documents.length < 1) {\n throw new Error(\n `No data to return from: \ncollection: ${collection_path}, \nfield_name: ${field_name}, \noperator: ${operator}, \nvalue: ${value}`\n );\n }\n return documents[0];\n } catch (error) {\n if (!ignore_log) {\n console.error(\"Error querying document:\", error);\n }\n return null;\n }\n};\nvar query_documents = async (collection_path, field_name, operator, value) => {\n try {\n const q = query(collection(db, collection_path), where(field_name, operator, value));\n const query_snapshot = await getDocs(q);\n const documents = query_snapshot.docs.map((doc2) => simpleExtractData(doc2));\n return documents;\n } catch (error) {\n console.error(`Error querying documents: ${collection_path} - ${field_name} - ${operator} - ${value} `, error);\n return [];\n }\n};\nvar query_documents_by_conditions = async (collection_path, where_conditions) => {\n try {\n let db_query = collection(db, collection_path);\n where_conditions.forEach((condition) => {\n db_query = query(db_query, where(condition.field_name, condition.operator, condition.value));\n });\n const query_snapshot = await getDocs(db_query);\n const documents = query_snapshot.docs.map((doc2) => simpleExtractData(doc2));\n return documents;\n } catch (error) {\n console.error(`Error querying documents: ${collection_path} - ${JSON.stringify(where_conditions)} `, error);\n return [];\n }\n};\nvar query_document_by_conditions = async (collection_path, where_conditions) => {\n try {\n let db_query = collection(db, collection_path);\n where_conditions.forEach((condition) => {\n db_query = query(db_query, where(condition.field_name, condition.operator, condition.value));\n });\n const query_snapshot = await getDocs(db_query);\n const documents = query_snapshot.docs.map((doc2) => simpleExtractData(doc2));\n if (!documents[0]) {\n throw new Error(\"No data returned from DB\");\n }\n return documents[0];\n } catch (error) {\n console.error(`Error querying documents: ${collection_path} - ${JSON.stringify(where_conditions)} `, error);\n return null;\n }\n};\nvar snapshot = (config, snapshotsFirstTime) => {\n let resolvePromise;\n let isResolved = false;\n const promise = new Promise((resolve) => {\n console.log(`==> ${config.collectionName} subscribed.`);\n resolvePromise = () => {\n if (!isResolved) {\n isResolved = true;\n resolve();\n }\n };\n });\n let collectionRef = collection(db, config.collectionName);\n if (config.conditions) {\n config.conditions.forEach((condition) => {\n collectionRef = query(collectionRef, where(condition.field_name, condition.operator, condition.value));\n });\n }\n if (config.orderBy) {\n config.orderBy.forEach((order) => {\n collectionRef = query(collectionRef, orderBy(order.fieldName, order.direction));\n });\n }\n const unsubscribe = onSnapshot(\n collectionRef,\n (snapshot2) => {\n if (!snapshotsFirstTime.includes(config.collectionName)) {\n snapshotsFirstTime.push(config.collectionName);\n const documents = snapshot2.docs.map((doc2) => simpleExtractData(doc2));\n config.onFirstTime?.(documents, config);\n config.extraParsers?.forEach((extraParser) => {\n extraParser.onFirstTime?.(documents, config);\n });\n resolvePromise();\n } else {\n const addedDocs = [];\n const modifiedDocs = [];\n const removedDocs = [];\n snapshot2.docChanges().forEach((change) => {\n if (change.type === \"added\") {\n addedDocs.push(simpleExtractData(change.doc));\n } else if (change.type === \"modified\") {\n modifiedDocs.push(simpleExtractData(change.doc));\n } else if (change.type === \"removed\") {\n removedDocs.push(simpleExtractData(change.doc));\n }\n });\n addedDocs.length && config.onAdd?.(addedDocs, config);\n modifiedDocs.length && config.onModify?.(modifiedDocs, config);\n removedDocs.length && config.onRemove?.(removedDocs, config);\n config.extraParsers?.forEach((extraParser) => {\n addedDocs.length && extraParser.onAdd?.(addedDocs, config);\n modifiedDocs.length && extraParser.onModify?.(modifiedDocs, config);\n removedDocs.length && extraParser.onRemove?.(removedDocs, config);\n });\n }\n },\n (error) => {\n console.error(`Error listening to collection: ${config.collectionName}`, error);\n resolvePromise();\n }\n );\n return { promise, unsubscribe };\n};\nvar snapshotDocument = (config, snapshotsFirstTime) => {\n let resolvePromise;\n let isResolved = false;\n const promise = new Promise((resolve) => {\n console.log(`==> Document in ${config.collectionName} subscribed.`);\n resolvePromise = () => {\n if (!isResolved) {\n isResolved = true;\n resolve();\n }\n };\n });\n const documentRef = doc(db, config.collectionName, config.documentId);\n const unsubscribe = onSnapshot(\n documentRef,\n (docSnapshot) => {\n if (!snapshotsFirstTime.includes(config.collectionName)) {\n snapshotsFirstTime.push(config.collectionName);\n if (docSnapshot.exists()) {\n const document2 = simpleExtractData(docSnapshot);\n if (checkConditions(document2, config.conditions)) {\n config.onFirstTime?.([document2], config);\n config.extraParsers?.forEach((extraParser) => {\n extraParser.onFirstTime?.([document2], config);\n });\n } else {\n console.warn(`Document in ${config.collectionName} does not meet conditions.`);\n }\n } else {\n console.warn(`Document not found in ${config.collectionName}.`);\n }\n resolvePromise();\n } else {\n if (docSnapshot.exists()) {\n const document2 = simpleExtractData(docSnapshot);\n if (checkConditions(document2, config.conditions)) {\n config.onModify?.([document2], config);\n config.extraParsers?.forEach((extraParser) => {\n extraParser.onModify?.([document2], config);\n });\n }\n } else {\n config.onRemove?.([], config);\n config.extraParsers?.forEach((extraParser) => {\n extraParser.onRemove?.([], config);\n });\n }\n }\n },\n (error) => {\n console.error(`Error listening to document in ${config.collectionName}:`, error);\n resolvePromise();\n }\n );\n return { promise, unsubscribe };\n};\nvar checkConditions = (document2, conditions) => {\n if (!conditions || conditions.length === 0) return true;\n return conditions.every((condition) => {\n const fieldValue = document2[condition.field_name];\n switch (condition.operator) {\n case \"==\":\n return fieldValue === condition.value;\n case \"!=\":\n return fieldValue !== condition.value;\n case \"<\":\n return fieldValue < condition.value;\n case \"<=\":\n return fieldValue <= condition.value;\n case \">\":\n return fieldValue > condition.value;\n case \">=\":\n return fieldValue >= condition.value;\n case \"array-contains\":\n return Array.isArray(fieldValue) && fieldValue.includes(condition.value);\n default:\n return false;\n }\n });\n};\nvar cleanNxSites = async () => {\n const clients = (await get_all_documents(\"nx-clients\")).map((v) => v.id);\n const sites = await get_all_documents(\"nx-sites\");\n const allSitesToDelete = sites.filter((v) => !clients.includes(v.client));\n console.log(\"allSitesToDelete\", allSitesToDelete);\n allSitesToDelete.forEach(async (v) => {\n await delete_document(\"nx-sites\", v.id);\n console.log(`Site ${v.id} deleted.`);\n });\n};\n\n// src/helpers/global.ts\nimport { CountryOptions } from \"akeyless-types-commons\";\nimport axios from \"axios\";\n\n// src/helpers/phoneNumber.ts\nimport { parsePhoneNumberFromString } from \"libphonenumber-js\";\nvar isInternational = (phone_number) => {\n return phone_number.startsWith(\"+\");\n};\nvar isInternationalIsraelPhone = (phone_number) => {\n return phone_number.startsWith(\"+9725\");\n};\nvar local_israel_phone_format = (international_number) => {\n return international_number.replace(\"+972\", \"0\");\n};\nvar international_israel_phone_format = (phone) => {\n const validNumber = phone.slice(1, phone.length);\n return \"+972\".concat(validNumber);\n};\nvar displayFormatPhoneNumber = (phoneNumber) => {\n if (isInternational(phoneNumber)) {\n const phoneNumberObject = parsePhoneNumberFromString(phoneNumber);\n if (!phoneNumberObject) {\n return phoneNumber;\n }\n return phoneNumberObject.formatInternational().replace(/\\s/g, \"\");\n }\n return phoneNumber.replace(/(\\d{3})(\\d{3})(\\d{4})/, \"$1-$2-$3\");\n};\nvar is_iccid = (number) => {\n if (number.length < 19 || number.length > 22) return false;\n if (!/^\\d+$/.test(number)) return false;\n if (!number.startsWith(\"89\")) return false;\n return true;\n};\n\n// src/helpers/global.ts\nimport { isEqual } from \"lodash\";\nvar calculateBearing = (startLat, startLng, endLat, endLng) => {\n if (startLat === endLat || startLng === endLng) {\n return 0;\n }\n if (startLat === void 0 || startLng === void 0 || endLat === void 0 || endLng === void 0) {\n return 0;\n }\n const startLatRad = startLat * Math.PI / 180;\n const startLngRad = startLng * Math.PI / 180;\n const endLatRad = endLat * Math.PI / 180;\n const endLngRad = endLng * Math.PI / 180;\n const dLon = endLngRad - startLngRad;\n const y = Math.sin(dLon) * Math.cos(endLatRad);\n const x = Math.cos(startLatRad) * Math.sin(endLatRad) - Math.sin(startLatRad) * Math.cos(endLatRad) * Math.cos(dLon);\n const bearing = Math.atan2(y, x) * 180 / Math.PI;\n return (bearing + 360) % 360;\n};\nvar renderOnce = () => {\n return true;\n};\nvar propsAreEqual = (prevProps, nextProps) => {\n return isEqual(prevProps, nextProps);\n};\nvar getUserCountryByIp = async () => {\n try {\n const response = await axios.get(\"https://ipapi.co/json/\");\n return (response.data.country_code || CountryOptions.IL).toLowerCase();\n } catch (error) {\n console.error(\"Error fetching Country:\", error);\n return CountryOptions.IL;\n }\n};\nvar parsePermissions = (object) => {\n if (!object?.features) {\n return {};\n }\n const features = object.features;\n let result = {};\n features.forEach((feature) => {\n if (!feature.includes(\"__\")) {\n return;\n }\n const [featureType, featureName] = feature.split(\"__\");\n if (!featureType || !featureName) {\n return;\n }\n if (!result[featureType]) {\n result[featureType] = {};\n }\n result[featureType][featureName] = true;\n });\n return result;\n};\nvar initializeUserPermissions = async ({ phoneNumber, firstTimeArray, getUpdatePermissions }) => {\n let unsubscribe = null;\n let permissions = {};\n try {\n const { promise, unsubscribe: unsubscribeSnapshot } = snapshot(\n {\n collectionName: \"nx-users\",\n conditions: [{ field_name: \"phone_number\", operator: \"in\", value: [phoneNumber, local_israel_phone_format(phoneNumber)] }],\n onFirstTime: (docs) => {\n if (!docs.length) {\n throw new Error(\"User not found\");\n }\n permissions = parsePermissions(docs[0]);\n getUpdatePermissions(parsePermissions(docs[0]));\n },\n onModify: (docs) => {\n getUpdatePermissions(parsePermissions(docs[0]));\n }\n },\n firstTimeArray\n );\n unsubscribe = unsubscribeSnapshot;\n await promise;\n return { unsubscribe, permissions };\n } catch (error) {\n if (unsubscribe) {\n unsubscribe();\n }\n console.error(\"Error initializing user permissions:\", error.message);\n throw error;\n }\n};\nvar userNameFormat = (user) => {\n return `${user?.first_name || \"\"} ${user?.last_name || \"\"}`.trim();\n};\nvar multiStringFormat = (str1, str2, str3) => {\n return `${str1} ${str2 || \"\"} ${str3 || \"\"}`.trim();\n};\nvar getLocationUrl = (lang, lat) => {\n return `https://www.google.com/maps?q=${lang},${lat}`;\n};\nvar isNodeEnv = typeof process !== \"undefined\" && process.env;\nvar { mode, isLocal } = {\n mode: isNodeEnv ? process.env.NEXT_PUBLIC_MODE : import.meta.env.VITE_MODE,\n isLocal: (isNodeEnv ? process.env.NEXT_PUBLIC_IS_LOCAL : import.meta.env.VITE_is_local) === \"true\"\n};\n\n// src/helpers/forms.ts\nimport XRegExp from \"xregexp\";\nvar textRegex = XRegExp(\"[^\\\\p{L}\\\\s-]\", \"gu\");\nvar numbersRegex = XRegExp(\"[^0-9\\\\s-+]\", \"g\");\nvar numbersOnlyRegex = XRegExp(\"[^0-9]\", \"g\");\nvar priceRegex = XRegExp(\"[^0-9.]\", \"g\");\nvar emailRegex = XRegExp(\"[^\\\\p{L}0-9.@\\\\s-]\", \"gu\");\nvar colorRegex = XRegExp(\"[^#0-9A-Fa-f]\", \"g\");\nvar carsRegex = XRegExp(\"[^\\\\p{L}0-9,_]\", \"gu\");\nvar textNumbersRegex = XRegExp(\"[^\\\\p{L}0-9\\\\s+\\\\-]\", \"gu\");\nvar addressRegex = XRegExp(\"[^\\\\p{L}0-9\\\\s.,+-\\\\-]\", \"gu\");\nvar chartsRegex = XRegExp(\"[^\\\\p{L}0-9\\\\s.,_@!+-\\\\-]\", \"gu\");\nvar handleChange = (e) => {\n e.target.setCustomValidity(\"\");\n const validation = e.target.getAttribute(\"data-validation\");\n if (validation === \"text\") {\n e.target.value = XRegExp.replace(e.target.value, textRegex, \"\");\n } else if (validation === \"numbers\") {\n e.target.value = XRegExp.replace(e.target.value, numbersRegex, \"\");\n } else if (validation === \"numbersOnly\") {\n e.target.value = XRegExp.replace(e.target.value, numbersOnlyRegex, \"\");\n } else if (validation === \"price\") {\n e.target.value = XRegExp.replace(e.target.value, priceRegex, \"\");\n } else if (validation === \"textNumbers\") {\n e.target.value = XRegExp.replace(e.target.value, textNumbersRegex, \"\");\n } else if (validation === \"email\") {\n e.target.value = XRegExp.replace(e.target.value, emailRegex, \"\");\n } else if (validation === \"color\") {\n e.target.value = XRegExp.replace(e.target.value, colorRegex, \"\");\n } else if (validation === \"address\") {\n e.target.value = XRegExp.replace(e.target.value, addressRegex, \"\");\n } else if (validation === \"cars\") {\n e.target.value = XRegExp.replace(e.target.value, carsRegex, \"\");\n } else if (validation === \"charts\") {\n e.target.value = XRegExp.replace(e.target.value, chartsRegex, \"\");\n }\n};\nvar handlePaste = (e) => {\n const validation = e.currentTarget.getAttribute(\"data-validation\");\n let pasteData = e.clipboardData.getData(\"text\");\n if (validation === \"text\") {\n pasteData = XRegExp.replace(pasteData, textRegex, \"\");\n } else if (validation === \"numbers\") {\n pasteData = XRegExp.replace(pasteData, numbersRegex, \"\");\n } else if (validation === \"numbersOnly\") {\n pasteData = XRegExp.replace(pasteData, numbersOnlyRegex, \"\");\n } else if (validation === \"price\") {\n pasteData = XRegExp.replace(pasteData, priceRegex, \"\");\n } else if (validation === \"textNumbers\") {\n pasteData = XRegExp.replace(pasteData, textNumbersRegex, \"\");\n } else if (validation === \"email\") {\n pasteData = XRegExp.replace(pasteData, emailRegex, \"\");\n } else if (validation === \"color\") {\n pasteData = XRegExp.replace(pasteData, colorRegex, \"\");\n } else if (validation === \"address\") {\n pasteData = XRegExp.replace(pasteData, addressRegex, \"\");\n } else if (validation === \"cars\") {\n pasteData = XRegExp.replace(pasteData, carsRegex, \"\");\n } else if (validation === \"charts\") {\n pasteData = XRegExp.replace(pasteData, chartsRegex, \"\");\n }\n e.preventDefault();\n document.execCommand(\"insertText\", false, pasteData);\n};\nvar handleInvalid = (e, requireError) => {\n e.target.setCustomValidity(requireError || \"This filed is required !\");\n};\nvar useValidation = (validationType, requireError) => {\n return {\n onChange: handleChange,\n onPaste: handlePaste,\n onInvalid: (e) => handleInvalid(e, requireError),\n \"data-validation\": validationType\n };\n};\nvar getFormElementValue = (form, name) => {\n return form.elements.namedItem(name)?.value || \"\";\n};\nvar parseMultiSelectInput = (input) => {\n const value = JSON.parse(input) || [];\n return value.map((v) => v.value);\n};\n\n// src/helpers/store.ts\nvar setState = (updater, set, stateName) => {\n return set((state) => ({\n [stateName]: typeof updater === \"function\" ? updater(state[stateName]) : updater\n }));\n};\nvar createSelectors = (store) => {\n let selectors = {};\n for (let k of Object.keys(store.getState())) {\n selectors[k] = () => store((s) => s[k]);\n }\n return selectors;\n};\nvar useStoreValues = (store, keys) => {\n const result = {};\n keys.forEach((key) => {\n result[key] = store.use[key]();\n });\n return result;\n};\n\n// src/lib/utils.ts\nimport { clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\nfunction cn(...inputs) {\n return twMerge(clsx(inputs));\n}\n\n// src/helpers/time_helpers.ts\nimport { Timestamp as Timestamp2 } from \"firebase/firestore\";\nimport moment2 from \"moment-timezone\";\nfunction timestamp_to_string(firebaseTimestamp, options) {\n let date;\n if (firebaseTimestamp instanceof Timestamp2) {\n date = firebaseTimestamp.toDate();\n } else if (firebaseTimestamp instanceof Date) {\n date = firebaseTimestamp;\n } else if (typeof firebaseTimestamp === \"string\") {\n date = moment2.utc(firebaseTimestamp, options?.fromFormat || \"DD/MM/YYYY HH:mm:ss\").toDate();\n if (isNaN(date.getTime())) {\n throw new Error(\"Invalid date string format\");\n }\n } else {\n throw new Error(\"Invalid input: firebaseTimestamp must be a Timestamp, Date, or valid date string.\");\n }\n if (options?.tz) {\n const result = moment2(date).tz(options?.tz).format(options?.format || \"DD/MM/YYYY HH:mm:ss\");\n return result;\n }\n return moment2.utc(date).format(options?.format || \"DD/MM/YYYY HH:mm:ss\");\n}\nfunction timestamp_to_millis(firebaseTimestamp) {\n const timestamp = new Timestamp2(firebaseTimestamp?.seconds, firebaseTimestamp?.nanoseconds);\n return timestamp.toMillis();\n}\nfunction sort_by_timestamp(a, b, reverse = false) {\n return reverse ? timestamp_to_millis(b) - timestamp_to_millis(a) : timestamp_to_millis(a) - timestamp_to_millis(b);\n}\n\n// src/helpers/api.ts\nimport axios2 from \"axios\";\nvar baseDomain = mode === \"qa\" ? \"https://nx-api.xyz/api\" : \"https://nx-api.info/api\";\nvar devicesDomain = isLocal ? \"http://localhost:9001/api/devices\" : baseDomain + \"/devices\";\nvar biDomain = isLocal ? \"http://localhost:9002/api/bi\" : baseDomain + \"/bi\";\nvar callCenterDomain = isLocal ? \"http://localhost:9003/api/call-center\" : baseDomain + \"/call-center\";\nvar akeylessOnlineDomain = mode === \"qa\" ? \"https://akeyless-online.xyz\" : \"https://akeyless-online.info\";\nvar nx_api_call = async (serverName, method, url, data) => {\n try {\n let urlResult = `${devicesDomain}/${url}`;\n switch (serverName) {\n case \"bi\":\n urlResult = `${biDomain}/${url}`;\n break;\n case \"devices\":\n urlResult = `${devicesDomain}/${url}`;\n break;\n case \"call-center\":\n urlResult = `${callCenterDomain}/${url}`;\n break;\n default:\n break;\n }\n const headers = {\n authorization: \"bearer \" + await auth.currentUser.getIdToken()\n };\n const response = await axios2({\n method,\n url: urlResult,\n headers,\n data\n });\n return response.data || null;\n } catch (error) {\n console.error(`Error from nx_api_call: ${JSON.stringify({ serverName, method, url, data })}`, error?.response?.data || error);\n return null;\n }\n};\nexport {\n add_document,\n addressRegex,\n akeylessOnlineDomain,\n auth,\n baseDomain,\n biDomain,\n calculateBearing,\n callCenterDomain,\n carsRegex,\n chartsRegex,\n cleanNxSites,\n cn,\n collections,\n colorRegex,\n createSelectors,\n db,\n delete_document,\n devicesDomain,\n displayFormatPhoneNumber,\n emailRegex,\n extractAlertsData,\n extractBoardsData,\n extractCanbusData,\n extractCarsData,\n extractClientData,\n extractLocationData,\n extractSiteData,\n fire_base_TIME_TEMP,\n formatCarNumber,\n getFormElementValue,\n getLocationUrl,\n getUserCountryByIp,\n get_all_documents,\n get_document_by_id,\n handleChange,\n handleInvalid,\n handlePaste,\n initializeUserPermissions,\n international_israel_phone_format,\n isInternational,\n isInternationalIsraelPhone,\n isLocal,\n isNodeEnv,\n is_iccid,\n local_israel_phone_format,\n mode,\n multiStringFormat,\n numbersOnlyRegex,\n numbersRegex,\n nx_api_call,\n parseMultiSelectInput,\n parsePermissions,\n priceRegex,\n propsAreEqual,\n query_document,\n query_document_by_conditions,\n query_documents,\n query_documents_by_conditions,\n renderOnce,\n setState,\n set_document,\n simpleExtractData,\n snapshot,\n snapshotDocument,\n sort_by_timestamp,\n storage,\n textNumbersRegex,\n textRegex,\n timestamp_to_millis,\n timestamp_to_string,\n useStoreValues,\n useValidation,\n userNameFormat\n};\n"]}
1
+ {"version":3,"sources":["c:\\work\\akeyless\\commons\\client_commons\\dist\\helpers\\index.mjs"],"names":[],"mappings":"0BAA0B","sourcesContent":["// src/helpers/firebase.ts\nimport moment from \"moment\";\nimport { initializeApp } from \"firebase/app\";\nimport { getStorage } from \"firebase/storage\";\nimport { getAuth } from \"firebase/auth\";\nimport {\n addDoc,\n collection,\n deleteDoc,\n doc,\n getDoc,\n getDocs,\n query,\n setDoc,\n Timestamp,\n where,\n getFirestore,\n onSnapshot,\n orderBy\n} from \"firebase/firestore\";\n\n// src/helpers/cars.ts\nvar formatCarNumber = (car_number) => {\n var cn2 = car_number;\n if (cn2?.length == 8) return `${cn2[0]}${cn2[1]}${cn2[2]}-${cn2[3]}${cn2[4]}-${cn2[5]}${cn2[6]}${cn2[7]}`;\n if (cn2?.length == 7) return `${cn2[0]}${cn2[1]}-${cn2[2]}${cn2[3]}${cn2[4]}-${cn2[5]}${cn2[6]}`;\n if (cn2?.length == 6) return `${cn2[0]}${cn2[1]}-${cn2[2]}${cn2[3]}-${cn2[4]}${cn2[5]}`;\n if (cn2?.length == 5) return `${cn2[0]}-${cn2[1]}${cn2[2]}-${cn2[3]}${cn2[4]}`;\n return cn2;\n};\n\n// src/helpers/firebase.ts\nvar initApp = () => {\n const isNodeEnv2 = typeof process !== \"undefined\" && process.env;\n const firebaseConfig = {\n apiKey: isNodeEnv2 ? process.env.NEXT_PUBLIC_API_KEY : import.meta.env.VITE_API_KEY,\n authDomain: isNodeEnv2 ? process.env.NEXT_PUBLIC_AUTH_DOMAIN : import.meta.env.VITE_AUTH_DOMAIN,\n projectId: isNodeEnv2 ? process.env.NEXT_PUBLIC_PROJECT_ID : import.meta.env.VITE_PROJECT_ID,\n storageBucket: isNodeEnv2 ? process.env.NEXT_PUBLIC_STORAGE_BUCKET : import.meta.env.VITE_STORAGE_BUCKET,\n messagingSenderId: isNodeEnv2 ? process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID : import.meta.env.VITE_MESSAGING_SENDER_ID,\n appId: isNodeEnv2 ? process.env.NEXT_PUBLIC_APP_ID : import.meta.env.VITE_APP_ID\n };\n try {\n const app = initializeApp(firebaseConfig);\n const auth2 = getAuth(app);\n const db2 = getFirestore(app);\n const storage2 = getStorage(app);\n return { db: db2, auth: auth2, storage: storage2 };\n } catch (error) {\n console.error(\"Failed to initialize Firebase app:\", error);\n return {};\n }\n};\nvar { db, auth, storage } = initApp();\nvar collections = {\n clients: collection(db, \"nx-clients\"),\n sites: collection(db, \"nx-sites\"),\n cars: collection(db, \"units\"),\n users: collection(db, \"nx-users\"),\n lastLocations: collection(db, \"last_locations\"),\n ermEvents: collection(db, \"erm_events_general\"),\n erm2Events: collection(db, \"erm2_events_general\"),\n ruptelaEvents: collection(db, \"ruptela_events_general\"),\n polygons: collection(db, \"nx-polygons\"),\n polygonEvents: collection(db, \"polygon_events\"),\n polygonCars: collection(db, \"polygon_cars\"),\n canbus: collection(db, \"erm_canbus_parameters\"),\n states: collection(db, \"erm_states\"),\n app_pro_commands_queue: collection(db, \"app_pro_commands_queue\"),\n trips: collection(db, \"erm2_trip\"),\n tripsDetails: collection(db, \"erm2_trip_details\"),\n audit: collection(db, \"nx-audit\"),\n nx_settings: collection(db, \"nx-settings\"),\n settings: collection(db, \"settings\"),\n translations: collection(db, \"nx-translations\"),\n nx_cars: collection(db, \"nx-cars\"),\n boards: collection(db, \"boards\"),\n protection_types: collection(db, \"protectionTypes\"),\n board_types: collection(db, \"boardTypes\"),\n charge_capacities: collection(db, \"nx-charge-capacities\")\n};\nvar fire_base_TIME_TEMP = Timestamp.now;\nvar extractAlertsData = (doc2) => {\n const data = doc2.data();\n const { car_number, timestamp } = data;\n return {\n ...data,\n timestamp_seconds: timestamp.seconds,\n timestamp_ui: moment.unix(timestamp.seconds).format(\"DD/MM/YY HH:mm\"),\n car_number: formatCarNumber(car_number)\n };\n};\nvar simpleExtractData = (doc2) => {\n const docData = doc2.data();\n return {\n ...docData,\n id: doc2.id\n };\n};\nvar extractSiteData = (doc2) => {\n const data = doc2.data();\n const dateUpdated = new Date(data.updated?.seconds * 1e3 + data.updated.nanoseconds / 1e6);\n const dateCreated = new Date(data.created?.seconds * 1e3 + data.created.nanoseconds / 1e6);\n return {\n ...data,\n id: doc2.id,\n created: moment(dateCreated).format(\"DD.MM.YYYY - HH:mm\"),\n updated: moment(dateUpdated).format(\"DD.MM.YYYY - HH:mm\")\n };\n};\nvar extractClientData = (doc2) => {\n const data = doc2.data();\n const dateUpdated = new Date(data.updated?.seconds * 1e3 + data.updated.nanoseconds / 1e6);\n const dateCreated = new Date(data.created?.seconds * 1e3 + data.created.nanoseconds / 1e6);\n return {\n ...data,\n id: doc2.id,\n created: moment(dateCreated).format(\"HH:mm DD/MM/YY\"),\n updated: moment(dateUpdated).format(\"HH:mm DD/MM/YY\")\n };\n};\nvar extractBoardsData = (doc2) => {\n const data = doc2.data();\n const dateUploaded = typeof data.uploaded === \"string\" ? data.uploaded : moment.unix(data.uploaded?.seconds).format(\"DD/MM/YY HH:mm\");\n return {\n ...data,\n id: doc2.id,\n uploaded: dateUploaded\n };\n};\nvar extractCarsData = (doc2) => {\n const carData = doc2.data();\n let icon;\n const gov_info = carData.gov_info;\n if (gov_info) {\n if (carData.icon) {\n icon = carData.icon;\n } else if (gov_info.vehicle_type === \"atv\") {\n icon = \"truck\";\n } else if (gov_info.vehicle_type === \"motorcycle\") {\n icon = \"motorcycle\";\n } else {\n icon = \"car\";\n }\n } else {\n icon = \"car\";\n }\n return {\n ...carData,\n id: doc2.id,\n brand: carData.brand || carData.manufacturer,\n car_number: carData.carId,\n icon\n };\n};\nvar extractCanbusData = (doc2) => {\n const data = doc2.data();\n let newDate = null;\n if (data.timestamp && typeof data.timestamp.seconds === \"number\" && data.timestamp.seconds > 0) {\n newDate = new Date(data.timestamp.seconds * 1e3);\n }\n return {\n ...data,\n date_ui: newDate ? moment(newDate).format(\"DD/MM/YYYY - HH:mm\") : \"N/A\"\n };\n};\nvar extractLocationData = (doc2) => {\n const locationData = doc2.data();\n const { latitude, longitude, spd, timestamp, prev_latitude, prev_longitude } = locationData;\n return {\n ...locationData,\n id: doc2.id,\n lat: latitude,\n lng: longitude,\n prev_lat: prev_latitude,\n prev_lng: prev_longitude,\n timestamp: timestamp?.seconds,\n spd: Number(spd).toFixed(0)\n };\n};\nvar get_all_documents = async (collection_path) => {\n try {\n const snapshot2 = await getDocs(collection(db, collection_path));\n const documents = snapshot2.docs.map((doc2) => simpleExtractData(doc2));\n return documents;\n } catch (error) {\n return [];\n }\n};\nvar get_document_by_id = async (collection_path, doc_id) => {\n try {\n const doc_ref = doc(db, collection_path, doc_id);\n const doc_snap = await getDoc(doc_ref);\n if (!doc_snap.exists()) {\n throw new Error(\"Document not found, document id: \" + doc_id);\n }\n return simpleExtractData(doc_snap);\n } catch (error) {\n console.error(\"Error from get_document_by_id\", error);\n return null;\n }\n};\nvar set_document = async (collection_path, doc_id, data) => {\n try {\n const doc_ref = doc(db, collection_path, doc_id);\n await setDoc(doc_ref, data, { merge: true });\n return true;\n } catch (error) {\n console.error(`Failed to create document by id: ${doc_id} in collection: ${collection_path}`, { error, data });\n return false;\n }\n};\nvar add_document = async (collection_path, data, include_id = false) => {\n try {\n const col_ref = collection(db, collection_path);\n const doc_ref = await addDoc(col_ref, data);\n if (include_id) {\n await setDoc(doc_ref, { ...data, id: doc_ref.id }, { merge: true });\n }\n return true;\n } catch (error) {\n console.error(`Failed to create document in collection: ${collection_path}`, error);\n return false;\n }\n};\nvar delete_document = async (collection_path, doc_id) => {\n try {\n const doc_ref = doc(db, collection_path, doc_id);\n await deleteDoc(doc_ref);\n return true;\n } catch (error) {\n console.error(`Failed to delete document with id ${doc_id} from collection ${collection_path}`, error);\n return false;\n }\n};\nvar query_document = async (collection_path, field_name, operator, value, ignore_log = false) => {\n try {\n const q = query(collection(db, collection_path), where(field_name, operator, value));\n const query_snapshot = await getDocs(q);\n const documents = query_snapshot.docs.map((doc2) => simpleExtractData(doc2));\n if (documents.length < 1) {\n throw new Error(\n `No data to return from: \ncollection: ${collection_path}, \nfield_name: ${field_name}, \noperator: ${operator}, \nvalue: ${value}`\n );\n }\n return documents[0];\n } catch (error) {\n if (!ignore_log) {\n console.error(\"Error querying document:\", error);\n }\n return null;\n }\n};\nvar query_documents = async (collection_path, field_name, operator, value) => {\n try {\n const q = query(collection(db, collection_path), where(field_name, operator, value));\n const query_snapshot = await getDocs(q);\n const documents = query_snapshot.docs.map((doc2) => simpleExtractData(doc2));\n return documents;\n } catch (error) {\n console.error(`Error querying documents: ${collection_path} - ${field_name} - ${operator} - ${value} `, error);\n return [];\n }\n};\nvar query_documents_by_conditions = async (collection_path, where_conditions) => {\n try {\n let db_query = collection(db, collection_path);\n where_conditions.forEach((condition) => {\n db_query = query(db_query, where(condition.field_name, condition.operator, condition.value));\n });\n const query_snapshot = await getDocs(db_query);\n const documents = query_snapshot.docs.map((doc2) => simpleExtractData(doc2));\n return documents;\n } catch (error) {\n console.error(`Error querying documents: ${collection_path} - ${JSON.stringify(where_conditions)} `, error);\n return [];\n }\n};\nvar query_document_by_conditions = async (collection_path, where_conditions) => {\n try {\n let db_query = collection(db, collection_path);\n where_conditions.forEach((condition) => {\n db_query = query(db_query, where(condition.field_name, condition.operator, condition.value));\n });\n const query_snapshot = await getDocs(db_query);\n const documents = query_snapshot.docs.map((doc2) => simpleExtractData(doc2));\n if (!documents[0]) {\n throw new Error(\"No data returned from DB\");\n }\n return documents[0];\n } catch (error) {\n console.error(`Error querying documents: ${collection_path} - ${JSON.stringify(where_conditions)} `, error);\n return null;\n }\n};\nvar snapshot = (config, snapshotsFirstTime) => {\n let resolvePromise;\n let isResolved = false;\n const promise = new Promise((resolve) => {\n console.log(`==> ${config.collectionName} subscribed.`);\n resolvePromise = () => {\n if (!isResolved) {\n isResolved = true;\n resolve();\n }\n };\n });\n let collectionRef = collection(db, config.collectionName);\n if (config.conditions) {\n config.conditions.forEach((condition) => {\n collectionRef = query(collectionRef, where(condition.field_name, condition.operator, condition.value));\n });\n }\n if (config.orderBy) {\n config.orderBy.forEach((order) => {\n collectionRef = query(collectionRef, orderBy(order.fieldName, order.direction));\n });\n }\n const unsubscribe = onSnapshot(\n collectionRef,\n (snapshot2) => {\n if (!snapshotsFirstTime.includes(config.collectionName)) {\n snapshotsFirstTime.push(config.collectionName);\n const documents = snapshot2.docs.map((doc2) => simpleExtractData(doc2));\n config.onFirstTime?.(documents, config);\n config.extraParsers?.forEach((extraParser) => {\n extraParser.onFirstTime?.(documents, config);\n });\n resolvePromise();\n } else {\n const addedDocs = [];\n const modifiedDocs = [];\n const removedDocs = [];\n snapshot2.docChanges().forEach((change) => {\n if (change.type === \"added\") {\n addedDocs.push(simpleExtractData(change.doc));\n } else if (change.type === \"modified\") {\n modifiedDocs.push(simpleExtractData(change.doc));\n } else if (change.type === \"removed\") {\n removedDocs.push(simpleExtractData(change.doc));\n }\n });\n addedDocs.length && config.onAdd?.(addedDocs, config);\n modifiedDocs.length && config.onModify?.(modifiedDocs, config);\n removedDocs.length && config.onRemove?.(removedDocs, config);\n config.extraParsers?.forEach((extraParser) => {\n addedDocs.length && extraParser.onAdd?.(addedDocs, config);\n modifiedDocs.length && extraParser.onModify?.(modifiedDocs, config);\n removedDocs.length && extraParser.onRemove?.(removedDocs, config);\n });\n }\n },\n (error) => {\n console.error(`Error listening to collection: ${config.collectionName}`, error);\n resolvePromise();\n }\n );\n return { promise, unsubscribe };\n};\nvar snapshotDocument = (config, snapshotsFirstTime) => {\n let resolvePromise;\n let isResolved = false;\n const promise = new Promise((resolve) => {\n console.log(`==> Document in ${config.collectionName} subscribed.`);\n resolvePromise = () => {\n if (!isResolved) {\n isResolved = true;\n resolve();\n }\n };\n });\n const documentRef = doc(db, config.collectionName, config.documentId);\n const unsubscribe = onSnapshot(\n documentRef,\n (docSnapshot) => {\n if (!snapshotsFirstTime.includes(config.collectionName)) {\n snapshotsFirstTime.push(config.collectionName);\n if (docSnapshot.exists()) {\n const document2 = simpleExtractData(docSnapshot);\n if (checkConditions(document2, config.conditions)) {\n config.onFirstTime?.([document2], config);\n config.extraParsers?.forEach((extraParser) => {\n extraParser.onFirstTime?.([document2], config);\n });\n } else {\n console.warn(`Document in ${config.collectionName} does not meet conditions.`);\n }\n } else {\n console.warn(`Document not found in ${config.collectionName}.`);\n }\n resolvePromise();\n } else {\n if (docSnapshot.exists()) {\n const document2 = simpleExtractData(docSnapshot);\n if (checkConditions(document2, config.conditions)) {\n config.onModify?.([document2], config);\n config.extraParsers?.forEach((extraParser) => {\n extraParser.onModify?.([document2], config);\n });\n }\n } else {\n config.onRemove?.([], config);\n config.extraParsers?.forEach((extraParser) => {\n extraParser.onRemove?.([], config);\n });\n }\n }\n },\n (error) => {\n console.error(`Error listening to document in ${config.collectionName}:`, error);\n resolvePromise();\n }\n );\n return { promise, unsubscribe };\n};\nvar checkConditions = (document2, conditions) => {\n if (!conditions || conditions.length === 0) return true;\n return conditions.every((condition) => {\n const fieldValue = document2[condition.field_name];\n switch (condition.operator) {\n case \"==\":\n return fieldValue === condition.value;\n case \"!=\":\n return fieldValue !== condition.value;\n case \"<\":\n return fieldValue < condition.value;\n case \"<=\":\n return fieldValue <= condition.value;\n case \">\":\n return fieldValue > condition.value;\n case \">=\":\n return fieldValue >= condition.value;\n case \"array-contains\":\n return Array.isArray(fieldValue) && fieldValue.includes(condition.value);\n default:\n return false;\n }\n });\n};\nvar cleanNxSites = async () => {\n const clients = (await get_all_documents(\"nx-clients\")).map((v) => v.id);\n const sites = await get_all_documents(\"nx-sites\");\n const allSitesToDelete = sites.filter((v) => !clients.includes(v.client));\n console.log(\"allSitesToDelete\", allSitesToDelete);\n allSitesToDelete.forEach(async (v) => {\n await delete_document(\"nx-sites\", v.id);\n console.log(`Site ${v.id} deleted.`);\n });\n};\n\n// src/helpers/global.ts\nimport { CountryOptions } from \"akeyless-types-commons\";\nimport axios from \"axios\";\n\n// src/helpers/phoneNumber.ts\nimport { parsePhoneNumberFromString } from \"libphonenumber-js\";\nvar isInternational = (phone_number) => {\n return phone_number.startsWith(\"+\");\n};\nvar isInternationalIsraelPhone = (phone_number) => {\n return phone_number.startsWith(\"+9725\");\n};\nvar local_israel_phone_format = (international_number) => {\n return international_number.replace(\"+972\", \"0\");\n};\nvar international_israel_phone_format = (phone) => {\n const validNumber = phone.slice(1, phone.length);\n return \"+972\".concat(validNumber);\n};\nvar displayFormatPhoneNumber = (phoneNumber) => {\n if (isInternational(phoneNumber)) {\n const phoneNumberObject = parsePhoneNumberFromString(phoneNumber);\n if (!phoneNumberObject) {\n return phoneNumber;\n }\n return phoneNumberObject.formatInternational().replace(/\\s/g, \"\");\n }\n return phoneNumber.replace(/(\\d{3})(\\d{3})(\\d{4})/, \"$1-$2-$3\");\n};\nvar is_iccid = (number) => {\n if (number.length < 19 || number.length > 22) return false;\n if (!/^\\d+$/.test(number)) return false;\n if (!number.startsWith(\"89\")) return false;\n return true;\n};\n\n// src/helpers/global.ts\nimport { isEqual } from \"lodash\";\nvar calculateBearing = (startLat, startLng, endLat, endLng) => {\n if (startLat === endLat || startLng === endLng) {\n return 0;\n }\n if (startLat === void 0 || startLng === void 0 || endLat === void 0 || endLng === void 0) {\n return 0;\n }\n const startLatRad = startLat * Math.PI / 180;\n const startLngRad = startLng * Math.PI / 180;\n const endLatRad = endLat * Math.PI / 180;\n const endLngRad = endLng * Math.PI / 180;\n const dLon = endLngRad - startLngRad;\n const y = Math.sin(dLon) * Math.cos(endLatRad);\n const x = Math.cos(startLatRad) * Math.sin(endLatRad) - Math.sin(startLatRad) * Math.cos(endLatRad) * Math.cos(dLon);\n const bearing = Math.atan2(y, x) * 180 / Math.PI;\n return (bearing + 360) % 360;\n};\nvar renderOnce = () => {\n return true;\n};\nvar propsAreEqual = (prevProps, nextProps) => {\n return isEqual(prevProps, nextProps);\n};\nvar getUserCountryByIp = async () => {\n try {\n const response = await axios.get(\"https://ipapi.co/json/\");\n return (response.data.country_code || CountryOptions.IL).toLowerCase();\n } catch (error) {\n console.error(\"Error fetching Country:\", error);\n return CountryOptions.IL;\n }\n};\nvar parsePermissions = (object) => {\n if (!object?.features) {\n return {};\n }\n const features = object.features;\n let result = {};\n features.forEach((feature) => {\n if (!feature.includes(\"__\")) {\n return;\n }\n const [featureType, featureName] = feature.split(\"__\");\n if (!featureType || !featureName) {\n return;\n }\n if (!result[featureType]) {\n result[featureType] = {};\n }\n result[featureType][featureName] = true;\n });\n return result;\n};\nvar initializeUserPermissions = async ({ phoneNumber, firstTimeArray, getUpdatePermissions }) => {\n let unsubscribe = null;\n let permissions = {};\n try {\n const { promise, unsubscribe: unsubscribeSnapshot } = snapshot(\n {\n collectionName: \"nx-users\",\n conditions: [{ field_name: \"phone_number\", operator: \"in\", value: [phoneNumber, local_israel_phone_format(phoneNumber)] }],\n onFirstTime: (docs) => {\n if (!docs.length) {\n throw new Error(\"User not found\");\n }\n permissions = parsePermissions(docs[0]);\n getUpdatePermissions(parsePermissions(docs[0]));\n },\n onModify: (docs) => {\n getUpdatePermissions(parsePermissions(docs[0]));\n }\n },\n firstTimeArray\n );\n unsubscribe = unsubscribeSnapshot;\n await promise;\n return { unsubscribe, permissions };\n } catch (error) {\n if (unsubscribe) {\n unsubscribe();\n }\n console.error(\"Error initializing user permissions:\", error.message);\n throw error;\n }\n};\nvar userNameFormat = (user) => {\n return `${user?.first_name || \"\"} ${user?.last_name || \"\"}`.trim();\n};\nvar multiStringFormat = (str1, str2, str3) => {\n return `${str1} ${str2 || \"\"} ${str3 || \"\"}`.trim();\n};\nvar getLocationUrl = (lang, lat) => {\n return `https://www.google.com/maps?q=${lang},${lat}`;\n};\nvar isNodeEnv = typeof process !== \"undefined\" && process.env;\nvar { mode, isLocal } = {\n mode: isNodeEnv ? process.env.NEXT_PUBLIC_MODE : import.meta.env.VITE_MODE,\n isLocal: (isNodeEnv ? process.env.NEXT_PUBLIC_IS_LOCAL : import.meta.env.VITE_is_local) === \"true\"\n};\n\n// src/helpers/forms.ts\nimport XRegExp from \"xregexp\";\nvar textRegex = XRegExp(\"[^\\\\p{L}\\\\s-]\", \"gu\");\nvar numbersRegex = XRegExp(\"[^0-9\\\\s-+]\", \"g\");\nvar numbersOnlyRegex = XRegExp(\"[^0-9]\", \"g\");\nvar priceRegex = XRegExp(\"[^0-9.]\", \"g\");\nvar emailRegex = XRegExp(\"[^\\\\p{L}0-9.@\\\\s-]\", \"gu\");\nvar colorRegex = XRegExp(\"[^#0-9A-Fa-f]\", \"g\");\nvar carsRegex = XRegExp(\"[^\\\\p{L}0-9,_]\", \"gu\");\nvar textNumbersRegex = XRegExp(\"[^\\\\p{L}0-9\\\\s+\\\\-]\", \"gu\");\nvar addressRegex = XRegExp(\"[^\\\\p{L}0-9\\\\s.,+-\\\\-]\", \"gu\");\nvar chartsRegex = XRegExp(\"[^\\\\p{L}0-9\\\\s.,_@!+-\\\\-]\", \"gu\");\nvar handleChange = (e) => {\n e.target.setCustomValidity(\"\");\n const validation = e.target.getAttribute(\"data-validation\");\n if (validation === \"text\") {\n e.target.value = XRegExp.replace(e.target.value, textRegex, \"\");\n } else if (validation === \"numbers\") {\n e.target.value = XRegExp.replace(e.target.value, numbersRegex, \"\");\n } else if (validation === \"numbersOnly\") {\n e.target.value = XRegExp.replace(e.target.value, numbersOnlyRegex, \"\");\n } else if (validation === \"price\") {\n e.target.value = XRegExp.replace(e.target.value, priceRegex, \"\");\n } else if (validation === \"textNumbers\") {\n e.target.value = XRegExp.replace(e.target.value, textNumbersRegex, \"\");\n } else if (validation === \"email\") {\n e.target.value = XRegExp.replace(e.target.value, emailRegex, \"\");\n } else if (validation === \"color\") {\n e.target.value = XRegExp.replace(e.target.value, colorRegex, \"\");\n } else if (validation === \"address\") {\n e.target.value = XRegExp.replace(e.target.value, addressRegex, \"\");\n } else if (validation === \"cars\") {\n e.target.value = XRegExp.replace(e.target.value, carsRegex, \"\");\n } else if (validation === \"charts\") {\n e.target.value = XRegExp.replace(e.target.value, chartsRegex, \"\");\n }\n};\nvar handlePaste = (e) => {\n const validation = e.currentTarget.getAttribute(\"data-validation\");\n let pasteData = e.clipboardData.getData(\"text\");\n if (validation === \"text\") {\n pasteData = XRegExp.replace(pasteData, textRegex, \"\");\n } else if (validation === \"numbers\") {\n pasteData = XRegExp.replace(pasteData, numbersRegex, \"\");\n } else if (validation === \"numbersOnly\") {\n pasteData = XRegExp.replace(pasteData, numbersOnlyRegex, \"\");\n } else if (validation === \"price\") {\n pasteData = XRegExp.replace(pasteData, priceRegex, \"\");\n } else if (validation === \"textNumbers\") {\n pasteData = XRegExp.replace(pasteData, textNumbersRegex, \"\");\n } else if (validation === \"email\") {\n pasteData = XRegExp.replace(pasteData, emailRegex, \"\");\n } else if (validation === \"color\") {\n pasteData = XRegExp.replace(pasteData, colorRegex, \"\");\n } else if (validation === \"address\") {\n pasteData = XRegExp.replace(pasteData, addressRegex, \"\");\n } else if (validation === \"cars\") {\n pasteData = XRegExp.replace(pasteData, carsRegex, \"\");\n } else if (validation === \"charts\") {\n pasteData = XRegExp.replace(pasteData, chartsRegex, \"\");\n }\n e.preventDefault();\n document.execCommand(\"insertText\", false, pasteData);\n};\nvar handleInvalid = (e, requireError) => {\n e.target.setCustomValidity(requireError || \"This filed is required !\");\n};\nvar useValidation = (validationType, requireError) => {\n return {\n onChange: handleChange,\n onPaste: handlePaste,\n onInvalid: (e) => handleInvalid(e, requireError),\n \"data-validation\": validationType\n };\n};\nvar getFormElementValue = (form, name) => {\n return form.elements.namedItem(name)?.value || \"\";\n};\nvar parseMultiSelectInput = (input) => {\n const value = JSON.parse(input) || [];\n return value.map((v) => v.value);\n};\n\n// src/helpers/store.ts\nvar setState = (updater, set, stateName) => {\n return set((state) => ({\n [stateName]: typeof updater === \"function\" ? updater(state[stateName]) : updater\n }));\n};\nvar createSelectors = (store) => {\n let selectors = {};\n for (let k of Object.keys(store.getState())) {\n selectors[k] = () => store((s) => s[k]);\n }\n return selectors;\n};\nvar useStoreValues = (store, keys) => {\n const result = {};\n keys.forEach((key) => {\n result[key] = store.use[key]();\n });\n return result;\n};\n\n// src/lib/utils.ts\nimport { clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\nfunction cn(...inputs) {\n return twMerge(clsx(inputs));\n}\n\n// src/helpers/time_helpers.ts\nimport { Timestamp as Timestamp2 } from \"firebase/firestore\";\nimport moment2 from \"moment-timezone\";\nfunction timestamp_to_string(firebaseTimestamp, options) {\n let date;\n if (firebaseTimestamp instanceof Timestamp2) {\n date = firebaseTimestamp.toDate();\n } else if (firebaseTimestamp instanceof Date) {\n date = firebaseTimestamp;\n } else if (typeof firebaseTimestamp === \"string\") {\n date = moment2.utc(firebaseTimestamp, options?.fromFormat || \"DD/MM/YYYY HH:mm:ss\").toDate();\n if (isNaN(date.getTime())) {\n throw new Error(\"Invalid date string format\");\n }\n } else {\n throw new Error(\"Invalid input: firebaseTimestamp must be a Timestamp, Date, or valid date string.\");\n }\n if (options?.tz) {\n const result = moment2(date).tz(options?.tz).format(options?.format || \"DD/MM/YYYY HH:mm:ss\");\n return result;\n }\n return moment2.utc(date).format(options?.format || \"DD/MM/YYYY HH:mm:ss\");\n}\nfunction timestamp_to_millis(firebaseTimestamp) {\n const timestamp = new Timestamp2(firebaseTimestamp?.seconds, firebaseTimestamp?.nanoseconds);\n return timestamp.toMillis();\n}\nfunction sort_by_timestamp(a, b, reverse = false) {\n return reverse ? timestamp_to_millis(b) - timestamp_to_millis(a) : timestamp_to_millis(a) - timestamp_to_millis(b);\n}\n\n// src/helpers/api.ts\nimport axios2 from \"axios\";\nvar baseDomain = mode === \"qa\" ? \"https://nx-api.xyz/api\" : \"https://nx-api.info/api\";\nvar devicesDomain = isLocal ? \"http://localhost:9001/api/devices\" : baseDomain + \"/devices\";\nvar biDomain = isLocal ? \"http://localhost:9002/api/bi\" : baseDomain + \"/bi\";\nvar callCenterDomain = isLocal ? \"http://localhost:9003/api/call-center\" : baseDomain + \"/call-center\";\nvar akeylessOnlineDomain = mode === \"qa\" ? \"https://akeyless-online.xyz\" : \"https://akeyless-online.info\";\nvar nx_api_call = async (serverName, method, url, data) => {\n try {\n let urlResult = `${devicesDomain}/${url}`;\n switch (serverName) {\n case \"bi\":\n urlResult = `${biDomain}/${url}`;\n break;\n case \"devices\":\n urlResult = `${devicesDomain}/${url}`;\n break;\n case \"call-center\":\n urlResult = `${callCenterDomain}/${url}`;\n break;\n default:\n break;\n }\n const headers = {\n authorization: \"bearer \" + await auth.currentUser.getIdToken()\n };\n const response = await axios2({\n method,\n url: urlResult,\n headers,\n data\n });\n return response.data || null;\n } catch (error) {\n console.error(`Error from nx_api_call: ${JSON.stringify({ serverName, method, url, data })}`, error?.response?.data || error);\n return null;\n }\n};\nexport {\n add_document,\n addressRegex,\n akeylessOnlineDomain,\n auth,\n baseDomain,\n biDomain,\n calculateBearing,\n callCenterDomain,\n carsRegex,\n chartsRegex,\n cleanNxSites,\n cn,\n collections,\n colorRegex,\n createSelectors,\n db,\n delete_document,\n devicesDomain,\n displayFormatPhoneNumber,\n emailRegex,\n extractAlertsData,\n extractBoardsData,\n extractCanbusData,\n extractCarsData,\n extractClientData,\n extractLocationData,\n extractSiteData,\n fire_base_TIME_TEMP,\n formatCarNumber,\n getFormElementValue,\n getLocationUrl,\n getUserCountryByIp,\n get_all_documents,\n get_document_by_id,\n handleChange,\n handleInvalid,\n handlePaste,\n initializeUserPermissions,\n international_israel_phone_format,\n isInternational,\n isInternationalIsraelPhone,\n isLocal,\n isNodeEnv,\n is_iccid,\n local_israel_phone_format,\n mode,\n multiStringFormat,\n numbersOnlyRegex,\n numbersRegex,\n nx_api_call,\n parseMultiSelectInput,\n parsePermissions,\n priceRegex,\n propsAreEqual,\n query_document,\n query_document_by_conditions,\n query_documents,\n query_documents_by_conditions,\n renderOnce,\n setState,\n set_document,\n simpleExtractData,\n snapshot,\n snapshotDocument,\n sort_by_timestamp,\n storage,\n textNumbersRegex,\n textRegex,\n timestamp_to_millis,\n timestamp_to_string,\n useStoreValues,\n useValidation,\n userNameFormat\n};\n"]}
@@ -2,13 +2,6 @@ import { CountryOptions } from 'akeyless-types-commons';
2
2
  import { Dispatch, SetStateAction, EffectCallback } from 'react';
3
3
  import { WhereFilterOp } from 'firebase/firestore';
4
4
 
5
- declare const useDocumentTitle: (title: string) => any;
6
- declare const useSetUserCountry: (setUserCountry: Dispatch<SetStateAction<CountryOptions>>, changLang: (lang: string) => void) => any;
7
-
8
- declare function useSafeEffect(callback: () => void, dependencies: any[], error_message?: string): void;
9
- declare const useDeepCompareMemo: <T>(factory: () => T, dependencies: any[]) => T;
10
- declare function useDeepCompareEffect(effect: EffectCallback, dependencies: any[]): void;
11
-
12
5
  type OnSnapshotCallback = (documents: any[], config: OnSnapshotConfig) => void;
13
6
  interface OnSnapshotParsers {
14
7
  onFirstTime?: OnSnapshotCallback;
@@ -29,29 +22,17 @@ interface OnSnapshotConfig extends OnSnapshotParsers {
29
22
  fieldName: string;
30
23
  direction: "asc" | "desc";
31
24
  }[];
32
- parseAs?: "object" | "array";
33
- subscribeTo?: "cache" | "db";
34
25
  }
35
26
 
36
- declare const useSocketSnapshots: (configs: OnSnapshotConfig[], label?: string, settings?: {
37
- cleanupForConfigChange?: boolean;
38
- disableLogs?: boolean;
39
- }) => {
40
- socketConnected: boolean;
41
- };
42
- declare const useDbSnapshots: (configs: OnSnapshotConfig[], label?: string, settings?: {
27
+ declare const useDocumentTitle: (title: string) => any;
28
+ declare const useSnapshotBulk: (configs: OnSnapshotConfig[], label?: string, settings?: {
43
29
  cleanupForConfigChange?: boolean;
44
30
  disableLogs?: boolean;
45
31
  }) => void;
46
- declare const useSmartSnapshots: (configs: OnSnapshotConfig[], label?: string, settings?: {
47
- cleanupForConfigChange?: boolean;
48
- disableLogs?: boolean;
49
- }) => {
50
- groupedConfig: {
51
- configForDb: OnSnapshotConfig[];
52
- configForCache: OnSnapshotConfig[];
53
- };
54
- socketConnected: boolean;
55
- };
32
+ declare const useSetUserCountry: (setUserCountry: Dispatch<SetStateAction<CountryOptions>>, changLang: (lang: string) => void) => any;
33
+
34
+ declare function useSafeEffect(callback: () => void, dependencies: any[], error_message?: string): void;
35
+ declare const useDeepCompareMemo: <T>(factory: () => T, dependencies: any[]) => T;
36
+ declare function useDeepCompareEffect(effect: EffectCallback, dependencies: any[]): void;
56
37
 
57
- export { useDbSnapshots, useDeepCompareEffect, useDeepCompareMemo, useDocumentTitle, useSafeEffect, useSetUserCountry, useSmartSnapshots, useSocketSnapshots };
38
+ export { useDeepCompareEffect, useDeepCompareMemo, useDocumentTitle, useSafeEffect, useSetUserCountry, useSnapshotBulk };
@@ -2,13 +2,6 @@ import { CountryOptions } from 'akeyless-types-commons';
2
2
  import { Dispatch, SetStateAction, EffectCallback } from 'react';
3
3
  import { WhereFilterOp } from 'firebase/firestore';
4
4
 
5
- declare const useDocumentTitle: (title: string) => any;
6
- declare const useSetUserCountry: (setUserCountry: Dispatch<SetStateAction<CountryOptions>>, changLang: (lang: string) => void) => any;
7
-
8
- declare function useSafeEffect(callback: () => void, dependencies: any[], error_message?: string): void;
9
- declare const useDeepCompareMemo: <T>(factory: () => T, dependencies: any[]) => T;
10
- declare function useDeepCompareEffect(effect: EffectCallback, dependencies: any[]): void;
11
-
12
5
  type OnSnapshotCallback = (documents: any[], config: OnSnapshotConfig) => void;
13
6
  interface OnSnapshotParsers {
14
7
  onFirstTime?: OnSnapshotCallback;
@@ -29,29 +22,17 @@ interface OnSnapshotConfig extends OnSnapshotParsers {
29
22
  fieldName: string;
30
23
  direction: "asc" | "desc";
31
24
  }[];
32
- parseAs?: "object" | "array";
33
- subscribeTo?: "cache" | "db";
34
25
  }
35
26
 
36
- declare const useSocketSnapshots: (configs: OnSnapshotConfig[], label?: string, settings?: {
37
- cleanupForConfigChange?: boolean;
38
- disableLogs?: boolean;
39
- }) => {
40
- socketConnected: boolean;
41
- };
42
- declare const useDbSnapshots: (configs: OnSnapshotConfig[], label?: string, settings?: {
27
+ declare const useDocumentTitle: (title: string) => any;
28
+ declare const useSnapshotBulk: (configs: OnSnapshotConfig[], label?: string, settings?: {
43
29
  cleanupForConfigChange?: boolean;
44
30
  disableLogs?: boolean;
45
31
  }) => void;
46
- declare const useSmartSnapshots: (configs: OnSnapshotConfig[], label?: string, settings?: {
47
- cleanupForConfigChange?: boolean;
48
- disableLogs?: boolean;
49
- }) => {
50
- groupedConfig: {
51
- configForDb: OnSnapshotConfig[];
52
- configForCache: OnSnapshotConfig[];
53
- };
54
- socketConnected: boolean;
55
- };
32
+ declare const useSetUserCountry: (setUserCountry: Dispatch<SetStateAction<CountryOptions>>, changLang: (lang: string) => void) => any;
33
+
34
+ declare function useSafeEffect(callback: () => void, dependencies: any[], error_message?: string): void;
35
+ declare const useDeepCompareMemo: <T>(factory: () => T, dependencies: any[]) => T;
36
+ declare function useDeepCompareEffect(effect: EffectCallback, dependencies: any[]): void;
56
37
 
57
- export { useDbSnapshots, useDeepCompareEffect, useDeepCompareMemo, useDocumentTitle, useSafeEffect, useSetUserCountry, useSmartSnapshots, useSocketSnapshots };
38
+ export { useDeepCompareEffect, useDeepCompareMemo, useDocumentTitle, useSafeEffect, useSetUserCountry, useSnapshotBulk };