web-collect-events
Version:
An sdk for collecting events from web pages
1 lines • 4.76 kB
JavaScript
;var __awaiter=this&&this.__awaiter||function(e,t,o,i){return new(o||(o=Promise))((function(n,r){function s(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const browserProfile_1=__importDefault(require("./helpers/browserProfile")),dateTimeIndex_1=__importDefault(require("./helpers/dateTimeIndex")),domNodeProfile_1=__importDefault(require("./helpers/domNodeProfile")),validNode_1=require("./helpers/validNode"),api_1=require("./helpers/api"),userId_1=__importDefault(require("./helpers/userId")),BASE_URL="http://localhost:8080";class GTETWebSDK{constructor(){this.isPushNotificationScope=!1,this.isCustomEventScope=!1,this._data=[],this.checkScope(),this.initStorage(),console.log("GTETWebSDK started")}initStorage(){this._data=[]}setData(e){this._data.push(e)}getData(){return this._data}removeData(){this._data=[]}checkScope(){this.isPushNotificationScope="undefined"!=typeof window&&"undefined"!=typeof navigator,this.isCustomEventScope="undefined"!=typeof window}handleDocumentClick(e){const t=e.target;if(console.log(t),(0,validNode_1.isNodeValid)(t)){const t={event_name:"click",event_data:{browserProfile:(0,browserProfile_1.default)(),dateTimeIndex:(0,dateTimeIndex_1.default)(),userDetails:(0,userId_1.default)(),domNodeProfile:(0,domNodeProfile_1.default)(e)}};this.setData(t)}}registerUser(e){const t=`${BASE_URL||process.env.BASE_URL}/api/v1/register`;if(!t)return void console.log("BASE_URL environment variable is not defined.");fetch(t,{method:"POST",headers:{type:"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({user_id:localStorage.getItem("userId")})})}sendEventData(){const e=`${BASE_URL||process.env.BASE_URL}/api/v1/event`;if(!e)return void console.log("BASE_URL environment variable is not defined.");const t={type:"application/json",Authorization:`Bearer ${localStorage.getItem("jwtToken")||""}`},o=new FormData,i=this.getData();o.append("headers",JSON.stringify(t)),o.append("data",JSON.stringify(i)),i.length>0&&navigator.sendBeacon(`${e}`,o),this.removeData()}selfAnalyze(){this.isCustomEventScope?(document.addEventListener("click",this.handleDocumentClick.bind(this)),document.addEventListener("visibilitychange",this.sendEventData.bind(this)),setInterval(this.sendEventData.bind(this),6e4),console.log("Self analyze started")):console.log("This code is not running in a browser environment for selfAnalyze.")}customEvent(e,t){if(this.isCustomEventScope){const o={event_name:e,event_data:t};this.sendCustomEvent(o)}else console.log("This code is not running in a browser environment for customEvent.")}sendCustomEvent(e){const t=`${BASE_URL||process.env.BASE_URL}/api/v1/event`;if(!t)return void console.log("BASE_URL environment variable is not defined.");const o={type:"application/json",Authorization:`Bearer ${localStorage.getItem("jwtToken")||""}`},i=new FormData,n=e;i.append("headers",JSON.stringify(o)),i.append("data",JSON.stringify(n)),navigator.sendBeacon(`${t}`,i)}setContext(e){const t=`${BASE_URL||process.env.BASE_URL}/api/v1/user`;t?(0,api_1.postData)(t,e):console.log("BASE_URL environment variable is not defined.")}pushNotification(e,t,o){this.isPushNotificationScope?"serviceWorker"in navigator&&"PushManager"in window?this.registerServiceWorker(o).then((()=>this.sendSubscriptionToServer(e,t))).catch((e=>console.error("Error:",e))):console.log("Service Worker or PushManager is not supported in this browser."):console.log("This code is not running in a browser environment for pushNotification.")}registerServiceWorker(e){return __awaiter(this,void 0,void 0,(function*(){try{const t=yield navigator.serviceWorker.register(`/${e}.js`,{scope:"/"});console.log("Service Worker registered:",t)}catch(e){throw console.error("Failed to register Service Worker:",e),e}}))}sendSubscriptionToServer(e,t){return __awaiter(this,void 0,void 0,(function*(){try{const o=yield navigator.serviceWorker.ready,i=yield o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this.urlBase64ToUint8Array(e)});yield fetch(t,{method:"POST",body:JSON.stringify(i),headers:{"content-type":"application/json"}}),console.log("Push Sent...",JSON.stringify(i))}catch(e){throw console.error("Failed to send subscription to the server:",e),e}}))}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),o=window.atob(t),i=new Uint8Array(o.length);for(let e=0;e<o.length;++e)i[e]=o.charCodeAt(e);return i}}exports.default=GTETWebSDK;