@zaplier/sdk 1.8.7 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/v2/chunks/anti-adblock-B_7p9rSc.min.js +6 -0
- package/dist/v2/chunks/anti-adblock-B_aAB361.min.js +6 -0
- package/dist/v2/chunks/auto-tracker-5ij0Y4C-.min.js +6 -0
- package/dist/v2/chunks/browser-apis-zkKPQ-Pn.min.js +6 -0
- package/dist/v2/chunks/confidence-DCUtUduG.min.js +6 -0
- package/dist/v2/chunks/core-BUMPOlca.min.js +6 -0
- package/dist/v2/chunks/core-CGxFM5QW.min.js +6 -0
- package/dist/v2/chunks/core-NFvhjAfH.min.js +6 -0
- package/dist/v2/chunks/core-zJiDcx4q.min.js +6 -0
- package/dist/v2/chunks/device-signals-DzcCjR7i.min.js +6 -0
- package/dist/v2/chunks/dom-blockers-CtmwJ8XW.min.js +6 -0
- package/dist/v2/chunks/fingerprint-C1MH_xUr.min.js +6 -0
- package/dist/v2/chunks/hardware-VrMyNUbt.min.js +6 -0
- package/dist/v2/chunks/heatmap-BxbXSH7M.min.js +6 -0
- package/dist/v2/chunks/incognito-CUk-WJ9L.min.js +6 -0
- package/dist/v2/chunks/math-k-cWr0Zr.min.js +6 -0
- package/dist/v2/chunks/plugins-enhanced-DybbZw-x.min.js +6 -0
- package/dist/v2/chunks/session-replay-DsIhuKDJ.min.js +6 -0
- package/dist/v2/chunks/session-replay-DzEF_WqO.min.js +6 -0
- package/dist/v2/chunks/storage-DGh64hgU.min.js +6 -0
- package/dist/v2/chunks/system-Bu10BgJe.min.js +6 -0
- package/dist/v2/chunks/visitor-persistence-BUu5td5h.min.js +6 -0
- package/dist/v2/chunks/visitor-persistence-CIXH9EKf.min.js +6 -0
- package/dist/v2/chunks/visitor-persistence-DSIEfVJQ.min.js +6 -0
- package/dist/v2/chunks/visitor-persistence-Djomq4wG.min.js +6 -0
- package/dist/v2/core.d.ts +149 -80
- package/dist/v2/core.min.js +2 -2
- package/dist/v2/modules/anti-adblock.js +2 -2
- package/dist/v2/modules/auto-tracker.js +6 -0
- package/dist/v2/modules/browser-apis-BFbMjhvj.js +6 -0
- package/dist/v2/modules/confidence-B8ji6M6W.js +6 -0
- package/dist/v2/modules/device-signals-OERVSprN.js +6 -0
- package/dist/v2/modules/dom-blockers-NN7G4m7O.js +6 -0
- package/dist/v2/modules/fingerprint-BmsWDNK6.js +6 -0
- package/dist/v2/modules/fingerprint.js +2 -2
- package/dist/v2/modules/hardware-DEB_C62e.js +6 -0
- package/dist/v2/modules/heatmap.js +1 -1
- package/dist/v2/modules/incognito-B8-4CGqL.js +6 -0
- package/dist/v2/modules/math-D6mV6BoT.js +6 -0
- package/dist/v2/modules/plugins-enhanced-Bs-rTKz4.js +6 -0
- package/dist/v2/modules/replay.js +2 -2
- package/dist/v2/modules/storage-DpYaBLNV.js +6 -0
- package/dist/v2/modules/system-C8YX5XCh.js +6 -0
- package/dist/v2/modules/visitor-persistence.js +6 -0
- package/package.json +2 -3
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
class t{constructor(){this.name="fetch",this.available="undefined"!=typeof fetch}async send(t,e){const s=Date.now();try{const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`HTTP ${r.status}`);return{success:!0,method:this.name,latency:Date.now()-s}}catch(t){return{success:!1,method:this.name,latency:Date.now()-s,error:t instanceof Error?t.message:String(t)}}}}class e{constructor(t,e){this.name="elysia-websocket",this.available="undefined"!=typeof WebSocket,this.connected=!1,this.baseUrl=t,this.token=e}async send(t,e){const s=Date.now();try{if(!this.token)throw new Error("Missing token for WebSocket connection");if(await this.connect(),!this.ws||!this.connected)throw new Error("WebSocket not connected");return new Promise((e,r)=>{var i,o;const n=t=>{var i,o;try{const r=JSON.parse(t.data);null===(i=this.ws)||void 0===i||i.removeEventListener("message",n),e({success:r.success||!1,method:this.name,latency:Date.now()-s})}catch(t){null===(o=this.ws)||void 0===o||o.removeEventListener("message",n),r(new Error("Failed to parse WebSocket response"))}};null===(i=this.ws)||void 0===i||i.addEventListener("message",n),null===(o=this.ws)||void 0===o||o.send(JSON.stringify({...t,eventId:t.eventId||crypto.randomUUID(),sessionId:t.sessionId||t.s,eventType:t.eventType||t.type||"websocket_event",eventName:t.eventName||t.name,url:t.url,userAgent:t.userAgent||navigator.userAgent,timestamp:(new Date).toISOString(),fingerprintHash:t.fingerprintHash,stableCoreHash:t.stableCoreHash,stableCoreVector:t.stableCoreVector})),setTimeout(()=>{var t;null===(t=this.ws)||void 0===t||t.removeEventListener("message",n),r(new Error("WebSocket response timeout"))},5e3)})}catch(t){return{success:!1,method:this.name,latency:Date.now()-s,error:t instanceof Error?t.message:String(t)}}}async connect(){var t;if(!this.connected||(null===(t=this.ws)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN)return new Promise((t,e)=>{try{const s=new URL(this.baseUrl),r=`${"https:"===s.protocol?"wss:":"ws:"}//${s.host}/ws/track?token=${encodeURIComponent(this.token)}`;this.ws=new WebSocket(r),this.ws.onopen=()=>{this.connected=!0,t()},this.ws.onerror=()=>{this.connected=!1,e(new Error("WebSocket connection failed"))},this.ws.onclose=()=>{this.connected=!1},setTimeout(()=>{var t;this.connected||(null===(t=this.ws)||void 0===t||t.close(),e(new Error("WebSocket connection timeout")))},5e3)}catch(t){e(t)}})}cleanup(){this.ws&&(this.ws.close(),this.connected=!1)}}class s{constructor(t,e,s={}){this.transports=[],this.stats={totalRequests:0,successfulRequests:0,methodSuccess:new Map,methodFailures:new Map},this.baseUrl=t,this.token=e,this.config={enabled:!0,methods:["elysia-websocket","fetch"],fallbackDelay:100,maxRetries:2,debug:!1,...s},this.initializeTransports()}initializeTransports(){const s={"elysia-websocket":()=>new e(this.baseUrl,this.token),fetch:()=>new t};this.transports=this.config.methods.map(t=>{var e;return null===(e=s[t])||void 0===e?void 0:e.call(s)}).filter(t=>void 0!==t&&t.available),this.config.debug&&this.transports.map(t=>t.name)}async send(t,e="/tracking/event"){if(this.stats.totalRequests++,!this.config.enabled||0===this.transports.length)return{success:!1,method:"none",error:"No transports available"};let s="";for(const r of this.transports){this.config.debug&&r.name;try{const i=await r.send(t,`${this.baseUrl}${e}`);if(i.success)return this.stats.successfulRequests++,this.updateMethodStats(r.name,!0),this.config.debug&&r.name,i;this.updateMethodStats(r.name,!1),s=i.error||"Unknown error",this.config.debug&&console.warn(`[Zaplier] ❌ Transport ${r.name} failed:`,i.error)}catch(t){s=t instanceof Error?t.message:String(t),this.updateMethodStats(r.name,!1),this.config.debug&&console.warn(`[Zaplier] ❌ Transport ${r.name} threw error:`,t)}this.config.fallbackDelay>0&&await new Promise(t=>setTimeout(t,this.config.fallbackDelay))}return{success:!1,method:"all_failed",error:`All transports failed. Last error: ${s}`}}updateMethodStats(t,e){e?this.stats.methodSuccess.set(t,(this.stats.methodSuccess.get(t)||0)+1):this.stats.methodFailures.set(t,(this.stats.methodFailures.get(t)||0)+1)}getStats(){return{...this.stats}}getSuccessRates(){const t={};for(const e of this.transports){const s=this.stats.methodSuccess.get(e.name)||0,r=s+(this.stats.methodFailures.get(e.name)||0);t[e.name]=r>0?s/r*100:0}return t}destroy(){this.transports.forEach(t=>{t.destroy&&t.destroy()}),this.transports=[]}async testTransports(){const t={},e={test:!0,timestamp:Date.now()};for(const s of this.transports)try{t[s.name]=await s.send(e,`${this.baseUrl}/test`)}catch(e){t[s.name]={success:!1,method:s.name,error:e instanceof Error?e.message:String(e)}}return t}}export{s as AntiAdblockManager,e as ElysiaWebSocketTransport,t as FetchTransport};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
class t{constructor(){this.name="fetch",this.available="undefined"!=typeof fetch}async send(t,s){const e=Date.now();try{const i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw new Error(`HTTP ${i.status}`);return{success:!0,method:this.name,latency:Date.now()-e}}catch(t){return{success:!1,method:this.name,latency:Date.now()-e,error:t instanceof Error?t.message:String(t)}}}}class s{constructor(t,s){this.name="elysia-websocket",this.available="undefined"!=typeof WebSocket,this.connected=!1,this.baseUrl=t,this.token=s}async send(t,s){const e=Date.now();try{if(!this.token)throw new Error("Missing token for WebSocket connection");if(await this.connect(),!this.ws||!this.connected)throw new Error("WebSocket not connected");return new Promise((s,i)=>{var r,o;const n=t=>{var r,o;try{const i=JSON.parse(t.data);null===(r=this.ws)||void 0===r||r.removeEventListener("message",n),s({success:i.success||!1,method:this.name,latency:Date.now()-e})}catch(t){null===(o=this.ws)||void 0===o||o.removeEventListener("message",n),i(new Error("Failed to parse WebSocket response"))}};null===(r=this.ws)||void 0===r||r.addEventListener("message",n),null===(o=this.ws)||void 0===o||o.send(JSON.stringify({...t,eventId:t.eventId||crypto.randomUUID(),sessionId:t.sessionId||t.s,eventType:t.eventType||t.type||"websocket_event",eventName:t.eventName||t.name,url:t.url,userAgent:t.userAgent||navigator.userAgent,timestamp:(new Date).toISOString(),fingerprintHash:t.fingerprintHash,stableCoreHash:t.stableCoreHash,stableCoreVector:t.stableCoreVector})),setTimeout(()=>{var t;null===(t=this.ws)||void 0===t||t.removeEventListener("message",n),i(new Error("WebSocket response timeout"))},5e3)})}catch(t){return{success:!1,method:this.name,latency:Date.now()-e,error:t instanceof Error?t.message:String(t)}}}async connect(){var t;if(!this.connected||(null===(t=this.ws)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN)return new Promise((t,s)=>{try{const e=new URL(this.baseUrl),i=`${"https:"===e.protocol?"wss:":"ws:"}//${e.host}/ws/track?token=${encodeURIComponent(this.token)}`;this.ws=new WebSocket(i),this.ws.onopen=()=>{this.connected=!0,t()},this.ws.onerror=()=>{this.connected=!1,s(new Error("WebSocket connection failed"))},this.ws.onclose=()=>{this.connected=!1},setTimeout(()=>{var t;this.connected||(null===(t=this.ws)||void 0===t||t.close(),s(new Error("WebSocket connection timeout")))},5e3)}catch(t){s(t)}})}cleanup(){this.ws&&(this.ws.close(),this.connected=!1)}}class e{constructor(){this.name="webrtc",this.available=void 0!==globalThis.RTCPeerConnection,this.connected=!1}async send(t,s){const e=Date.now();if(!this.available)return{success:!1,method:this.name,error:"WebRTC not available"};try{return await this.setupConnection(),this.dataChannel&&this.connected?(this.dataChannel.send(JSON.stringify(t)),{success:!0,method:this.name,latency:Date.now()-e}):{success:!1,method:this.name,error:"DataChannel not ready"}}catch(t){return{success:!1,method:this.name,error:t instanceof Error?t.message:String(t)}}}async setupConnection(){if(!this.connected)return new Promise((t,s)=>{try{this.pc=new globalThis.RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]}),this.dataChannel=this.pc.createDataChannel("tracking",{ordered:!1,maxRetransmits:0}),this.dataChannel.onopen=()=>{this.connected=!0,t()},this.dataChannel.onerror=t=>{s(t)}}catch(t){s(t)}})}destroy(){this.dataChannel&&this.dataChannel.close(),this.pc&&this.pc.close(),this.connected=!1}}class i{constructor(t,s,e={}){this.transports=[],this.stats={totalRequests:0,successfulRequests:0,methodSuccess:new Map,methodFailures:new Map},this.baseUrl=t,this.token=s,this.config={enabled:!0,methods:["elysia-websocket","fetch"],fallbackDelay:100,maxRetries:2,debug:!1,...e},this.initializeTransports()}initializeTransports(){const i={"elysia-websocket":()=>new s(this.baseUrl,this.token),fetch:()=>new t,webrtc:()=>new e};this.transports=this.config.methods.map(t=>{var s;return null===(s=i[t])||void 0===s?void 0:s.call(i)}).filter(t=>void 0!==t&&t.available),this.config.debug&&this.transports.map(t=>t.name)}async send(t,s="/tracking/event"){if(this.stats.totalRequests++,!this.config.enabled||0===this.transports.length)return{success:!1,method:"none",error:"No transports available"};let e="";for(const i of this.transports){this.config.debug&&i.name;try{const r=await i.send(t,`${this.baseUrl}${s}`);if(r.success)return this.stats.successfulRequests++,this.updateMethodStats(i.name,!0),this.config.debug&&i.name,r;this.updateMethodStats(i.name,!1),e=r.error||"Unknown error",this.config.debug&&console.warn(`[Zaplier] ❌ Transport ${i.name} failed:`,r.error)}catch(t){e=t instanceof Error?t.message:String(t),this.updateMethodStats(i.name,!1),this.config.debug&&console.warn(`[Zaplier] ❌ Transport ${i.name} threw error:`,t)}this.config.fallbackDelay>0&&await new Promise(t=>setTimeout(t,this.config.fallbackDelay))}return{success:!1,method:"all_failed",error:`All transports failed. Last error: ${e}`}}updateMethodStats(t,s){s?this.stats.methodSuccess.set(t,(this.stats.methodSuccess.get(t)||0)+1):this.stats.methodFailures.set(t,(this.stats.methodFailures.get(t)||0)+1)}getStats(){return{...this.stats}}getSuccessRates(){const t={};for(const s of this.transports){const e=this.stats.methodSuccess.get(s.name)||0,i=e+(this.stats.methodFailures.get(s.name)||0);t[s.name]=i>0?e/i*100:0}return t}destroy(){this.transports.forEach(t=>{t.destroy&&t.destroy()}),this.transports=[]}async testTransports(){const t={},s={test:!0,timestamp:Date.now()};for(const e of this.transports)try{t[e.name]=await e.send(s,`${this.baseUrl}/test`)}catch(s){t[e.name]={success:!1,method:e.name,error:s instanceof Error?s.message:String(s)}}return t}}export{i as AntiAdblockManager,s as ElysiaWebSocketTransport,t as FetchTransport,e as WebRTCTransport};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
class t{constructor(t,e={}){this.observedElements=new Set,this.scrollThrottle=0,this.isInitialized=!1,this.delegationHandlers=new Map,this.initializationAttempts=0,this.maxInitializationAttempts=3,this.diagnostics={},this.cachedScrollElements=null,this.lastScrollElementsCheck=0,this.sdkInstance=t,this.config={enabled:!0,trackClicks:!0,trackScrolls:!0,trackViews:!0,trackHovers:!0,trackForms:!0,debug:!1,...e}}start(){this.config.enabled&&(this.initializationAttempts++,this.runDiagnostics(),this.config.debug&&this.diagnostics,this.tryInitialization())}runDiagnostics(){var t;this.diagnostics={timestamp:(new Date).toISOString(),attempt:this.initializationAttempts,environment:{domReady:document.readyState,reactDetected:this.detectReact(),reactVersion:this.getReactVersion(),userAgent:navigator.userAgent,isMobile:/Mobile|Android|iPhone|iPad/.test(navigator.userAgent),isSafari:/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent),protocol:window.location.protocol,isLocalhost:"localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname},dom:{documentElement:!!document.documentElement,body:!!document.body,querySelector:"function"==typeof document.querySelector,addEventListener:"function"==typeof document.addEventListener,elementsFound:this.getElementCounts(),hasReactRoot:this.findReactRoot()},tracking:{sdkInstance:!!this.sdkInstance,trackCustomEvent:"function"==typeof(null===(t=this.sdkInstance)||void 0===t?void 0:t.trackCustomEvent),config:this.config,isInitialized:this.isInitialized,activeHandlers:Array.from(this.delegationHandlers.keys())}}}detectReact(){return!!(window.__REACT_DEVTOOLS_GLOBAL_HOOK__||window.React||document.querySelector("[data-reactroot]")||document.querySelector("#root")||document.querySelector("#__next"))}getReactVersion(){try{const t=window.React;return(null==t?void 0:t.version)||null}catch{return null}}findReactRoot(){const t=document.querySelector("[data-reactroot]")||document.querySelector("#root")||document.querySelector("#__next")||document.querySelector("div[data-react-helmet]");return t?t.tagName+(t.id?"#"+t.id:""):null}getElementCounts(){return{click:document.querySelectorAll("[data-track-click]").length,scroll:document.querySelectorAll("[data-track-scroll]").length,view:document.querySelectorAll("[data-track-view]").length,hover:document.querySelectorAll("[data-track-hover]").length,form:document.querySelectorAll("[data-track-form]").length}}tryInitialization(){const t=[()=>this.immediateInitialization(),()=>this.delayedInitialization(100),()=>this.delayedInitialization(500),()=>this.delayedInitialization(1e3),()=>this.reactReadyInitialization()];"complete"===document.readyState?this.attemptStrategy(0,t):"interactive"===document.readyState?this.attemptStrategy(1,t):document.addEventListener("DOMContentLoaded",()=>{this.attemptStrategy(0,t)},{once:!0})}attemptStrategy(t,e){if(!(t>=e.length||this.isInitialized)){this.config.debug&&e.length;try{const i=e[t];i&&"function"==typeof i?(i(),setTimeout(()=>{this.verifyInitialization()?this.config.debug:(this.config.debug,this.attemptStrategy(t+1,e))},50)):this.attemptStrategy(t+1,e)}catch(i){this.config.debug&&console.error(`[❌ AutoTracker] Strategy ${t+1} error:`,i),this.attemptStrategy(t+1,e)}}}immediateInitialization(){this.initializeTracking()}delayedInitialization(t){setTimeout(()=>{this.initializeTracking()},t)}reactReadyInitialization(){"function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(()=>{setTimeout(()=>{this.initializeTracking()},0)}):setTimeout(()=>{this.initializeTracking()},16)}verifyInitialization(){const t=this.getElementCounts(),e=Object.values(t).reduce((t,e)=>t+e,0),i=this.delegationHandlers.size>0;return this.config.debug&&(this.isInitialized,Array.from(this.delegationHandlers.keys())),this.isInitialized&&(e>0||i)}initializeTracking(){this.config.debug,this.observeDOM(),this.processExistingElements(),this.config.trackViews&&this.setupViewTracking(),this.setupEventDelegation(),this.config.debug&&(this.logFoundElements(),setTimeout(()=>{this.logFoundElements()},500),setTimeout(()=>{this.logFoundElements()},2e3))}logFoundElements(){const t=document.querySelectorAll("[data-track-click]"),e=document.querySelectorAll("[data-track-scroll]"),i=document.querySelectorAll("[data-track-view]"),s=document.querySelectorAll("[data-track-hover]"),r=document.querySelectorAll("[data-track-form]");t.length,e.length,i.length,s.length,r.length,t.length,e.length,i.length,s.length,r.length,e.length>0&&Array.from(e).map(t=>({tagName:t.tagName,trackEvent:t.getAttribute("data-track-scroll"),threshold:t.getAttribute("data-scroll-threshold")||"0.5",id:t.id||"no-id",classes:t.className||"no-classes"}))}setupEventDelegation(){this.config.debug;const t=this.getOptimalDelegationTarget();if(this.config.debug,this.config.trackClicks){const e=this.createReactCompatibleClickHandler();this.delegationHandlers.set("click",e),t.addEventListener("click",e,this.getEventOptions("click")),this.config.debug}this.config.trackScrolls&&(this.config.debug,this.setupIntersectionObserverScrollTracking(),this.setupFallbackScrollListener(),this.config.debug),this.setupIntelligentMutationObserver(),this.isInitialized=!0,this.config.debug&&(this.delegationHandlers.has("click"),this.delegationHandlers.has("scroll"),this.delegationHandlers.size)}getOptimalDelegationTarget(){var t;const e=document.querySelector("#root")||document.querySelector("#__next")||document.querySelector("[data-reactroot]");return e&&(null===(t=this.diagnostics.environment)||void 0===t?void 0:t.reactDetected)?(this.config.debug,e):document}getEventOptions(t){var e,i;null===(e=this.diagnostics.environment)||void 0===e||e.isMobile;const s=null===(i=this.diagnostics.environment)||void 0===i?void 0:i.isSafari;let r={};switch(t){case"click":r={passive:!s,capture:!1};break;case"scroll":r={passive:!0,capture:!1};break;default:r={passive:!0}}return this.config.debug,r}createReactCompatibleClickHandler(){return t=>{try{if(!this.config.trackClicks)return;const e=t.target;if(!e)return;let i=null;if(i=e.closest("[data-track-click]"),!i&&e.hasAttribute&&e.hasAttribute("data-track-click")&&(i=e),i||(i=this.findTrackingElementManually(e,"data-track-click")),!i)return void(this.config.debug&&(e.tagName,e.closest,e.hasAttribute));const s=i.getAttribute("data-track-click");if(!s)return;const r=this.extractMetadata(i);this.trackEvent(s,{type:"click",element:i.tagName.toLowerCase(),reactCompatible:!0,...r}),this.config.debug&&i.tagName.toLowerCase()}catch(t){this.config.debug&&console.error("[❌ AutoTracker] Click handler error:",t)}}}findTrackingElementManually(t,e,i=10){let s=t,r=0;for(;s&&s!==document.documentElement&&r<i;){if(s.hasAttribute&&s.hasAttribute(e))return s;s=s.parentElement,r++}return null}setupIntersectionObserverScrollTracking(){if("undefined"==typeof window||!("IntersectionObserver"in window))return void this.config.debug;const t=document.querySelectorAll("[data-track-scroll]");if(0===t.length)return void this.config.debug;const e=new IntersectionObserver(t=>{t.forEach(t=>{const i=t.target,s=i.getAttribute("data-track-scroll"),r=parseFloat(i.getAttribute("data-scroll-threshold")||"0.5"),o="true"===i.getAttribute("data-scroll-triggered");if(!s||o)return;const a=t.intersectionRatio;if(this.config.debug&&(i.id,Math.round(1e3*a),t.isIntersecting),a>=r){i.setAttribute("data-scroll-triggered","true");const t=this.extractMetadata(i);this.trackEvent(s,{type:"scroll",method:"IntersectionObserver",element:i.tagName.toLowerCase(),threshold:r,visibilityRatio:Math.round(1e3*a)/1e3,enhanced:!0,modern:!0,...t}),this.config.debug&&Math.round(100*a),e.unobserve(i)}})},{root:null,rootMargin:"0px",threshold:[0,.1,.25,.5,.75,.9,1]});t.forEach(t=>{e.observe(t),this.config.debug&&(t.getAttribute("data-track-scroll"),t.id)}),this.intersectionObserver=e,this.config.debug&&t.length}setupFallbackScrollListener(){if("undefined"==typeof window)return;const t=this.createThrottledScrollHandler();[()=>window.addEventListener("scroll",t,{passive:!0}),()=>document.addEventListener("scroll",t,{passive:!0}),()=>window.addEventListener("scroll",t,{passive:!0,capture:!0}),()=>{setTimeout(()=>{window.addEventListener("scroll",t,{passive:!0})},100)},()=>{"complete"===document.readyState?window.addEventListener("scroll",t,{passive:!0}):window.addEventListener("load",()=>{window.addEventListener("scroll",t,{passive:!0})})}].forEach((t,e)=>{try{t(),this.config.debug}catch(t){this.config.debug}}),this.delegationHandlers.set("scroll",t),this.config.debug&&setTimeout(()=>{window.addEventListener("scroll",()=>{},{once:!0,passive:!0});const t=window.scrollY;window.scrollBy(0,1),setTimeout(()=>window.scrollTo(0,t),50)},2e3)}createThrottledScrollHandler(){let t=0,e=!1;return()=>{t=window.scrollY,e||(setTimeout(()=>{this.config.debug,this.processFallbackScroll(t),e=!1},20),e=!0)}}processFallbackScroll(t){const e=document.querySelectorAll('[data-track-scroll]:not([data-scroll-triggered="true"])');0!==e.length&&e.forEach(e=>{const i=e.getAttribute("data-track-scroll"),s=parseFloat(e.getAttribute("data-scroll-threshold")||"0.5");if(!i)return;const r=e.getBoundingClientRect(),o=window.innerHeight,a=r.height;if(a<=0)return;const n=Math.max(r.top,0),c=Math.min(r.bottom,o),l=Math.max(0,c-n)/a;if(l>=s){e.setAttribute("data-scroll-triggered","true");const r=this.extractMetadata(e);this.trackEvent(i,{type:"scroll",method:"fallback_scroll",element:e.tagName.toLowerCase(),threshold:s,visibilityRatio:Math.round(1e3*l)/1e3,scrollPosition:t,fallback:!0,...r}),this.config.debug&&Math.round(100*l)}})}createEnhancedScrollHandler(){return()=>{var t;try{if(this.config.debug&&(this.config.trackScrolls,window.scrollY,Date.now()),!this.config.trackScrolls)return void this.config.debug;const e=Date.now(),i=e-this.scrollThrottle,s=(null===(t=this.diagnostics.environment)||void 0===t?void 0:t.isMobile)?150:100;if(this.config.debug&&this.scrollThrottle,i<s)return void this.config.debug;this.scrollThrottle=e;const r=this.getCachedScrollElements();this.config.debug&&(r.length,window.scrollY,window.innerHeight),r.length>0?(this.config.debug&&r.length,r.forEach((t,e)=>{this.config.debug&&(r.length,t.id,t.getAttribute("data-track-scroll"),t.getAttribute("data-scroll-triggered")),this.processScrollElementEnhanced(t)}),this.config.debug&&r.length):this.config.debug}catch(t){this.config.debug&&console.error("[❌ AutoTracker] CRITICAL: Enhanced scroll handler error:",t)}}}getCachedScrollElements(){const t=Date.now();return(!this.cachedScrollElements||t-this.lastScrollElementsCheck>2e3)&&(this.cachedScrollElements=document.querySelectorAll("[data-track-scroll]"),this.lastScrollElementsCheck=t,this.config.debug&&(this.cachedScrollElements.length,Array.from(this.cachedScrollElements).forEach((t,e)=>{t.id,t.className,t.getAttribute("data-track-scroll"),t.getAttribute("data-scroll-threshold"),t.tagName,t.getAttribute("data-scroll-triggered")}))),this.cachedScrollElements}processScrollElementEnhanced(t){try{if("true"===t.getAttribute("data-scroll-triggered"))return void(this.config.debug&&(t.id||t.className));const e=parseFloat(t.getAttribute("data-scroll-threshold")||"0.5"),i=t.getBoundingClientRect(),s=i.height,r=window.innerHeight;if(s<=0)return void(this.config.debug&&t.id);const o=Math.max(i.top,0),a=Math.min(i.bottom,r),n=Math.max(0,a-o)/s,c=t.getAttribute("data-track-scroll");if(!c)return void(this.config.debug&&t.id);if(this.config.debug&&(t.id,t.className,t.tagName,Math.round(i.top),Math.round(i.bottom),Math.round(s),window.scrollY,Math.round(i.top),Math.round(i.bottom),Math.round(s),Math.round(1e3*n),Math.round(1e3*n)),n>=e){t.setAttribute("data-scroll-triggered","true");const i=this.extractMetadata(t),s={type:"scroll",element:t.tagName.toLowerCase(),threshold:e,scrollDepth:window.scrollY,visibilityRatio:Math.round(1e3*n)/1e3,enhanced:!0,...i};this.config.debug,this.trackEvent(c,s),this.config.debug}}catch(e){this.config.debug&&console.error("[❌ AutoTracker] Scroll element processing error:",e,{element:t.id||t.className||"no-id",tagName:t.tagName})}}processScrollElement(t){this.processScrollElementEnhanced(t)}setupIntelligentMutationObserver(){if(this.mutationObserver)return;const t=this.debounce(t=>{let e=!1;t.forEach(t=>{t.addedNodes.forEach(t=>{if(t.nodeType===Node.ELEMENT_NODE){const i=t;(this.hasTrackingAttributes(i)||this.hasTrackingDescendants(i))&&(e=!0,this.config.debug)}})}),e&&(this.config.debug,this.processExistingElements())},150);this.mutationObserver=new MutationObserver(t),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.config.debug}hasTrackingAttributes(t){return t.hasAttribute&&(t.hasAttribute("data-track-click")||t.hasAttribute("data-track-scroll")||t.hasAttribute("data-track-view")||t.hasAttribute("data-track-hover")||t.hasAttribute("data-track-form"))}hasTrackingDescendants(t){return!!t.querySelector&&!!(t.querySelector("[data-track-click]")||t.querySelector("[data-track-scroll]")||t.querySelector("[data-track-view]")||t.querySelector("[data-track-hover]")||t.querySelector("[data-track-form]"))}debounce(t,e){let i;return(...s)=>{clearTimeout(i),i=setTimeout(()=>t.apply(this,s),e)}}stop(){this.config.debug,this.delegationHandlers.forEach((t,e)=>{"click"===e?this.getOptimalDelegationTarget().removeEventListener("click",t):"scroll"===e?(window.removeEventListener("scroll",t),document.removeEventListener("scroll",t),this.config.debug):document.removeEventListener(e,t)}),this.delegationHandlers.clear(),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=void 0),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=void 0),this.observedElements.clear(),this.isInitialized=!1,this.config.debug}observeDOM(){this.config.debug}processExistingElements(){document.querySelectorAll("[data-track-click], [data-track-scroll], [data-track-view], [data-track-hover], [data-track-form]").forEach(t=>{this.processElement(t)})}processElement(t){this.config.trackViews&&t.hasAttribute("data-track-view")&&this.setupElementViewTracking(t),this.config.trackHovers&&t.hasAttribute("data-track-hover")&&this.setupHoverTracking(t),this.config.trackForms&&t.hasAttribute("data-track-form")&&this.setupFormTracking(t)}setupViewTracking(){this.intersectionObserver=new IntersectionObserver(t=>{t.forEach(t=>{var e;if(t.isIntersecting){const i=t.target,s=i.getAttribute("data-track-view");if(!s)return;const r=this.extractMetadata(i);this.trackEvent(s,{type:"view",element:i.tagName.toLowerCase(),intersectionRatio:t.intersectionRatio,...r}),this.config.debug,null===(e=this.intersectionObserver)||void 0===e||e.unobserve(i)}})},{threshold:.5,rootMargin:"0px"})}setupElementViewTracking(t){this.intersectionObserver&&(this.observedElements.has(t)||(this.intersectionObserver.observe(t),this.observedElements.add(t)))}setupHoverTracking(t){let e;const i=parseInt(t.getAttribute("data-hover-time")||"1000");t.addEventListener("mouseenter",()=>{e=Date.now()}),t.addEventListener("mouseleave",()=>{const s=Date.now()-e;if(s>=i){const e=t.getAttribute("data-track-hover");if(!e)return;const r=this.extractMetadata(t);this.trackEvent(e,{type:"hover",element:t.tagName.toLowerCase(),hoverDuration:s,minHoverTime:i,...r}),this.config.debug}})}setupFormTracking(t){"form"===t.tagName.toLowerCase()&&t.addEventListener("submit",e=>{const i=t.getAttribute("data-track-form");if(!i)return;const s=new FormData(t),r=this.extractMetadata(t),o={};for(const[t,e]of s.entries())this.isSensitiveField(t)||(o[t]="string"==typeof e?e.substring(0,100):"file");this.trackEvent(i,{type:"form_submit",element:"form",fieldCount:Array.from(s.entries()).length,fields:o,...r}),this.config.debug})}extractMetadata(t){var e;const i={};Array.from(t.attributes).forEach(t=>{if(t.name.startsWith("data-meta-")){const e=t.name.replace("data-meta-","");i[e]=t.value}}),t.id&&(i.elementId=t.id),t.className&&(i.elementClass=t.className);const s=null===(e=t.textContent)||void 0===e?void 0:e.trim();s&&s.length>0&&(i.textContent=s.substring(0,50));const r=t.getBoundingClientRect();return i.elementPosition={x:Math.round(r.left),y:Math.round(r.top),width:Math.round(r.width),height:Math.round(r.height)},i}isSensitiveField(t){return[/password/i,/pass/i,/pwd/i,/secret/i,/token/i,/api[_-]?key/i,/credit[_-]?card/i,/ssn/i,/social/i,/tax/i].some(e=>e.test(t))}trackEvent(t,e){var i,s,r,o;const a=performance.now();this.config.debug&&((new Date).toISOString(),null===(i=(new Error).stack)||void 0===i||i.split("\n").slice(1,4));const n=this.validateTrackingCall(t,e);if(n.isValid)try{const i={autoTracked:!0,enhanced:!0,timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,trackingLatency:Math.round(100*(performance.now()-a))/100,isReactApp:null===(s=this.diagnostics.environment)||void 0===s?void 0:s.reactDetected,isMobile:null===(r=this.diagnostics.environment)||void 0===r?void 0:r.isMobile,...e};if(this.config.debug&&(this.sdkInstance,null===(o=this.sdkInstance)||void 0===o||o.trackCustomEvent),!this.sdkInstance)return void(this.config.debug&&console.error("[❌ AutoTracker] 🚫 SDK INSTANCE IS NULL - CANNOT SEND EVENT"));if("function"!=typeof this.sdkInstance.trackCustomEvent)return void(this.config.debug&&console.error("[❌ AutoTracker] 🚫 trackCustomEvent IS NOT A FUNCTION:",typeof this.sdkInstance.trackCustomEvent));if(this.sdkInstance.trackCustomEvent(t,i),this.config.debug){const t=performance.now();Math.round(100*(t-a))}}catch(i){this.config.debug&&console.error("[💥 AutoTracker] 💀 CRITICAL TRACKING ERROR:",{eventName:t,error:i instanceof Error?i.message:i,stack:i instanceof Error?i.stack:void 0,metadata:e,sdkInstance:!!this.sdkInstance,sdkInstanceType:typeof this.sdkInstance})}else this.config.debug&&console.error("[❌ AutoTracker] 🚫 VALIDATION FAILED:",n.errors)}validateTrackingCall(t,e){const i=[];return t&&"string"==typeof t||i.push("Event name is required and must be a string"),this.sdkInstance||i.push("SDK instance is null or undefined"),this.sdkInstance&&"function"!=typeof this.sdkInstance.trackCustomEvent&&i.push("trackCustomEvent is not a function: "+typeof this.sdkInstance.trackCustomEvent),window&&"object"==typeof window||i.push("Window object is not available"),{isValid:0===i.length,errors:i}}refreshTracking(){this.isInitialized?(this.config.debug,this.processExistingElements(),this.config.debug&&this.logFoundElements()):this.config.debug}rescan(){this.refreshTracking()}getDiagnostics(){const t={triggerScrollHandler:()=>{this.config.debug;const t=this.delegationHandlers.get("scroll");t?t(new Event("scroll")):console.error("[❌ AutoTracker] No scroll handler found")},forceScrollEvent:t=>{const e=document.querySelector(t);e?e.getAttribute("data-track-scroll")?(e.removeAttribute("data-scroll-triggered"),this.processScrollElementEnhanced(e)):console.error(`[❌ AutoTracker] Element has no data-track-scroll: ${t}`):console.error(`[❌ AutoTracker] Element not found: ${t}`)},testTrackEvent:(t="test_event")=>{this.trackEvent(t,{type:"test",source:"manual_diagnostic",timestamp:Date.now()})},testIntersectionObserver:()=>{const t=document.querySelectorAll("[data-track-scroll]");if(t.length,this.intersectionObserver&&t.length>0){const e=t[0];e&&(e.getAttribute("data-track-scroll"),e.removeAttribute("data-scroll-triggered"),this.intersectionObserver.observe(e))}},testScrollFallback:()=>{const t=this.delegationHandlers.get("scroll");t&&t(new Event("scroll"))}};return"undefined"!=typeof window&&(window.autoTrackerTests=t),{initialization:{isInitialized:this.isInitialized,attempts:this.initializationAttempts,maxAttempts:this.maxInitializationAttempts,timestamp:(new Date).toISOString()},eventHandlers:{hasClickHandler:this.delegationHandlers.has("click"),hasScrollHandler:this.delegationHandlers.has("scroll"),activeHandlers:Array.from(this.delegationHandlers.keys()),delegationTarget:this.getOptimalDelegationTarget()===document?"document":"react-root"},observers:{observedElements:this.observedElements.size,hasMutationObserver:!!this.mutationObserver,hasIntersectionObserver:!!this.intersectionObserver,scrollElementsCache:!!this.cachedScrollElements,cacheExpiry:new Date(this.lastScrollElementsCheck+5e3).toISOString()},config:this.config,environment:this.diagnostics.environment||{},dom:this.diagnostics.dom||{},tracking:this.diagnostics.tracking||{},elementsFound:this.getElementCounts(),performance:{lastScrollThrottle:this.scrollThrottle,cacheLastUpdate:this.lastScrollElementsCheck},validation:this.validateTrackingCall("test",{}),recommendations:this.generateRecommendations(),manualTests:{available:!0,usage:{triggerScrollHandler:"window.autoTrackerTests.triggerScrollHandler()",forceScrollEvent:'window.autoTrackerTests.forceScrollEvent("[data-track-scroll]")',testTrackEvent:'window.autoTrackerTests.testTrackEvent("my_event")',testIntersectionObserver:"window.autoTrackerTests.testIntersectionObserver()",testScrollFallback:"window.autoTrackerTests.testScrollFallback()"},description:"Use these functions in the browser console to manually test the AutoTracker"}}}generateRecommendations(){var t,e;const i=[],s=this.getElementCounts(),r=Object.values(s).reduce((t,e)=>t+e,0);return this.isInitialized||i.push("AutoTracker is not initialized. Check console for errors."),0===r&&i.push("No trackable elements found. Ensure data-track-* attributes are present in the DOM."),this.sdkInstance||i.push("SDK instance is missing. Ensure the SDK is properly initialized."),this.sdkInstance&&"function"!=typeof this.sdkInstance.trackCustomEvent&&i.push("trackCustomEvent method is not available on SDK instance."),!(null===(t=this.diagnostics.environment)||void 0===t?void 0:t.reactDetected)&&window.location.hostname.includes("localhost")&&i.push("React not detected. If using React, ensure proper setup and try refreshTracking() after route changes."),(null===(e=this.diagnostics.environment)||void 0===e?void 0:e.isMobile)&&!this.delegationHandlers.has("scroll")&&i.push("Mobile device detected but scroll tracking not active. Check scroll tracking configuration."),this.initializationAttempts>1&&i.push(`AutoTracker required ${this.initializationAttempts} initialization attempts. Consider adding delay before enabling.`),i}configure(t){this.config={...this.config,...t}}getStats(){return{observedElements:this.observedElements.size,config:this.config,isModern:this.isInitialized,diagnostics:this.config.debug?this.getDiagnostics():void 0}}}export{t as AutoTracker};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
import{i as t,a as n,b as e}from"./fingerprint-C1MH_xUr.min.js";function r(){var n;try{return t()&&null!==(n=navigator.pdfViewerEnabled)&&void 0!==n?n:null}catch{return null}}function o(){try{if(!n())return-1;const{ApplePaySession:t}=window;if("function"!=typeof(null==t?void 0:t.canMakePayments))return-1;if(!e())return-2;if(window.self!==window.top)return-3;try{return t.canMakePayments()?1:0}catch(t){if(t instanceof Error&&"InvalidAccessError"===t.name)return-2;throw t}}catch{return-1}}function i(){try{return"attributionReporting"in window||"privateClickMeasurement"in window||null}catch{return null}}function a(){const n={enabled:!1,sameSiteSupport:!1,secureSupport:!1,partitionedSupport:!1};try{if(n.enabled=navigator.cookieEnabled,!n.enabled)return n;n.sameSiteSupport=c("__rb_test_samesite","SameSite=Strict"),e()&&(n.secureSupport=c("__rb_test_secure","Secure")),e()&&t()&&(n.partitionedSupport=c("__rb_test_partitioned","Partitioned; Secure; SameSite=None"))}catch{}return n}function c(t,n){try{const e="1",r=`${t}=${e}; ${n}; path=/`;document.cookie=r;const o=document.cookie.includes(`${t}=${e}`);return u(t),o}catch{return u(t),!1}}function u(t){try{const n=[`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`,`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${location.hostname}`,`${t}=; max-age=0; path=/`,`${t}=; max-age=0; path=/; domain=${location.hostname}`];for(const t of n)try{document.cookie=t}catch{}setTimeout(()=>{try{document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}catch{}},100)}catch{}}function s(){try{const t=document.createElement("canvas"),n=t.getContext("webgl")||t.getContext("experimental-webgl");return n?(n.getSupportedExtensions()||[]).sort():[]}catch{return[]}}function l(){try{const t=performance.memory;return t?{usedJSHeapSize:t.usedJSHeapSize,totalJSHeapSize:t.totalJSHeapSize,jsHeapSizeLimit:t.jsHeapSizeLimit}:null}catch{return null}}function p(){try{const t=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return t?{effectiveType:t.effectiveType,downlink:t.downlink,rtt:t.rtt,saveData:t.saveData}:null}catch{return null}}function d(){var t;const n={};try{n.webkitTemporaryStorage="webkitTemporaryStorage"in navigator,n.webkitPersistentStorage="webkitPersistentStorage"in navigator,window.safari&&(n.safariObjectTypes=Object.getOwnPropertyNames(window.safari)),n.chromeRuntime=!!(null===(t=window.chrome)||void 0===t?void 0:t.runtime),n.mozInnerScreenX="mozInnerScreenX"in window,n.msCredentials="msCredentials"in navigator}catch{}return n}function f(){return"undefined"!=typeof window&&"undefined"!=typeof navigator}function w(){const t=r(),n=o(),e=i(),c=a(),u=s(),f=l(),w=p(),m=d();let h="unknown";m.chromeRuntime?h="chrome":-1!==n?h="safari":m.mozInnerScreenX?h="firefox":m.msCredentials&&(h="edge");const v=Boolean(t||n>-1||e||f||w),S=[null!==t,-1!==n,null!==e,c.enabled,u.length>0,null!==f,null!==w,Object.keys(m).length>0];return{pdfViewerEnabled:t,applePayState:n,privateClickMeasurement:e,cookieCapabilities:c,webglExtensions:u,performanceMemory:f,connectionInfo:w,vendorProperties:m,browserVendor:h,hasNativeFeatures:v,apiScore:Math.round(S.filter(Boolean).length/S.length*100)}}export{o as getApplePayState,w as getBrowserApisFingerprint,p as getConnectionInfo,a as getCookieCapabilities,r as getPdfViewerEnabled,l as getPerformanceMemory,i as getPrivateClickMeasurement,d as getVendorProperties,s as getWebGLExtensions,f as isBrowserApisDetectionAvailable};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
const e={canvas:{stability:.95,entropy:.9,uniqueness:.85,spoofResistance:.8},webgl:{stability:.92,entropy:.88,uniqueness:.82,spoofResistance:.85},audio:{stability:.9,entropy:.85,uniqueness:.8,spoofResistance:.9},hardware:{stability:.98,entropy:.7,uniqueness:.75,spoofResistance:.95},screen:{stability:.85,entropy:.6,uniqueness:.65,spoofResistance:.7},system:{stability:.8,entropy:.65,uniqueness:.7,spoofResistance:.6},browser:{stability:.75,entropy:.6,uniqueness:.65,spoofResistance:.5},fonts:{stability:.7,entropy:.75,uniqueness:.7,spoofResistance:.4},math:{stability:.95,entropy:.8,uniqueness:.9,spoofResistance:.95},storage:{stability:.6,entropy:.5,uniqueness:.6,spoofResistance:.3},incognito:{stability:.5,entropy:.4,uniqueness:.3,spoofResistance:.2},domBlockers:{stability:.8,entropy:.7,uniqueness:.6,spoofResistance:.9},accessibility:{stability:.9,entropy:.6,uniqueness:.7,spoofResistance:.85},browserApis:{stability:.85,entropy:.75,uniqueness:.8,spoofResistance:.7},pluginsEnhanced:{stability:.7,entropy:.65,uniqueness:.75,spoofResistance:.5},mathFingerprint:{stability:.99,entropy:.95,uniqueness:.9,spoofResistance:.98},fontPreferences:{stability:.92,entropy:.88,uniqueness:.85,spoofResistance:.75},dateTimeLocale:{stability:.95,entropy:.7,uniqueness:.75,spoofResistance:.8},accessibilityEnhanced:{stability:.93,entropy:.65,uniqueness:.8,spoofResistance:.9},enhancedFonts:{stability:.88,entropy:.85,uniqueness:.82,spoofResistance:.7},webrtc:{stability:.92,entropy:.85,uniqueness:.8,spoofResistance:.9},permissions:{stability:.88,entropy:.75,uniqueness:.72,spoofResistance:.8},speech:{stability:.9,entropy:.7,uniqueness:.65,spoofResistance:.85},cssFeatures:{stability:.97,entropy:.88,uniqueness:.85,spoofResistance:.95},mediaCodecs:{stability:.95,entropy:.82,uniqueness:.78,spoofResistance:.92},wasmFeatures:{stability:.98,entropy:.7,uniqueness:.72,spoofResistance:.97},mathml:{stability:.9,entropy:.8,uniqueness:.75,spoofResistance:.88},clientHints:{stability:.93,entropy:.92,uniqueness:.9,spoofResistance:.85}},s={domBlockers:{stability:.8,entropy:.7,uniqueness:.6,spoofResistance:.9},accessibility:{stability:.9,entropy:.6,uniqueness:.7,spoofResistance:.85},browserApis:{stability:.85,entropy:.75,uniqueness:.8,spoofResistance:.7}};function n(n){const t=e[n]||s[n];if(!t)return.5;const i=.3*t.stability+.25*t.entropy+.25*t.uniqueness+.2*t.spoofResistance;return Math.max(.1,Math.min(1,i))}function t(t,i={}){const{requireMinimumComponents:o=4,penalizeMissingCore:a=!0,adjustForIncognito:r=!0}=i,c=t.filter(e=>e.success),p=[];c.length<o&&p.push(`Collect at least ${o} components for reliable identification`);let u=0,y=0,l=0,b=0,f=0;const q=["canvas","webgl","audio","hardware"].filter(e=>!c.some(s=>s.component===e));for(const t of c){const i=n(t.component),o=e[t.component]||s[t.component];o&&(u+=i,y+=o.stability*i,l+=o.entropy*i,b+=o.uniqueness*i,f+=o.spoofResistance*i)}const R=u>0?y/u:0,m=u>0?l/u:0,d=u>0?f/u:0;let h,g,w=.35*R+.25*m+.25*(u>0?b/u:0)+.15*d,M=w;return a&&q.length>0&&(M-=.1*q.length,p.push(`Missing core components: ${q.join(", ")}`)),c.length<6&&(M-=.05*(6-c.length)),r&&c.some(e=>"incognito"===e.component)&&(M+=.02),c.filter(e=>["domBlockers","accessibility","browserApis","math"].includes(e.component)).length>=2&&(M+=.05),M=Math.max(0,Math.min(1,M)),M>=.995?(h=.995,g="Very High"):M>=.99?(h=.99,g="High"):M>=.95?(h=.95,g="Medium"):M>=.8?(h=.8,g="Low"):(h=.5,g="Very Low",p.push("Consider implementing additional fingerprinting techniques")),M<.95&&p.push("Enable all available fingerprinting components for better accuracy"),d<.6&&p.push("Include more spoof-resistant components like audio and WebGL"),m<.6&&p.push("Add high-entropy components like canvas and math fingerprinting"),{score:h,level:g,factors:{componentCount:c.length,weightedScore:Math.round(1e3*w)/1e3,stabilityScore:Math.round(1e3*R)/1e3,entropyScore:Math.round(1e3*m)/1e3,spoofResistanceScore:Math.round(1e3*d)/1e3},recommendations:p.slice(0,3)}}export{s as ADVANCED_COMPONENT_CHARACTERISTICS,e as COMPONENT_CHARACTERISTICS,n as calculateComponentWeight,t as calculateConfidence};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
const t=new Set(["token","replay","heatmap","debug","allow_localhost","gdprMode","replaySampleRate"]);function i(t){return function(t){const i=new Date||new Date;return`${t}_${i.getFullYear()}${(i.getMonth()+1).toString().padStart(2,"0")}${i.getDate().toString().padStart(2,"0")}_${i.getHours().toString().padStart(2,"0")}`}(t)}const e={apiEndpoint:"https://api.zaplier.com",retryEnabled:!0,maxRetries:3,retryDelays:[1e3,2e3,4e3],autoTrack:!0,dedupeEnabled:!0,fingerprintEnabled:!0,presenceTracking:!1,heartbeatInterval:3e4,scrollTracking:!0,scrollDepthTracking:!0,gdprCompliant:!0,enhancedTracking:"ask",replaySampling:.1,replayMaskInputs:!0};class n{constructor(i){var n;if(this.version="1.9.0",this.isInitialized=!1,this.eventQueue=[],this.t=!1,!i.token)throw console.error('[Zaplier] Missing required "token" option. Get your token at https://app.zaplier.com/dashboard/keys'),new Error("Zaplier: token is required");if("string"!=typeof i.token||i.token.trim().length<5)throw console.error('[Zaplier] Invalid token format. Token should be a workspace API key (e.g., "ws_abc123...")'),new Error("Zaplier: invalid token format");for(const e of Object.keys(i))t.has(e)||console.warn(`[Zaplier] Unknown config option "${e}". Valid options: ${[...t].join(", ")}`);const s=["replay","heatmap","debug","allow_localhost","gdprMode"];for(const t of s){const e=i[t];void 0!==e&&"boolean"!=typeof e&&console.warn(`[Zaplier] "${t}" should be true or false, got: ${typeof e}`)}let o=i;if(void 0!==i.replaySampleRate){const t=i.replaySampleRate;("number"!=typeof t||t<0||t>1)&&(console.warn(`[Zaplier] "replaySampleRate" must be a number between 0 and 1, got: ${t}. Defaulting to 1.0.`),o={...i,replaySampleRate:1})}this.config={...e,...o,gdprMode:null!==(n=o.gdprMode)&&void 0!==n&&n},this.t=this.isDevEnvironment(),this.heatmap=this.createHeatmapProxy(),this.replay=this.createReplayProxy(),this.autoTrack=this.createAutoTrackProxy(),this.initializeCore()}initializeCore(){try{if(this.config.debug&&this.version,!this.config.allow_localhost&&this.isLocalhost())return void this.config.debug;this.sessionId=this.generateTempSessionId(),this.visitorId=this.generateTempVisitorId(),this.isInitialized=!0,this.processEventQueue(),this.config.debug,"undefined"!=typeof window&&this.scheduleModuleLoading()}catch(t){console.error("[Zaplier] Initialization failed:",t)}}scheduleModuleLoading(){const t=(t,i)=>{"undefined"!=typeof requestIdleCallback?requestIdleCallback(t,{timeout:i}):setTimeout(t,Math.min(i/10,200))};t(async()=>{try{await this.loadFingerprint(),this.config.debug}catch(t){this.config.debug&&console.error("[Zaplier] Deferred fingerprinting failed:",t)}},3e3),t(()=>{this.loadAntiAdblock(),this.config.debug},1e3),this.config.autoTrack&&t(()=>{this.loadAutoTracker(),this.config.debug},1500),this.config.replay&&t(async()=>{await this.loadReplayEngine(),this.config.debug},2e3),this.config.heatmap&&t(()=>{this.loadHeatmapEngine(),this.config.debug},2500)}async loadFingerprint(){if(!this.fingerprint)try{const{getCompleteFingerprint:t,getLightweightFingerprint:i}=await import("./fingerprint-C1MH_xUr.min.js").then(function(t){return t.f}),e=this.config.gdprMode?await i():await t();if(e.success&&e.data){this.fingerprint=e.data,e.data.incognitoDetection&&(this.fingerprint.incognitoDetection={...e.data.incognitoDetection,detectionTimestamp:Date.now(),sdkVersion:this.version});try{const{VisitorIdentityManager:t}=await import("./visitor-persistence-BUu5td5h.min.js");this.visitorIdentityManager=new t;const i=await this.visitorIdentityManager.getOrCreateVisitorIdentity({fingerprintHash:e.data.hash,stableCoreHash:e.data.stableCoreHash,deviceFingerprint:e.data.stableCoreHash||e.data.hash,sessionId:this.sessionId,userAgent:navigator.userAgent,ipAddress:void 0});i.visitorId&&!i.pendingBackendResponse&&(this.visitorId=i.visitorId,this.backendVisitorId=i.visitorId),this.config.debug&&(this.visitorId,i.persistenceMethod,i.confidence,i.reused)}catch(t){this.config.debug&&console.error("[Zaplier] Visitor persistence loading failed:",t)}this.config.debug&&(e.collectedComponents,e.data.hash,e.data.stableCoreHash,this.config.gdprMode)}}catch(t){this.config.debug&&console.error("[Zaplier] Fingerprinting failed:",t),this.collectFallbackEntropy()}}collectFallbackEntropy(){try{const t=[navigator.userAgent||"",navigator.language||"",navigator.platform||"",screen.width||0,screen.height||0,screen.colorDepth||0,new Date(2024,0,1).getTimezoneOffset(),navigator.hardwareConcurrency||0,navigator.deviceMemory||0,navigator.maxTouchPoints||0,performance.timeOrigin||0,navigator.plugins?navigator.plugins.length:0].join("|");let i=0;for(let e=0;e<t.length;e++)i=(i<<5)-i+t.charCodeAt(e)&4294967295,i^=i>>>16;this.fingerprint||(this.fingerprint={}),this.fingerprint.fallbackEntropy=Math.abs(i).toString(36)}catch{}}async loadAntiAdblock(){if(!this.antiAdblockManager)try{const{AntiAdblockManager:t}=await import("./anti-adblock-B_aAB361.min.js");this.antiAdblockManager=new t(this.config.apiEndpoint,this.config.token,{enabled:!0,methods:["elysia-websocket","fetch"],fallbackDelay:100,maxRetries:2,debug:this.config.debug})}catch(t){this.config.debug&&console.error("[Zaplier] Anti-adblock loading failed:",t)}}async loadAutoTracker(){if(!this.i)try{const{AutoTracker:t}=await import("./auto-tracker-5ij0Y4C-.min.js");this.i=new t(this,{enabled:!0,trackClicks:!0,trackScrolls:!0,trackViews:!0,trackHovers:!0,trackForms:!0,debug:this.config.debug}),this.i.start()}catch(t){this.config.debug&&console.error("[Zaplier] Auto tracker loading failed:",t)}}shouldRecord(){var t,i;const e="__zp_rs";try{if("undefined"!=typeof window&&window.sessionStorage){const i=sessionStorage.getItem(e);if(null!==i)return"1"===i;const n=null!==(t=this.config.replaySampleRate)&&void 0!==t?t:1,s=Math.random()<n;return sessionStorage.setItem(e,s?"1":"0"),s}}catch{}const n=null!==(i=this.config.replaySampleRate)&&void 0!==i?i:1;return Math.random()<n}async fetchFeatureFlags(){try{const t=await this.makeRequest(`/sdk/features?token=${encodeURIComponent(this.config.token)}`,null,"GET");return!0===(null==t?void 0:t.hasSessionReplay)}catch{return!1}}async loadReplayEngine(){if(!this.o)try{if(!await this.fetchFeatureFlags())return;if(!this.shouldRecord())return void this.config.debug;this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DzEF_WqO.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay loading failed:",t)}}async loadHeatmapEngine(){if(!this.h)try{this.sessionId||(this.sessionId=this.generateSessionId());const{HeatmapEngine:t}=await import("./heatmap-BxbXSH7M.min.js");this.h=new t(this.sessionId,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1}),this.antiAdblockManager&&this.h.setAntiAdblockManager(this.antiAdblockManager),this.h.start()}catch(t){this.config.debug&&console.error("[Zaplier] Heatmap loading failed:",t)}}createHeatmapProxy(){const t=this;return{enable(){t.config.heatmap=!0,!t.h&&t.isInitialized&&t.loadHeatmapEngine(),t.config.debug},disable(){t.config.heatmap=!1,t.h&&(t.h.stop(),t.h=void 0),t.config.debug},enableMouseTracking(){t.h?t.h.enableMouseTracking():t.loadHeatmapEngine().then(()=>{var i;null===(i=t.h)||void 0===i||i.enableMouseTracking()})},disableMouseTracking(){t.h&&t.h.disableMouseTracking()},getStats:()=>t.h?t.h.getStats():null,isRecording:()=>!!t.h&&t.h.isRecording()}}createReplayProxy(){const t=this;return{enable(){t.config.replay=!0,(!t.o&&t.isInitialized||t.o&&!t.o.isRecording())&&t.loadReplayEngineForced(),t.config.debug},disable(){t.config.replay=!1,t.o&&(t.o.stop(),t.o=void 0),t.config.debug},start:async()=>(!t.o&&t.isInitialized&&await t.loadReplayEngineForced(),!!t.o&&t.o.start()),stop(){t.o&&t.o.stop()},isRecording:()=>!!t.o&&t.o.isRecording(),getEventCount:()=>t.o?t.o.getEventCount():0,addFunnelStep(i){t.sendEvent({eventType:"funnel_step",eventName:"funnel_step",customData:i})},markConversion(i){t.trackConversion("funnel_conversion",i.value,i.currency,i)}}}createAutoTrackProxy(){const t=this;return{enable(){t.i?t.i.configure({enabled:!0}):t.loadAutoTracker(),t.config.debug},disable(){t.i&&(t.i.stop(),t.i=void 0),t.config.debug},configure(i){t.i&&t.i.configure(i),t.config.debug},refreshTracking(){t.i&&t.i.refreshTracking(),t.config.debug},getDiagnostics:()=>t.i?t.i.getDiagnostics():null,getStats:()=>t.i?t.i.getStats():null,isEnabled:()=>!!t.i}}async loadReplayEngineForced(){try{this.o&&(this.o.stop(),this.o=void 0),this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DzEF_WqO.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay engine loading failed:",t)}}extractUTMParameters(){const t={};if("undefined"==typeof window||!window.location)return t;try{const i=new URLSearchParams(window.location.search),e=i.get("utm_source"),n=i.get("utm_medium"),s=i.get("utm_campaign"),o=i.get("utm_content"),a=i.get("utm_term"),r=i.get("fbclid"),h=i.get("gclid"),c=i.get("ttclid"),l=i.get("creative_id"),d=i.get("ad_id"),u=i.get("adset_id"),p=i.get("campaign_id"),v=i.get("platform");e&&(t.utmSource=e),n&&(t.utmMedium=n),s&&(t.utmCampaign=s),o&&(t.utmContent=o),a&&(t.utmTerm=a),r&&(t.fbclid=r),h&&(t.gclid=h),c&&(t.ttclid=c),l&&(t.creativeId=l),d&&(t.adId=d),u&&(t.adsetId=u),p&&(t.campaignId=p),v&&(t.platform=v),this.config.debug&&Object.keys(t).length}catch(t){this.config.debug&&console.warn("[Zaplier] Failed to extract UTM parameters:",t)}return t}async sendEvent(t){var e,n,s,o,a,r,h,c,l,d,u,p,v,f,g,w,m,y;if(!this.isInitialized)return this.eventQueue.length>=100&&this.eventQueue.shift(),void this.eventQueue.push(t);try{const k={visitorId:this.backendVisitorId||null,sessionId:this.sessionId,fingerprintHash:null===(e=this.fingerprint)||void 0===e?void 0:e.hash,stableCoreHash:null===(n=this.fingerprint)||void 0===n?void 0:n.stableCoreHash,stableCoreVector:null===(s=this.fingerprint)||void 0===s?void 0:s.stableCoreVector,fingerprintVector:this.fingerprint||void 0,incognitoDetection:(null===(o=this.fingerprint)||void 0===o?void 0:o.incognitoDetection)&&(void 0!==this.fingerprint.incognitoDetection.likelihood||this.fingerprint.incognitoDetection.methods&&this.fingerprint.incognitoDetection.methods.length>0)?this.fingerprint.incognitoDetection:void 0,fingerprintComponents:(null===(a=this.fingerprint)||void 0===a?void 0:a.components)||{},isSafari:"undefined"!=typeof navigator&&/safari/i.test(navigator.userAgent)&&!/chrome|chromium|opr|edg|edge/i.test(navigator.userAgent),ch:navigator.userAgentData?{brands:navigator.userAgentData.brands||[],platform:navigator.userAgentData.platform||void 0,mobile:navigator.userAgentData.mobile||void 0,model:navigator.userAgentData.model||void 0}:void 0,...this.extractUTMParameters(),...t,timestamp:(new Date).toISOString(),url:"undefined"!=typeof window&&window.location?window.location.href:"",referrer:"undefined"!=typeof document?document.referrer:"",pageTitle:"undefined"!=typeof document?document.title:"",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"",screenWidth:(null===(c=null===(h=null===(r=this.fingerprint)||void 0===r?void 0:r.screen)||void 0===h?void 0:h.value)||void 0===c?void 0:c.width)||("undefined"!=typeof window&&window.screen?window.screen.width:0),screenHeight:(null===(u=null===(d=null===(l=this.fingerprint)||void 0===l?void 0:l.screen)||void 0===d?void 0:d.value)||void 0===u?void 0:u.height)||("undefined"!=typeof window&&window.screen?window.screen.height:0),viewportWidth:(null===(f=null===(v=null===(p=this.fingerprint)||void 0===p?void 0:p.screen)||void 0===v?void 0:v.value)||void 0===f?void 0:f.viewportWidth)||("undefined"!=typeof window?window.innerWidth:0),viewportHeight:(null===(m=null===(w=null===(g=this.fingerprint)||void 0===g?void 0:g.screen)||void 0===w?void 0:w.value)||void 0===m?void 0:m.viewportHeight)||("undefined"!=typeof window?window.innerHeight:0),gdprMode:this.config.gdprMode,isDev:this.t},b=await this.makeRequest(`/tracking/event?token=${encodeURIComponent(this.config.token)}`,k);if(b.visitorId){if(this.backendVisitorId=b.visitorId,this.visitorIdentityManager&&(null===(y=this.fingerprint)||void 0===y?void 0:y.stableCoreHash))try{await this.visitorIdentityManager.updateVisitorIdFromBackend(b.visitorId,this.fingerprint.stableCoreHash,this.sessionId)}catch(t){this.config.debug&&console.error("[Zaplier] Failed to save backend visitor ID to storage:",t)}this.config.debug&&b.visitorId}if(!b.sessionId||this.sessionId&&!this.sessionId.includes("temp_")){if(this.backendVisitorId&&(!this.sessionId||this.sessionId.includes("temp_"))){const t=this.sessionId;this.sessionId=i(this.backendVisitorId),t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}}else{const t=this.sessionId;this.sessionId=b.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return b}catch(i){this.config.debug&&console.error("[Zaplier] Event sending failed:",i),this.config.retryEnabled&&setTimeout(()=>this.sendEvent(t),5e3)}}async sendReplayBatch(t){var i;if(!this.isInitialized)return{success:!1,error:"SDK not initialized"};try{const e={sessionId:t.sessionId,userId:this.backendVisitorId,events:t.events,metadata:{...t.metadata,visitorId:this.backendVisitorId,fingerprintHash:null===(i=this.fingerprint)||void 0===i?void 0:i.hash}};this.config.debug&&(e.sessionId,e.events.length);const n=await this.makeRequest(`/replays/record?token=${encodeURIComponent(this.config.token)}`,e,"POST");if(n.sessionId&&n.sessionId!==this.sessionId){const t=this.sessionId;this.sessionId=n.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return n}catch(t){return this.config.debug&&console.error("[Zaplier] Replay batch sending failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async makeRequest(t,i,e="POST"){const n=`${this.config.apiEndpoint}${t}`,s={method:e,headers:{"Content-Type":"application/json"}};"POST"===e&&i&&(s.body=JSON.stringify(i),s.keepalive=!0);try{const t=Promise.race([fetch(n,s),new Promise((t,i)=>setTimeout(()=>i(new Error("Fetch timeout - possibly blocked")),5e3))]),i=await t;if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return await i.json()}catch(n){if(this.antiAdblockManager&&"POST"===e){this.config.debug&&console.warn(`[Zaplier] Standard fetch failed (${n instanceof Error?n.message:String(n)}), trying anti-adblock fallback`);try{const e=await this.antiAdblockManager.send(i,t);if(e.success)return this.config.debug&&(e.method,e.latency),{success:!0,method:e.method}}catch(t){this.config.debug&&console.warn("[Zaplier] Both standard fetch and anti-adblock failed:",t)}}throw n}}updateTrackingEnginesSessionId(t){try{if(this.o){const i=this.o.isRecording();this.o.stop(),import("./session-replay-DzEF_WqO.min.js").then(({SessionReplayEngine:e})=>{this.o=new e(t,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),i&&this.o.start()})}if(this.h){const i=this.h.isRecording();this.h.stop(),import("./heatmap-BxbXSH7M.min.js").then(({HeatmapEngine:e})=>{this.h=new e(t,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1}),this.antiAdblockManager&&this.h.setAntiAdblockManager(this.antiAdblockManager),i&&this.h.start()})}this.config.debug}catch(t){console.error("[Zaplier] Failed to update tracking engines session ID:",t)}}processEventQueue(){if(0===this.eventQueue.length)return;const t=[...this.eventQueue];this.eventQueue=[],t.forEach(t=>this.sendEvent(t))}isLocalhost(){return!("undefined"==typeof window||!window.location)&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||window.location.hostname.startsWith("192.168.")||window.location.hostname.startsWith("10.")||window.location.hostname.includes("local"))}isDevEnvironment(){if("undefined"==typeof window)return!1;const t=window.location.hostname;return"localhost"===t||"127.0.0.1"===t||"[::1]"===t||t.endsWith(".local")||t.endsWith(".test")||!0===this.config.debug}generateTempSessionId(){const t=new Date,i=t.getFullYear()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0"),e=t.getHours().toString().padStart(2,"0");return`temp_${Date.now()}_${i}_${e}`}generateTempVisitorId(){return`temp_visitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateSessionId(){return this.backendVisitorId?i(this.backendVisitorId):i(this.visitorId||"temp-"+Date.now().toString(36))}track(t,i){this.sendEvent({eventType:t,eventName:t,customData:i})}trackCustomEvent(t,i){return this.sendEvent({eventType:"custom",eventName:t,customData:i}),!0}trackConversion(t,i,e,n){return this.sendEvent({eventType:"conversion",eventName:t,revenue:i,currency:e||"USD",customData:n}),!0}trackPageView(t){this.sendEvent({eventType:"page_view",eventName:"page_view",...t})}trackSPANavigation(t,i){this.trackPageView({url:t||("undefined"!=typeof window&&window.location?window.location.href:""),pageTitle:i||("undefined"!=typeof document?document.title:"")})}trackPurchase(t){this.sendEvent({eventType:"purchase",eventName:"purchase",revenue:t.value||t.revenue,currency:t.currency||"USD",quantity:t.quantity||1,productId:t.productId,customData:{productName:t.productName,orderId:t.orderId,...t.customData}})}trackAddToCart(t){this.sendEvent({eventType:"add_to_cart",eventName:"add_to_cart",revenue:null==t?void 0:t.price,quantity:(null==t?void 0:t.quantity)||1,productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,...null==t?void 0:t.customData}})}trackViewContent(t){this.sendEvent({eventType:"view_content",eventName:"view_content",productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,category:null==t?void 0:t.category,...null==t?void 0:t.customData}})}trackInitiateCheckout(t){this.sendEvent({eventType:"initiate_checkout",eventName:"initiate_checkout",revenue:null==t?void 0:t.value,currency:(null==t?void 0:t.currency)||"USD",quantity:null==t?void 0:t.numItems,customData:null==t?void 0:t.customData})}trackLead(t){this.sendEvent({eventType:"lead",eventName:"lead",customData:t})}identify(t){this.sendEvent({eventType:"identify",eventName:"identify",email:t.email,phone:t.phone,customData:t})}startPresenceTracking(){this.config.presenceTracking=!0,this.config.debug}stopPresenceTracking(){this.config.presenceTracking=!1,this.config.debug}enableAdvancedFeatures(){return this.loadFingerprint()}enableEnhancedTracking(){return this.config.enhancedTracking="true",this.config.gdprMode=!1,this.loadFingerprint(),this.config.debug,!0}disableEnhancedTracking(){this.config.enhancedTracking="false",this.config.gdprMode=!0,this.config.debug}isEnhancedMode(){return"true"===this.config.enhancedTracking&&!this.config.gdprMode}resetScrollTracking(){this.config.debug}getVisitorId(){if(this.backendVisitorId)return this.backendVisitorId;if(this.visitorId)return this.visitorId;if(this.visitorIdentityManager){const t=this.visitorIdentityManager.getCurrentVisitorId();if(t)return this.backendVisitorId=t,this.visitorId=t,t}return null}getUserData(){var t,i,e,n,s,o,a;const r="undefined"!=typeof navigator?{userAgent:navigator.userAgent,language:navigator.language,screen:{width:null!==(i=null===(t=window.screen)||void 0===t?void 0:t.width)&&void 0!==i?i:0,height:null!==(n=null===(e=window.screen)||void 0===e?void 0:e.height)&&void 0!==n?n:0}}:{userAgent:"",language:"",screen:{width:0,height:0}};return{sessionId:null!==(s=this.sessionId)&&void 0!==s?s:"",visitorId:null!==(o=this.getVisitorId())&&void 0!==o?o:void 0,location:{},device:r,journey:[],fingerprint:null===(a=this.fingerprint)||void 0===a?void 0:a.hash}}async getVisitorInfo(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID yet. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;if(this.cachedVisitorInfo)return this.cachedVisitorInfo;try{const i=await this.makeRequest(`/tracking/visitor/${t}?token=${encodeURIComponent(this.config.token)}`,null,"GET");return this.cachedVisitorInfo=i,i}catch{return null}}async getVisitorHistory(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID available. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;try{return await this.makeRequest(`/tracking/visitor/${t}/history?token=${encodeURIComponent(this.config.token)}`,null,"GET")}catch(t){return this.config.debug&&console.error("[Zaplier] Failed to get visitor history:",t),null}}getConversionLikelihood(){return{score:0,level:"unknown",factors:[]}}getUserSegment(){return{segment:"unknown",confidence:0,traits:[]}}}function s(t){return new n(t)}const o=s;if("undefined"!=typeof window){window.Zaplier={init:s,version:"1.9.0"};const t=()=>{const t=document.getElementsByTagName("script");for(const i of Array.from(t))if(i.src&&(i.src.includes("zaplier")||i.src.includes("core.min.js")||i.src.includes("sdk.min.js"))&&i.dataset.token){const t=s({token:i.dataset.token,debug:"true"===i.dataset.debug,replay:"true"===i.dataset.replay,heatmap:"true"===i.dataset.heatmap,gdprMode:"true"===i.dataset.gdprMode,allow_localhost:"true"===i.dataset.allowLocalhost});return window.Zaplier.instance=t,void t.trackPageView()}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}export{n as Z,o as a,i as g,s as i};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
const t=new Set(["token","replay","heatmap","debug","allow_localhost","gdprMode","replaySampleRate"]);function i(t){return function(t){const i=new Date||new Date;return`${t}_${i.getFullYear()}${(i.getMonth()+1).toString().padStart(2,"0")}${i.getDate().toString().padStart(2,"0")}_${i.getHours().toString().padStart(2,"0")}`}(t)}const e={apiEndpoint:"https://api.zaplier.com",retryEnabled:!0,maxRetries:3,retryDelays:[1e3,2e3,4e3],autoTrack:!0,dedupeEnabled:!0,fingerprintEnabled:!0,presenceTracking:!1,heartbeatInterval:3e4,scrollTracking:!0,scrollDepthTracking:!0,gdprCompliant:!0,enhancedTracking:"ask",replaySampling:.1,replayMaskInputs:!0};class n{constructor(i){var n;if(this.version="3.0.0",this.isInitialized=!1,this.eventQueue=[],this.t=!1,!i.token)throw console.error('[Zaplier] Missing required "token" option. Get your token at https://app.zaplier.com/dashboard/keys'),new Error("Zaplier: token is required");if("string"!=typeof i.token||i.token.trim().length<5)throw console.error('[Zaplier] Invalid token format. Token should be a workspace API key (e.g., "ws_abc123...")'),new Error("Zaplier: invalid token format");for(const e of Object.keys(i))t.has(e)||console.warn(`[Zaplier] Unknown config option "${e}". Valid options: ${[...t].join(", ")}`);const s=["replay","heatmap","debug","allow_localhost","gdprMode"];for(const t of s){const e=i[t];void 0!==e&&"boolean"!=typeof e&&console.warn(`[Zaplier] "${t}" should be true or false, got: ${typeof e}`)}let o=i;if(void 0!==i.replaySampleRate){const t=i.replaySampleRate;("number"!=typeof t||t<0||t>1)&&(console.warn(`[Zaplier] "replaySampleRate" must be a number between 0 and 1, got: ${t}. Defaulting to 1.0.`),o={...i,replaySampleRate:1})}this.config={...e,...o,gdprMode:null!==(n=o.gdprMode)&&void 0!==n&&n},this.t=this.isDevEnvironment(),this.heatmap=this.createHeatmapProxy(),this.replay=this.createReplayProxy(),this.autoTrack=this.createAutoTrackProxy(),this.initializeCore()}initializeCore(){try{if(this.config.debug&&this.version,!this.config.allow_localhost&&this.isLocalhost())return void this.config.debug;this.sessionId=this.generateTempSessionId(),this.visitorId=this.generateTempVisitorId(),this.isInitialized=!0,this.processEventQueue(),this.config.debug,"undefined"!=typeof window&&this.scheduleModuleLoading()}catch(t){console.error("[Zaplier] Initialization failed:",t)}}scheduleModuleLoading(){const t=(t,i)=>{"undefined"!=typeof requestIdleCallback?requestIdleCallback(t,{timeout:i}):setTimeout(t,Math.min(i/10,200))};t(async()=>{try{await this.loadFingerprint(),this.config.debug}catch(t){this.config.debug&&console.error("[Zaplier] Deferred fingerprinting failed:",t)}},3e3),t(()=>{this.loadAntiAdblock(),this.config.debug},1e3),this.config.autoTrack&&t(()=>{this.loadAutoTracker(),this.config.debug},1500),this.config.replay&&t(async()=>{await this.loadReplayEngine(),this.config.debug},2e3),this.config.heatmap&&t(()=>{this.loadHeatmapEngine(),this.config.debug},2500)}async loadFingerprint(){if(!this.fingerprint)try{const{getCompleteFingerprint:t,getLightweightFingerprint:i}=await import("./fingerprint-C1MH_xUr.min.js").then(function(t){return t.f}),e=this.config.gdprMode?await i():await t();if(e.success&&e.data){this.fingerprint=e.data,e.data.incognitoDetection&&(this.fingerprint.incognitoDetection={...e.data.incognitoDetection,detectionTimestamp:Date.now(),sdkVersion:this.version});try{const{VisitorIdentityManager:t}=await import("./visitor-persistence-CIXH9EKf.min.js");this.visitorIdentityManager=new t;const i=await this.visitorIdentityManager.getOrCreateVisitorIdentity({fingerprintHash:e.data.hash,stableCoreHash:e.data.stableCoreHash,deviceFingerprint:e.data.stableCoreHash||e.data.hash,sessionId:this.sessionId,userAgent:navigator.userAgent,ipAddress:void 0});i.visitorId&&!i.pendingBackendResponse&&(this.visitorId=i.visitorId,this.backendVisitorId=i.visitorId),this.config.debug&&(this.visitorId,i.persistenceMethod,i.confidence,i.reused)}catch(t){this.config.debug&&console.error("[Zaplier] Visitor persistence loading failed:",t)}this.config.debug&&(e.collectedComponents,e.data.hash,e.data.stableCoreHash,this.config.gdprMode)}}catch(t){this.config.debug&&console.error("[Zaplier] Fingerprinting failed:",t),this.collectFallbackEntropy()}}collectFallbackEntropy(){try{const t=[navigator.userAgent||"",navigator.language||"",navigator.platform||"",screen.width||0,screen.height||0,screen.colorDepth||0,new Date(2024,0,1).getTimezoneOffset(),navigator.hardwareConcurrency||0,navigator.deviceMemory||0,navigator.maxTouchPoints||0,performance.timeOrigin||0,navigator.plugins?navigator.plugins.length:0].join("|");let i=0;for(let e=0;e<t.length;e++)i=(i<<5)-i+t.charCodeAt(e)&4294967295,i^=i>>>16;this.fingerprint||(this.fingerprint={}),this.fingerprint.fallbackEntropy=Math.abs(i).toString(36)}catch{}}async loadAntiAdblock(){if(!this.antiAdblockManager)try{const{AntiAdblockManager:t}=await import("./anti-adblock-B_aAB361.min.js");this.antiAdblockManager=new t(this.config.apiEndpoint,this.config.token,{enabled:!0,methods:["elysia-websocket","fetch"],fallbackDelay:100,maxRetries:2,debug:this.config.debug})}catch(t){this.config.debug&&console.error("[Zaplier] Anti-adblock loading failed:",t)}}async loadAutoTracker(){if(!this.i)try{const{AutoTracker:t}=await import("./auto-tracker-5ij0Y4C-.min.js");this.i=new t(this,{enabled:!0,trackClicks:!0,trackScrolls:!0,trackViews:!0,trackHovers:!0,trackForms:!0,debug:this.config.debug}),this.i.start()}catch(t){this.config.debug&&console.error("[Zaplier] Auto tracker loading failed:",t)}}shouldRecord(){var t,i;const e="__zp_rs";try{if("undefined"!=typeof window&&window.sessionStorage){const i=sessionStorage.getItem(e);if(null!==i)return"1"===i;const n=null!==(t=this.config.replaySampleRate)&&void 0!==t?t:1,s=Math.random()<n;return sessionStorage.setItem(e,s?"1":"0"),s}}catch{}const n=null!==(i=this.config.replaySampleRate)&&void 0!==i?i:1;return Math.random()<n}async fetchFeatureFlags(){try{const t=await this.makeRequest(`/sdk/features?token=${encodeURIComponent(this.config.token)}`,null,"GET");return!0===(null==t?void 0:t.hasSessionReplay)}catch{return!1}}async loadReplayEngine(){if(!this.o)try{if(!await this.fetchFeatureFlags())return;if(!this.shouldRecord())return void this.config.debug;this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DzEF_WqO.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay loading failed:",t)}}async loadHeatmapEngine(){if(!this.h)try{this.sessionId||(this.sessionId=this.generateSessionId());const{HeatmapEngine:t}=await import("./heatmap-BxbXSH7M.min.js");this.h=new t(this.sessionId,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1}),this.antiAdblockManager&&this.h.setAntiAdblockManager(this.antiAdblockManager),this.h.start()}catch(t){this.config.debug&&console.error("[Zaplier] Heatmap loading failed:",t)}}createHeatmapProxy(){const t=this;return{enable(){t.config.heatmap=!0,!t.h&&t.isInitialized&&t.loadHeatmapEngine(),t.config.debug},disable(){t.config.heatmap=!1,t.h&&(t.h.stop(),t.h=void 0),t.config.debug},enableMouseTracking(){t.h?t.h.enableMouseTracking():t.loadHeatmapEngine().then(()=>{var i;null===(i=t.h)||void 0===i||i.enableMouseTracking()})},disableMouseTracking(){t.h&&t.h.disableMouseTracking()},getStats:()=>t.h?t.h.getStats():null,isRecording:()=>!!t.h&&t.h.isRecording()}}createReplayProxy(){const t=this;return{enable(){t.config.replay=!0,(!t.o&&t.isInitialized||t.o&&!t.o.isRecording())&&t.loadReplayEngineForced(),t.config.debug},disable(){t.config.replay=!1,t.o&&(t.o.stop(),t.o=void 0),t.config.debug},start:async()=>(!t.o&&t.isInitialized&&await t.loadReplayEngineForced(),!!t.o&&t.o.start()),stop(){t.o&&t.o.stop()},isRecording:()=>!!t.o&&t.o.isRecording(),getEventCount:()=>t.o?t.o.getEventCount():0,addFunnelStep(i){t.sendEvent({eventType:"funnel_step",eventName:"funnel_step",customData:i})},markConversion(i){t.trackConversion("funnel_conversion",i.value,i.currency,i)}}}createAutoTrackProxy(){const t=this;return{enable(){t.i?t.i.configure({enabled:!0}):t.loadAutoTracker(),t.config.debug},disable(){t.i&&(t.i.stop(),t.i=void 0),t.config.debug},configure(i){t.i&&t.i.configure(i),t.config.debug},refreshTracking(){t.i&&t.i.refreshTracking(),t.config.debug},getDiagnostics:()=>t.i?t.i.getDiagnostics():null,getStats:()=>t.i?t.i.getStats():null,isEnabled:()=>!!t.i}}async loadReplayEngineForced(){try{this.o&&(this.o.stop(),this.o=void 0),this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DzEF_WqO.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay engine loading failed:",t)}}extractUTMParameters(){const t={};if("undefined"==typeof window||!window.location)return t;try{const i=new URLSearchParams(window.location.search),e=i.get("utm_source"),n=i.get("utm_medium"),s=i.get("utm_campaign"),o=i.get("utm_content"),a=i.get("utm_term"),r=i.get("fbclid"),h=i.get("gclid"),l=i.get("ttclid"),c=i.get("creative_id"),d=i.get("ad_id"),u=i.get("adset_id"),p=i.get("campaign_id"),v=i.get("platform");e&&(t.utmSource=e),n&&(t.utmMedium=n),s&&(t.utmCampaign=s),o&&(t.utmContent=o),a&&(t.utmTerm=a),r&&(t.fbclid=r),h&&(t.gclid=h),l&&(t.ttclid=l),c&&(t.creativeId=c),d&&(t.adId=d),u&&(t.adsetId=u),p&&(t.campaignId=p),v&&(t.platform=v),this.config.debug&&Object.keys(t).length}catch(t){this.config.debug&&console.warn("[Zaplier] Failed to extract UTM parameters:",t)}return t}async sendEvent(t){var e,n,s,o,a,r,h,l,c,d,u,p,v,f,g,w,m,y;if(this.isInitialized)try{const k={visitorId:this.backendVisitorId||null,sessionId:this.sessionId,fingerprintHash:null===(e=this.fingerprint)||void 0===e?void 0:e.hash,stableCoreHash:null===(n=this.fingerprint)||void 0===n?void 0:n.stableCoreHash,stableCoreVector:null===(s=this.fingerprint)||void 0===s?void 0:s.stableCoreVector,fingerprintVector:this.fingerprint||void 0,incognitoDetection:(null===(o=this.fingerprint)||void 0===o?void 0:o.incognitoDetection)&&(void 0!==this.fingerprint.incognitoDetection.likelihood||this.fingerprint.incognitoDetection.methods&&this.fingerprint.incognitoDetection.methods.length>0)?this.fingerprint.incognitoDetection:void 0,fingerprintComponents:(null===(a=this.fingerprint)||void 0===a?void 0:a.components)||{},isSafari:"undefined"!=typeof navigator&&/safari/i.test(navigator.userAgent)&&!/chrome|chromium|opr|edg|edge/i.test(navigator.userAgent),ch:navigator.userAgentData?{brands:navigator.userAgentData.brands||[],platform:navigator.userAgentData.platform||void 0,mobile:navigator.userAgentData.mobile||void 0,model:navigator.userAgentData.model||void 0}:void 0,...this.extractUTMParameters(),...t,timestamp:(new Date).toISOString(),url:"undefined"!=typeof window&&window.location?window.location.href:"",referrer:"undefined"!=typeof document?document.referrer:"",pageTitle:"undefined"!=typeof document?document.title:"",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"",screenWidth:(null===(l=null===(h=null===(r=this.fingerprint)||void 0===r?void 0:r.screen)||void 0===h?void 0:h.value)||void 0===l?void 0:l.width)||("undefined"!=typeof window&&window.screen?window.screen.width:0),screenHeight:(null===(u=null===(d=null===(c=this.fingerprint)||void 0===c?void 0:c.screen)||void 0===d?void 0:d.value)||void 0===u?void 0:u.height)||("undefined"!=typeof window&&window.screen?window.screen.height:0),viewportWidth:(null===(f=null===(v=null===(p=this.fingerprint)||void 0===p?void 0:p.screen)||void 0===v?void 0:v.value)||void 0===f?void 0:f.viewportWidth)||("undefined"!=typeof window?window.innerWidth:0),viewportHeight:(null===(m=null===(w=null===(g=this.fingerprint)||void 0===g?void 0:g.screen)||void 0===w?void 0:w.value)||void 0===m?void 0:m.viewportHeight)||("undefined"!=typeof window?window.innerHeight:0),gdprMode:this.config.gdprMode,isDev:this.t},b=await this.makeRequest(`/tracking/event?token=${encodeURIComponent(this.config.token)}`,k);if(b.visitorId){if(this.backendVisitorId=b.visitorId,this.visitorIdentityManager&&(null===(y=this.fingerprint)||void 0===y?void 0:y.stableCoreHash))try{await this.visitorIdentityManager.updateVisitorIdFromBackend(b.visitorId,this.fingerprint.stableCoreHash,this.sessionId)}catch(t){this.config.debug&&console.error("[Zaplier] Failed to save backend visitor ID to storage:",t)}this.config.debug&&b.visitorId}if(!b.sessionId||this.sessionId&&!this.sessionId.includes("temp_")){if(this.backendVisitorId&&(!this.sessionId||this.sessionId.includes("temp_"))){const t=this.sessionId;this.sessionId=i(this.backendVisitorId),t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}}else{const t=this.sessionId;this.sessionId=b.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return b}catch(i){this.config.debug&&console.error("[Zaplier] Event sending failed:",i),this.config.retryEnabled&&setTimeout(()=>this.sendEvent(t),5e3)}else this.eventQueue.push(t)}async sendReplayBatch(t){var i;if(!this.isInitialized)return{success:!1,error:"SDK not initialized"};try{const e={sessionId:t.sessionId,userId:this.backendVisitorId,events:t.events,metadata:{...t.metadata,visitorId:this.backendVisitorId,fingerprintHash:null===(i=this.fingerprint)||void 0===i?void 0:i.hash}};this.config.debug&&(e.sessionId,e.events.length);const n=await this.makeRequest(`/replays/record?token=${encodeURIComponent(this.config.token)}`,e,"POST");if(n.sessionId&&n.sessionId!==this.sessionId){const t=this.sessionId;this.sessionId=n.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return n}catch(t){return this.config.debug&&console.error("[Zaplier] Replay batch sending failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async makeRequest(t,i,e="POST"){const n=`${this.config.apiEndpoint}${t}`,s={method:e,headers:{"Content-Type":"application/json"}};"POST"===e&&i&&(s.body=JSON.stringify(i),s.keepalive=!0);try{const t=Promise.race([fetch(n,s),new Promise((t,i)=>setTimeout(()=>i(new Error("Fetch timeout - possibly blocked")),5e3))]),i=await t;if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return await i.json()}catch(n){if(this.antiAdblockManager&&"POST"===e){this.config.debug&&console.warn(`[Zaplier] Standard fetch failed (${n instanceof Error?n.message:String(n)}), trying anti-adblock fallback`);try{const e=await this.antiAdblockManager.send(i,t);if(e.success)return this.config.debug&&(e.method,e.latency),{success:!0,method:e.method}}catch(t){this.config.debug&&console.warn("[Zaplier] Both standard fetch and anti-adblock failed:",t)}}throw n}}updateTrackingEnginesSessionId(t){try{this.o&&this.o.isRecording()&&(this.o.stop(),import("./session-replay-DzEF_WqO.min.js").then(({SessionReplayEngine:i})=>{this.o=new i(t,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()})),this.h&&this.h.isRecording()&&(this.h.stop(),import("./heatmap-BxbXSH7M.min.js").then(({HeatmapEngine:i})=>{this.h=new i(t,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1}),this.antiAdblockManager&&this.h.setAntiAdblockManager(this.antiAdblockManager),this.h.start()})),this.config.debug}catch(t){console.error("[Zaplier] Failed to update tracking engines session ID:",t)}}processEventQueue(){if(0===this.eventQueue.length)return;const t=[...this.eventQueue];this.eventQueue=[],t.forEach(t=>this.sendEvent(t))}isLocalhost(){return!("undefined"==typeof window||!window.location)&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||window.location.hostname.startsWith("192.168.")||window.location.hostname.startsWith("10.")||window.location.hostname.includes("local"))}isDevEnvironment(){if("undefined"==typeof window)return!1;const t=window.location.hostname;return"localhost"===t||"127.0.0.1"===t||"[::1]"===t||t.endsWith(".local")||t.endsWith(".test")||!0===this.config.debug}generateTempSessionId(){const t=new Date,i=t.getFullYear()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0"),e=t.getHours().toString().padStart(2,"0");return`temp_${Date.now()}_${i}_${e}`}generateTempVisitorId(){return`temp_visitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateSessionId(){return this.backendVisitorId?i(this.backendVisitorId):i(this.visitorId||"temp-"+Date.now().toString(36))}track(t,i){this.sendEvent({eventType:t,eventName:t,customData:i})}trackCustomEvent(t,i){return this.sendEvent({eventType:"custom",eventName:t,customData:i}),!0}trackConversion(t,i,e,n){return this.sendEvent({eventType:"conversion",eventName:t,revenue:i,currency:e||"USD",customData:n}),!0}trackPageView(t){this.sendEvent({eventType:"page_view",eventName:"page_view",...t})}trackSPANavigation(t,i){this.trackPageView({url:t||("undefined"!=typeof window&&window.location?window.location.href:""),pageTitle:i||("undefined"!=typeof document?document.title:"")})}trackPurchase(t){this.sendEvent({eventType:"purchase",eventName:"purchase",revenue:t.value||t.revenue,currency:t.currency||"USD",quantity:t.quantity||1,productId:t.productId,customData:{productName:t.productName,orderId:t.orderId,...t.customData}})}trackAddToCart(t){this.sendEvent({eventType:"add_to_cart",eventName:"add_to_cart",revenue:null==t?void 0:t.price,quantity:(null==t?void 0:t.quantity)||1,productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,...null==t?void 0:t.customData}})}trackViewContent(t){this.sendEvent({eventType:"view_content",eventName:"view_content",productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,category:null==t?void 0:t.category,...null==t?void 0:t.customData}})}trackInitiateCheckout(t){this.sendEvent({eventType:"initiate_checkout",eventName:"initiate_checkout",revenue:null==t?void 0:t.value,currency:(null==t?void 0:t.currency)||"USD",quantity:null==t?void 0:t.numItems,customData:null==t?void 0:t.customData})}trackLead(t){this.sendEvent({eventType:"lead",eventName:"lead",customData:t})}identify(t){this.sendEvent({eventType:"identify",eventName:"identify",email:t.email,phone:t.phone,customData:t})}startPresenceTracking(){this.config.presenceTracking=!0,this.config.debug}stopPresenceTracking(){this.config.presenceTracking=!1,this.config.debug}enableAdvancedFeatures(){return this.loadFingerprint()}enableEnhancedTracking(){return this.config.enhancedTracking="true",this.config.gdprMode=!1,this.loadFingerprint(),this.config.debug,!0}disableEnhancedTracking(){this.config.enhancedTracking="false",this.config.gdprMode=!0,this.config.debug}isEnhancedMode(){return"true"===this.config.enhancedTracking&&!this.config.gdprMode}resetScrollTracking(){this.config.debug}getVisitorId(){if(this.backendVisitorId)return this.backendVisitorId;if(this.visitorId)return this.visitorId;if(this.visitorIdentityManager){const t=this.visitorIdentityManager.getCurrentVisitorId();if(t)return this.backendVisitorId=t,this.visitorId=t,t}return null}getUserData(){var t,i,e,n,s,o,a;const r="undefined"!=typeof navigator?{userAgent:navigator.userAgent,language:navigator.language,screen:{width:null!==(i=null===(t=window.screen)||void 0===t?void 0:t.width)&&void 0!==i?i:0,height:null!==(n=null===(e=window.screen)||void 0===e?void 0:e.height)&&void 0!==n?n:0}}:{userAgent:"",language:"",screen:{width:0,height:0}};return{sessionId:null!==(s=this.sessionId)&&void 0!==s?s:"",visitorId:null!==(o=this.getVisitorId())&&void 0!==o?o:void 0,location:{},device:r,journey:[],fingerprint:null===(a=this.fingerprint)||void 0===a?void 0:a.hash}}async getVisitorInfo(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID yet. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;if(this.cachedVisitorInfo)return this.cachedVisitorInfo;try{const i=await this.makeRequest(`/tracking/visitor/${t}?token=${encodeURIComponent(this.config.token)}`,null,"GET");return this.cachedVisitorInfo=i,i}catch{return null}}async getVisitorHistory(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID available. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;try{return await this.makeRequest(`/tracking/visitor/${t}/history?token=${encodeURIComponent(this.config.token)}`,null,"GET")}catch(t){return this.config.debug&&console.error("[Zaplier] Failed to get visitor history:",t),null}}getConversionLikelihood(){return{score:0,level:"unknown",factors:[]}}getUserSegment(){return{segment:"unknown",confidence:0,traits:[]}}}function s(t){return new n(t)}const o=s;if("undefined"!=typeof window){window.Zaplier={init:s,version:"3.0.0"};const t=()=>{const t=document.getElementsByTagName("script");for(const i of Array.from(t))if(i.src&&(i.src.includes("zaplier")||i.src.includes("core.min.js")||i.src.includes("sdk.min.js"))&&i.dataset.token){const t=s({token:i.dataset.token,debug:"true"===i.dataset.debug,replay:"true"===i.dataset.replay,heatmap:"true"===i.dataset.heatmap,gdprMode:"true"===i.dataset.gdprMode,allow_localhost:"true"===i.dataset.allowLocalhost});return window.Zaplier.instance=t,void t.trackPageView()}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}export{n as Z,o as a,i as g,s as i};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
const t=new Set(["token","replay","heatmap","debug","allow_localhost","gdprMode","replaySampleRate"]);function i(t){return function(t){const i=new Date||new Date;return`${t}_${i.getFullYear()}${(i.getMonth()+1).toString().padStart(2,"0")}${i.getDate().toString().padStart(2,"0")}_${i.getHours().toString().padStart(2,"0")}`}(t)}const e={apiEndpoint:"https://api.zaplier.com",retryEnabled:!0,maxRetries:3,retryDelays:[1e3,2e3,4e3],autoTrack:!0,dedupeEnabled:!0,fingerprintEnabled:!0,presenceTracking:!1,heartbeatInterval:3e4,scrollTracking:!0,scrollDepthTracking:!0,gdprCompliant:!0,enhancedTracking:"ask",replaySampling:.1,replayMaskInputs:!0};class n{constructor(i){var n;if(this.version="3.0.0",this.isInitialized=!1,this.eventQueue=[],this.t=!1,!i.token)throw console.error('[Zaplier] Missing required "token" option. Get your token at https://app.zaplier.com/dashboard/keys'),new Error("Zaplier: token is required");if("string"!=typeof i.token||i.token.trim().length<5)throw console.error('[Zaplier] Invalid token format. Token should be a workspace API key (e.g., "ws_abc123...")'),new Error("Zaplier: invalid token format");for(const e of Object.keys(i))t.has(e)||console.warn(`[Zaplier] Unknown config option "${e}". Valid options: ${[...t].join(", ")}`);const s=["replay","heatmap","debug","allow_localhost","gdprMode"];for(const t of s){const e=i[t];void 0!==e&&"boolean"!=typeof e&&console.warn(`[Zaplier] "${t}" should be true or false, got: ${typeof e}`)}let o=i;if(void 0!==i.replaySampleRate){const t=i.replaySampleRate;("number"!=typeof t||t<0||t>1)&&(console.warn(`[Zaplier] "replaySampleRate" must be a number between 0 and 1, got: ${t}. Defaulting to 1.0.`),o={...i,replaySampleRate:1})}this.config={...e,...o,gdprMode:null!==(n=o.gdprMode)&&void 0!==n&&n},this.t=this.isDevEnvironment(),this.heatmap=this.createHeatmapProxy(),this.replay=this.createReplayProxy(),this.autoTrack=this.createAutoTrackProxy(),this.initializeCore()}initializeCore(){try{if(this.config.debug&&this.version,!this.config.allow_localhost&&this.isLocalhost())return void this.config.debug;this.sessionId=this.generateTempSessionId(),this.visitorId=this.generateTempVisitorId(),this.isInitialized=!0,this.processEventQueue(),this.config.debug,"undefined"!=typeof window&&this.scheduleModuleLoading()}catch(t){console.error("[Zaplier] Initialization failed:",t)}}scheduleModuleLoading(){const t=(t,i)=>{"undefined"!=typeof requestIdleCallback?requestIdleCallback(t,{timeout:i}):setTimeout(t,Math.min(i/10,200))};t(async()=>{try{await this.loadFingerprint(),this.config.debug}catch(t){this.config.debug&&console.error("[Zaplier] Deferred fingerprinting failed:",t)}},3e3),t(()=>{this.loadAntiAdblock(),this.config.debug},1e3),this.config.autoTrack&&t(()=>{this.loadAutoTracker(),this.config.debug},1500),this.config.replay&&t(async()=>{await this.loadReplayEngine(),this.config.debug},2e3),this.config.heatmap&&t(()=>{this.loadHeatmapEngine(),this.config.debug},2500)}async loadFingerprint(){if(!this.fingerprint)try{const{getCompleteFingerprint:t,getLightweightFingerprint:i}=await import("./fingerprint-C1MH_xUr.min.js").then(function(t){return t.f}),e=this.config.gdprMode?await i():await t();if(e.success&&e.data){this.fingerprint=e.data,e.data.incognitoDetection&&(this.fingerprint.incognitoDetection={...e.data.incognitoDetection,detectionTimestamp:Date.now(),sdkVersion:this.version});try{const{VisitorIdentityManager:t}=await import("./visitor-persistence-DSIEfVJQ.min.js");this.visitorIdentityManager=new t;const i=await this.visitorIdentityManager.getOrCreateVisitorIdentity({fingerprintHash:e.data.hash,stableCoreHash:e.data.stableCoreHash,deviceFingerprint:e.data.stableCoreHash||e.data.hash,sessionId:this.sessionId,userAgent:navigator.userAgent,ipAddress:void 0});i.visitorId&&!i.pendingBackendResponse&&(this.visitorId=i.visitorId,this.backendVisitorId=i.visitorId),this.config.debug&&(this.visitorId,i.persistenceMethod,i.confidence,i.reused)}catch(t){this.config.debug&&console.error("[Zaplier] Visitor persistence loading failed:",t)}this.config.debug&&(e.collectedComponents,e.data.hash,e.data.stableCoreHash,this.config.gdprMode)}}catch(t){this.config.debug&&console.error("[Zaplier] Fingerprinting failed:",t),this.collectFallbackEntropy()}}collectFallbackEntropy(){try{const t=[navigator.userAgent||"",navigator.language||"",navigator.platform||"",screen.width||0,screen.height||0,screen.colorDepth||0,new Date(2024,0,1).getTimezoneOffset(),navigator.hardwareConcurrency||0,navigator.deviceMemory||0,navigator.maxTouchPoints||0,performance.timeOrigin||0,navigator.plugins?navigator.plugins.length:0].join("|");let i=0;for(let e=0;e<t.length;e++)i=(i<<5)-i+t.charCodeAt(e)&4294967295,i^=i>>>16;this.fingerprint||(this.fingerprint={}),this.fingerprint.fallbackEntropy=Math.abs(i).toString(36)}catch{}}async loadAntiAdblock(){if(!this.antiAdblockManager)try{const{AntiAdblockManager:t}=await import("./anti-adblock-B_aAB361.min.js");this.antiAdblockManager=new t(this.config.apiEndpoint,this.config.token,{enabled:!0,methods:["elysia-websocket","fetch"],fallbackDelay:100,maxRetries:2,debug:this.config.debug})}catch(t){this.config.debug&&console.error("[Zaplier] Anti-adblock loading failed:",t)}}async loadAutoTracker(){if(!this.i)try{const{AutoTracker:t}=await import("./auto-tracker-5ij0Y4C-.min.js");this.i=new t(this,{enabled:!0,trackClicks:!0,trackScrolls:!0,trackViews:!0,trackHovers:!0,trackForms:!0,debug:this.config.debug}),this.i.start()}catch(t){this.config.debug&&console.error("[Zaplier] Auto tracker loading failed:",t)}}shouldRecord(){var t,i;const e="__zp_rs";try{if("undefined"!=typeof window&&window.sessionStorage){const i=sessionStorage.getItem(e);if(null!==i)return"1"===i;const n=null!==(t=this.config.replaySampleRate)&&void 0!==t?t:1,s=Math.random()<n;return sessionStorage.setItem(e,s?"1":"0"),s}}catch{}const n=null!==(i=this.config.replaySampleRate)&&void 0!==i?i:1;return Math.random()<n}async fetchFeatureFlags(){try{const t=await this.makeRequest(`/sdk/features?token=${encodeURIComponent(this.config.token)}`,null,"GET");return!0===(null==t?void 0:t.hasSessionReplay)}catch{return!1}}async loadReplayEngine(){if(!this.o)try{if(!await this.fetchFeatureFlags())return;if(!this.shouldRecord())return void this.config.debug;this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DzEF_WqO.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay loading failed:",t)}}async loadHeatmapEngine(){if(!this.l)try{this.sessionId||(this.sessionId=this.generateSessionId());const{HeatmapEngine:t}=await import("./heatmap-BxbXSH7M.min.js");this.l=new t(this.sessionId,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1}),this.antiAdblockManager&&this.l.setAntiAdblockManager(this.antiAdblockManager),this.l.start()}catch(t){this.config.debug&&console.error("[Zaplier] Heatmap loading failed:",t)}}createHeatmapProxy(){const t=this;return{enable(){t.config.heatmap=!0,!t.l&&t.isInitialized&&t.loadHeatmapEngine(),t.config.debug},disable(){t.config.heatmap=!1,t.l&&(t.l.stop(),t.l=void 0),t.config.debug},enableMouseTracking(){t.l?t.l.enableMouseTracking():t.loadHeatmapEngine().then(()=>{var i;null===(i=t.l)||void 0===i||i.enableMouseTracking()})},disableMouseTracking(){t.l&&t.l.disableMouseTracking()},getStats:()=>t.l?t.l.getStats():null,isRecording:()=>!!t.l&&t.l.isRecording()}}createReplayProxy(){const t=this;return{enable(){t.config.replay=!0,(!t.o&&t.isInitialized||t.o&&!t.o.isRecording())&&t.loadReplayEngineForced(),t.config.debug},disable(){t.config.replay=!1,t.o&&(t.o.stop(),t.o=void 0),t.config.debug},start:async()=>(!t.o&&t.isInitialized&&await t.loadReplayEngineForced(),!!t.o&&t.o.start()),stop(){t.o&&t.o.stop()},isRecording:()=>!!t.o&&t.o.isRecording(),getEventCount:()=>t.o?t.o.getEventCount():0,addFunnelStep(i){t.sendEvent({eventType:"funnel_step",eventName:"funnel_step",customData:i})},markConversion(i){t.trackConversion("funnel_conversion",i.value,i.currency,i)}}}createAutoTrackProxy(){const t=this;return{enable(){t.i?t.i.configure({enabled:!0}):t.loadAutoTracker(),t.config.debug},disable(){t.i&&(t.i.stop(),t.i=void 0),t.config.debug},configure(i){t.i&&t.i.configure(i),t.config.debug},refreshTracking(){t.i&&t.i.refreshTracking(),t.config.debug},getDiagnostics:()=>t.i?t.i.getDiagnostics():null,getStats:()=>t.i?t.i.getStats():null,isEnabled:()=>!!t.i}}async loadReplayEngineForced(){try{this.o&&(this.o.stop(),this.o=void 0),this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DzEF_WqO.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay engine loading failed:",t)}}extractUTMParameters(){const t={};if("undefined"==typeof window||!window.location)return t;try{const i=new URLSearchParams(window.location.search),e=i.get("utm_source"),n=i.get("utm_medium"),s=i.get("utm_campaign"),o=i.get("utm_content"),a=i.get("utm_term"),r=i.get("fbclid"),l=i.get("gclid"),h=i.get("ttclid"),c=i.get("creative_id"),d=i.get("ad_id"),u=i.get("adset_id"),p=i.get("campaign_id"),v=i.get("platform");e&&(t.utmSource=e),n&&(t.utmMedium=n),s&&(t.utmCampaign=s),o&&(t.utmContent=o),a&&(t.utmTerm=a),r&&(t.fbclid=r),l&&(t.gclid=l),h&&(t.ttclid=h),c&&(t.creativeId=c),d&&(t.adId=d),u&&(t.adsetId=u),p&&(t.campaignId=p),v&&(t.platform=v),this.config.debug&&Object.keys(t).length}catch(t){this.config.debug&&console.warn("[Zaplier] Failed to extract UTM parameters:",t)}return t}async sendEvent(t){var e,n,s,o,a,r,l,h,c,d,u,p,v,f,g,w,m,y;if(this.isInitialized)try{const k={visitorId:this.backendVisitorId||null,sessionId:this.sessionId,fingerprintHash:null===(e=this.fingerprint)||void 0===e?void 0:e.hash,stableCoreHash:null===(n=this.fingerprint)||void 0===n?void 0:n.stableCoreHash,stableCoreVector:null===(s=this.fingerprint)||void 0===s?void 0:s.stableCoreVector,fingerprintVector:this.fingerprint||void 0,incognitoDetection:(null===(o=this.fingerprint)||void 0===o?void 0:o.incognitoDetection)&&(void 0!==this.fingerprint.incognitoDetection.likelihood||this.fingerprint.incognitoDetection.methods&&this.fingerprint.incognitoDetection.methods.length>0)?this.fingerprint.incognitoDetection:void 0,fingerprintComponents:(null===(a=this.fingerprint)||void 0===a?void 0:a.components)||{},isSafari:"undefined"!=typeof navigator&&/safari/i.test(navigator.userAgent)&&!/chrome|chromium|opr|edg|edge/i.test(navigator.userAgent),ch:navigator.userAgentData?{brands:navigator.userAgentData.brands||[],platform:navigator.userAgentData.platform||void 0,mobile:navigator.userAgentData.mobile||void 0,model:navigator.userAgentData.model||void 0}:void 0,...this.extractUTMParameters(),...t,timestamp:(new Date).toISOString(),url:"undefined"!=typeof window&&window.location?window.location.href:"",referrer:"undefined"!=typeof document?document.referrer:"",pageTitle:"undefined"!=typeof document?document.title:"",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"",screenWidth:(null===(h=null===(l=null===(r=this.fingerprint)||void 0===r?void 0:r.screen)||void 0===l?void 0:l.value)||void 0===h?void 0:h.width)||("undefined"!=typeof window&&window.screen?window.screen.width:0),screenHeight:(null===(u=null===(d=null===(c=this.fingerprint)||void 0===c?void 0:c.screen)||void 0===d?void 0:d.value)||void 0===u?void 0:u.height)||("undefined"!=typeof window&&window.screen?window.screen.height:0),viewportWidth:(null===(f=null===(v=null===(p=this.fingerprint)||void 0===p?void 0:p.screen)||void 0===v?void 0:v.value)||void 0===f?void 0:f.viewportWidth)||("undefined"!=typeof window?window.innerWidth:0),viewportHeight:(null===(m=null===(w=null===(g=this.fingerprint)||void 0===g?void 0:g.screen)||void 0===w?void 0:w.value)||void 0===m?void 0:m.viewportHeight)||("undefined"!=typeof window?window.innerHeight:0),gdprMode:this.config.gdprMode,isDev:this.t},b=await this.makeRequest(`/tracking/event?token=${encodeURIComponent(this.config.token)}`,k);if(b.visitorId){if(this.backendVisitorId=b.visitorId,this.visitorIdentityManager&&(null===(y=this.fingerprint)||void 0===y?void 0:y.stableCoreHash))try{await this.visitorIdentityManager.updateVisitorIdFromBackend(b.visitorId,this.fingerprint.stableCoreHash,this.sessionId)}catch(t){this.config.debug&&console.error("[Zaplier] Failed to save backend visitor ID to storage:",t)}this.config.debug&&b.visitorId}if(!b.sessionId||this.sessionId&&!this.sessionId.includes("temp_")){if(this.backendVisitorId&&(!this.sessionId||this.sessionId.includes("temp_"))){const t=this.sessionId;this.sessionId=i(this.backendVisitorId),t!==this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}}else{const t=this.sessionId;this.sessionId=b.sessionId,t!==this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return b}catch(i){this.config.debug&&console.error("[Zaplier] Event sending failed:",i),this.config.retryEnabled&&setTimeout(()=>this.sendEvent(t),5e3)}else this.eventQueue.push(t)}async sendReplayBatch(t){var i;if(!this.isInitialized)return{success:!1,error:"SDK not initialized"};try{const e={sessionId:t.sessionId,userId:this.backendVisitorId,events:t.events,metadata:{...t.metadata,visitorId:this.backendVisitorId,fingerprintHash:null===(i=this.fingerprint)||void 0===i?void 0:i.hash}};this.config.debug&&(e.sessionId,e.events.length);const n=await this.makeRequest(`/replays/record?token=${encodeURIComponent(this.config.token)}`,e,"POST");if(n.sessionId&&n.sessionId!==this.sessionId){const t=this.sessionId;this.sessionId=n.sessionId,t!==this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return n}catch(t){return this.config.debug&&console.error("[Zaplier] Replay batch sending failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async makeRequest(t,i,e="POST"){const n=`${this.config.apiEndpoint}${t}`,s={method:e,headers:{"Content-Type":"application/json"}};"POST"===e&&i&&(s.body=JSON.stringify(i),s.keepalive=!0);try{const t=Promise.race([fetch(n,s),new Promise((t,i)=>setTimeout(()=>i(new Error("Fetch timeout - possibly blocked")),5e3))]),i=await t;if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return await i.json()}catch(n){if(this.antiAdblockManager&&"POST"===e){this.config.debug&&console.warn(`[Zaplier] Standard fetch failed (${n instanceof Error?n.message:String(n)}), trying anti-adblock fallback`);try{const e=await this.antiAdblockManager.send(i,t);if(e.success)return this.config.debug&&(e.method,e.latency),{success:!0,method:e.method}}catch(t){this.config.debug&&console.warn("[Zaplier] Both standard fetch and anti-adblock failed:",t)}}throw n}}updateTrackingEnginesSessionId(t){try{this.o&&this.o.isRecording()&&(this.o.stop(),import("./session-replay-DzEF_WqO.min.js").then(({SessionReplayEngine:i})=>{this.o=new i(t,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()})),this.l&&this.l.isRecording()&&(this.l.stop(),import("./heatmap-BxbXSH7M.min.js").then(({HeatmapEngine:i})=>{this.l=new i(t,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1}),this.antiAdblockManager&&this.l.setAntiAdblockManager(this.antiAdblockManager),this.l.start()})),this.config.debug}catch(t){console.error("[Zaplier] Failed to update tracking engines session ID:",t)}}processEventQueue(){if(0===this.eventQueue.length)return;const t=[...this.eventQueue];this.eventQueue=[],t.forEach(t=>this.sendEvent(t))}isLocalhost(){return!("undefined"==typeof window||!window.location)&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||window.location.hostname.startsWith("192.168.")||window.location.hostname.startsWith("10.")||window.location.hostname.includes("local"))}isDevEnvironment(){if("undefined"==typeof window)return!1;const t=window.location.hostname;return"localhost"===t||"127.0.0.1"===t||"[::1]"===t||t.endsWith(".local")||t.endsWith(".test")||!0===this.config.debug}generateTempSessionId(){const t=new Date,i=t.getFullYear()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0"),e=t.getHours().toString().padStart(2,"0");return`temp_${Date.now()}_${i}_${e}`}generateTempVisitorId(){return`temp_visitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateSessionId(){return this.backendVisitorId?i(this.backendVisitorId):i(this.visitorId||"temp-"+Date.now().toString(36))}track(t,i){this.sendEvent({eventType:t,eventName:t,customData:i})}trackCustomEvent(t,i){return this.sendEvent({eventType:"custom",eventName:t,customData:i}),!0}trackConversion(t,i,e,n){return this.sendEvent({eventType:"conversion",eventName:t,revenue:i,currency:e||"USD",customData:n}),!0}trackPageView(t){this.sendEvent({eventType:"page_view",eventName:"page_view",...t})}trackSPANavigation(t,i){this.trackPageView({url:t||("undefined"!=typeof window&&window.location?window.location.href:""),pageTitle:i||("undefined"!=typeof document?document.title:"")})}trackPurchase(t){this.sendEvent({eventType:"purchase",eventName:"purchase",revenue:t.value||t.revenue,currency:t.currency||"USD",quantity:t.quantity||1,productId:t.productId,customData:{productName:t.productName,orderId:t.orderId,...t.customData}})}trackAddToCart(t){this.sendEvent({eventType:"add_to_cart",eventName:"add_to_cart",revenue:null==t?void 0:t.price,quantity:(null==t?void 0:t.quantity)||1,productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,...null==t?void 0:t.customData}})}trackViewContent(t){this.sendEvent({eventType:"view_content",eventName:"view_content",productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,category:null==t?void 0:t.category,...null==t?void 0:t.customData}})}trackInitiateCheckout(t){this.sendEvent({eventType:"initiate_checkout",eventName:"initiate_checkout",revenue:null==t?void 0:t.value,currency:(null==t?void 0:t.currency)||"USD",quantity:null==t?void 0:t.numItems,customData:null==t?void 0:t.customData})}trackLead(t){this.sendEvent({eventType:"lead",eventName:"lead",customData:t})}identify(t){this.sendEvent({eventType:"identify",eventName:"identify",email:t.email,phone:t.phone,customData:t})}startPresenceTracking(){this.config.presenceTracking=!0,this.config.debug}stopPresenceTracking(){this.config.presenceTracking=!1,this.config.debug}enableAdvancedFeatures(){return this.loadFingerprint()}enableEnhancedTracking(){return this.config.enhancedTracking="true",this.config.gdprMode=!1,this.loadFingerprint(),this.config.debug,!0}disableEnhancedTracking(){this.config.enhancedTracking="false",this.config.gdprMode=!0,this.config.debug}isEnhancedMode(){return"true"===this.config.enhancedTracking&&!this.config.gdprMode}resetScrollTracking(){this.config.debug}getVisitorId(){if(this.backendVisitorId)return this.backendVisitorId;if(this.visitorId)return this.visitorId;if(this.visitorIdentityManager){const t=this.visitorIdentityManager.getCurrentVisitorId();if(t)return this.backendVisitorId=t,this.visitorId=t,t}return null}getUserData(){var t,i,e,n,s,o,a;const r="undefined"!=typeof navigator?{userAgent:navigator.userAgent,language:navigator.language,screen:{width:null!==(i=null===(t=window.screen)||void 0===t?void 0:t.width)&&void 0!==i?i:0,height:null!==(n=null===(e=window.screen)||void 0===e?void 0:e.height)&&void 0!==n?n:0}}:{userAgent:"",language:"",screen:{width:0,height:0}};return{sessionId:null!==(s=this.sessionId)&&void 0!==s?s:"",visitorId:null!==(o=this.getVisitorId())&&void 0!==o?o:void 0,location:{},device:r,journey:[],fingerprint:null===(a=this.fingerprint)||void 0===a?void 0:a.hash}}async getVisitorInfo(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID yet. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;if(this.cachedVisitorInfo)return this.cachedVisitorInfo;try{const i=await this.makeRequest(`/tracking/visitor/${t}?token=${encodeURIComponent(this.config.token)}`,null,"GET");return this.cachedVisitorInfo=i,i}catch{return null}}async getVisitorHistory(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID available. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;try{return await this.makeRequest(`/tracking/visitor/${t}/history?token=${encodeURIComponent(this.config.token)}`,null,"GET")}catch(t){return this.config.debug&&console.error("[Zaplier] Failed to get visitor history:",t),null}}getConversionLikelihood(){return{score:0,level:"unknown",factors:[]}}getUserSegment(){return{segment:"unknown",confidence:0,traits:[]}}}function s(t){return new n(t)}const o=s;if("undefined"!=typeof window){window.Zaplier={init:s,version:"3.0.0"};const t=()=>{const t=document.getElementsByTagName("script");for(const i of Array.from(t))if(i.src&&(i.src.includes("zaplier")||i.src.includes("core.min.js")||i.src.includes("sdk.min.js"))&&i.dataset.token){const t=s({token:i.dataset.token,debug:"true"===i.dataset.debug,replay:"true"===i.dataset.replay,heatmap:"true"===i.dataset.heatmap,gdprMode:"true"===i.dataset.gdprMode,allow_localhost:"true"===i.dataset.allowLocalhost});return window.Zaplier.instance=t,void t.trackPageView()}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}export{n as Z,o as a,i as g,s as i};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
const t=new Set(["token","replay","heatmap","debug","allow_localhost","gdprMode","replaySampleRate"]);function i(t){return function(t){const i=new Date||new Date;return`${t}_${i.getFullYear()}${(i.getMonth()+1).toString().padStart(2,"0")}${i.getDate().toString().padStart(2,"0")}_${i.getHours().toString().padStart(2,"0")}`}(t)}const e={apiEndpoint:"https://api.zaplier.com",retryEnabled:!0,maxRetries:3,retryDelays:[1e3,2e3,4e3],autoTrack:!0,dedupeEnabled:!0,fingerprintEnabled:!0,presenceTracking:!1,heartbeatInterval:3e4,scrollTracking:!0,scrollDepthTracking:!0,gdprCompliant:!0,enhancedTracking:"ask",replaySampling:.1,replayMaskInputs:!0};class n{constructor(i){var n;if(this.version="1.9.0",this.isInitialized=!1,this.eventQueue=[],this.t=!1,!i.token)throw console.error('[Zaplier] Missing required "token" option. Get your token at https://app.zaplier.com/dashboard/keys'),new Error("Zaplier: token is required");if("string"!=typeof i.token||i.token.trim().length<5)throw console.error('[Zaplier] Invalid token format. Token should be a workspace API key (e.g., "ws_abc123...")'),new Error("Zaplier: invalid token format");for(const e of Object.keys(i))t.has(e)||console.warn(`[Zaplier] Unknown config option "${e}". Valid options: ${[...t].join(", ")}`);const s=["replay","heatmap","debug","allow_localhost","gdprMode"];for(const t of s){const e=i[t];void 0!==e&&"boolean"!=typeof e&&console.warn(`[Zaplier] "${t}" should be true or false, got: ${typeof e}`)}let o=i;if(void 0!==i.replaySampleRate){const t=i.replaySampleRate;("number"!=typeof t||t<0||t>1)&&(console.warn(`[Zaplier] "replaySampleRate" must be a number between 0 and 1, got: ${t}. Defaulting to 1.0.`),o={...i,replaySampleRate:1})}this.config={...e,...o,gdprMode:null!==(n=o.gdprMode)&&void 0!==n&&n},this.t=this.isDevEnvironment(),this.heatmap=this.createHeatmapProxy(),this.replay=this.createReplayProxy(),this.autoTrack=this.createAutoTrackProxy(),this.initializeCore()}initializeCore(){try{if(this.config.debug&&this.version,!this.config.allow_localhost&&this.isLocalhost())return void this.config.debug;this.sessionId=this.generateTempSessionId(),this.visitorId=this.generateTempVisitorId(),this.isInitialized=!0,this.processEventQueue(),this.config.debug,"undefined"!=typeof window&&this.scheduleModuleLoading()}catch(t){console.error("[Zaplier] Initialization failed:",t)}}scheduleModuleLoading(){const t=(t,i)=>{"undefined"!=typeof requestIdleCallback?requestIdleCallback(t,{timeout:i}):setTimeout(t,Math.min(i/10,200))};t(async()=>{try{await this.loadFingerprint(),this.config.debug}catch(t){this.config.debug&&console.error("[Zaplier] Deferred fingerprinting failed:",t)}},3e3),t(()=>{this.loadAntiAdblock(),this.config.debug},1e3),this.config.autoTrack&&t(()=>{this.loadAutoTracker(),this.config.debug},1500),this.config.replay&&t(async()=>{await this.loadReplayEngine(),this.config.debug},2e3),this.config.heatmap&&t(()=>{this.loadHeatmapEngine(),this.config.debug},2500)}async loadFingerprint(){if(!this.fingerprint)try{const{getCompleteFingerprint:t,getLightweightFingerprint:i}=await import("./fingerprint-C1MH_xUr.min.js").then(function(t){return t.f}),e=this.config.gdprMode?await i():await t();if(e.success&&e.data){this.fingerprint=e.data,e.data.incognitoDetection&&(this.fingerprint.incognitoDetection={...e.data.incognitoDetection,detectionTimestamp:Date.now(),sdkVersion:this.version});try{const{VisitorIdentityManager:t}=await import("./visitor-persistence-Djomq4wG.min.js");this.visitorIdentityManager=new t;const i=await this.visitorIdentityManager.getOrCreateVisitorIdentity({fingerprintHash:e.data.hash,stableCoreHash:e.data.stableCoreHash,deviceFingerprint:e.data.stableCoreHash||e.data.hash,sessionId:this.sessionId,userAgent:navigator.userAgent,ipAddress:void 0});i.visitorId&&!i.pendingBackendResponse&&(this.visitorId=i.visitorId,this.backendVisitorId=i.visitorId),this.config.debug&&(this.visitorId,i.persistenceMethod,i.confidence,i.reused)}catch(t){this.config.debug&&console.error("[Zaplier] Visitor persistence loading failed:",t)}this.config.debug&&(e.collectedComponents,e.data.hash,e.data.stableCoreHash,this.config.gdprMode)}}catch(t){this.config.debug&&console.error("[Zaplier] Fingerprinting failed:",t),this.collectFallbackEntropy()}}collectFallbackEntropy(){try{const t=[navigator.userAgent||"",navigator.language||"",navigator.platform||"",screen.width||0,screen.height||0,screen.colorDepth||0,new Date(2024,0,1).getTimezoneOffset(),navigator.hardwareConcurrency||0,navigator.deviceMemory||0,navigator.maxTouchPoints||0,performance.timeOrigin||0,navigator.plugins?navigator.plugins.length:0].join("|");let i=0;for(let e=0;e<t.length;e++)i=(i<<5)-i+t.charCodeAt(e)&4294967295,i^=i>>>16;this.fingerprint||(this.fingerprint={}),this.fingerprint.fallbackEntropy=Math.abs(i).toString(36)}catch{}}async loadAntiAdblock(){if(!this.antiAdblockManager)try{const{AntiAdblockManager:t}=await import("./anti-adblock-B_7p9rSc.min.js");this.antiAdblockManager=new t(this.config.apiEndpoint,this.config.token,{enabled:!0,methods:["elysia-websocket","fetch"],fallbackDelay:100,maxRetries:2,debug:this.config.debug})}catch(t){this.config.debug&&console.error("[Zaplier] Anti-adblock loading failed:",t)}}async loadAutoTracker(){if(!this.i)try{const{AutoTracker:t}=await import("./auto-tracker-5ij0Y4C-.min.js");this.i=new t(this,{enabled:!0,trackClicks:!0,trackScrolls:!0,trackViews:!0,trackHovers:!0,trackForms:!0,debug:this.config.debug}),this.i.start()}catch(t){this.config.debug&&console.error("[Zaplier] Auto tracker loading failed:",t)}}shouldRecord(){var t,i;const e="__zp_rs";try{if("undefined"!=typeof window&&window.sessionStorage){const i=sessionStorage.getItem(e);if(null!==i)return"1"===i;const n=null!==(t=this.config.replaySampleRate)&&void 0!==t?t:1,s=Math.random()<n;return sessionStorage.setItem(e,s?"1":"0"),s}}catch{}const n=null!==(i=this.config.replaySampleRate)&&void 0!==i?i:1;return Math.random()<n}async fetchFeatureFlags(){try{const t=await this.makeRequest(`/sdk/features?token=${encodeURIComponent(this.config.token)}`,null,"GET");return!0===(null==t?void 0:t.hasSessionReplay)}catch{return this.config.debug&&console.warn("[Zaplier] Feature flag fetch failed, assuming replay enabled"),!0}}async loadReplayEngine(){if(!this.o)try{if(!await this.fetchFeatureFlags())return;if(!this.shouldRecord())return void this.config.debug;this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DsIhuKDJ.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay loading failed:",t)}}async loadHeatmapEngine(){if(!this.l)try{this.sessionId||(this.sessionId=this.generateSessionId());const{HeatmapEngine:t}=await import("./heatmap-BxbXSH7M.min.js");this.l=new t(this.sessionId,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1}),this.antiAdblockManager&&this.l.setAntiAdblockManager(this.antiAdblockManager),this.l.start()}catch(t){this.config.debug&&console.error("[Zaplier] Heatmap loading failed:",t)}}createHeatmapProxy(){const t=this;return{enable(){t.config.heatmap=!0,!t.l&&t.isInitialized&&t.loadHeatmapEngine(),t.config.debug},disable(){t.config.heatmap=!1,t.l&&(t.l.stop(),t.l=void 0),t.config.debug},enableMouseTracking(){t.l?t.l.enableMouseTracking():t.loadHeatmapEngine().then(()=>{var i;null===(i=t.l)||void 0===i||i.enableMouseTracking()})},disableMouseTracking(){t.l&&t.l.disableMouseTracking()},getStats:()=>t.l?t.l.getStats():null,isRecording:()=>!!t.l&&t.l.isRecording()}}createReplayProxy(){const t=this;return{enable(){t.config.replay=!0,(!t.o&&t.isInitialized||t.o&&!t.o.isRecording())&&t.loadReplayEngineForced(),t.config.debug},disable(){t.config.replay=!1,t.o&&(t.o.stop(),t.o=void 0),t.config.debug},start:async()=>(!t.o&&t.isInitialized&&await t.loadReplayEngineForced(),!!t.o&&t.o.start()),stop(){t.o&&t.o.stop()},isRecording:()=>!!t.o&&t.o.isRecording(),getEventCount:()=>t.o?t.o.getEventCount():0,addFunnelStep(i){t.sendEvent({eventType:"funnel_step",eventName:"funnel_step",customData:i})},markConversion(i){t.trackConversion("funnel_conversion",i.value,i.currency,i)}}}createAutoTrackProxy(){const t=this;return{enable(){t.i?t.i.configure({enabled:!0}):t.loadAutoTracker(),t.config.debug},disable(){t.i&&(t.i.stop(),t.i=void 0),t.config.debug},configure(i){t.i&&t.i.configure(i),t.config.debug},refreshTracking(){t.i&&t.i.refreshTracking(),t.config.debug},getDiagnostics:()=>t.i?t.i.getDiagnostics():null,getStats:()=>t.i?t.i.getStats():null,isEnabled:()=>!!t.i}}async loadReplayEngineForced(){try{this.o&&(this.o.stop(),this.o=void 0),this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DsIhuKDJ.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay engine loading failed:",t)}}extractUTMParameters(){const t={};if("undefined"==typeof window||!window.location)return t;try{const i=new URLSearchParams(window.location.search),e=i.get("utm_source"),n=i.get("utm_medium"),s=i.get("utm_campaign"),o=i.get("utm_content"),a=i.get("utm_term"),r=i.get("fbclid"),l=i.get("gclid"),h=i.get("ttclid"),c=i.get("creative_id"),d=i.get("ad_id"),u=i.get("adset_id"),p=i.get("campaign_id"),v=i.get("platform");e&&(t.utmSource=e),n&&(t.utmMedium=n),s&&(t.utmCampaign=s),o&&(t.utmContent=o),a&&(t.utmTerm=a),r&&(t.fbclid=r),l&&(t.gclid=l),h&&(t.ttclid=h),c&&(t.creativeId=c),d&&(t.adId=d),u&&(t.adsetId=u),p&&(t.campaignId=p),v&&(t.platform=v),this.config.debug&&Object.keys(t).length}catch(t){this.config.debug&&console.warn("[Zaplier] Failed to extract UTM parameters:",t)}return t}async sendEvent(t){var e,n,s,o,a,r,l,h,c,d,u,p,v,f,g,w,m,y,k;if(!this.isInitialized)return this.eventQueue.length>=100&&this.eventQueue.shift(),void this.eventQueue.push(t);try{const k={visitorId:this.backendVisitorId||null,sessionId:this.sessionId,fingerprintHash:null===(e=this.fingerprint)||void 0===e?void 0:e.hash,stableCoreHash:null===(n=this.fingerprint)||void 0===n?void 0:n.stableCoreHash,stableCoreVector:null===(s=this.fingerprint)||void 0===s?void 0:s.stableCoreVector,fingerprintVector:this.fingerprint||void 0,incognitoDetection:(null===(o=this.fingerprint)||void 0===o?void 0:o.incognitoDetection)&&(void 0!==this.fingerprint.incognitoDetection.likelihood||this.fingerprint.incognitoDetection.methods&&this.fingerprint.incognitoDetection.methods.length>0)?this.fingerprint.incognitoDetection:void 0,fingerprintComponents:(null===(a=this.fingerprint)||void 0===a?void 0:a.components)||{},isSafari:"undefined"!=typeof navigator&&/safari/i.test(navigator.userAgent)&&!/chrome|chromium|opr|edg|edge/i.test(navigator.userAgent),ch:navigator.userAgentData?{brands:navigator.userAgentData.brands||[],platform:navigator.userAgentData.platform||void 0,mobile:navigator.userAgentData.mobile||void 0,model:navigator.userAgentData.model||void 0}:void 0,...this.extractUTMParameters(),...t,timestamp:(new Date).toISOString(),url:"undefined"!=typeof window&&window.location?window.location.href:"",referrer:"undefined"!=typeof document?document.referrer:"",pageTitle:"undefined"!=typeof document?document.title:"",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"",screenWidth:(null===(h=null===(l=null===(r=this.fingerprint)||void 0===r?void 0:r.screen)||void 0===l?void 0:l.value)||void 0===h?void 0:h.width)||("undefined"!=typeof window&&window.screen?window.screen.width:0),screenHeight:(null===(u=null===(d=null===(c=this.fingerprint)||void 0===c?void 0:c.screen)||void 0===d?void 0:d.value)||void 0===u?void 0:u.height)||("undefined"!=typeof window&&window.screen?window.screen.height:0),viewportWidth:(null===(f=null===(v=null===(p=this.fingerprint)||void 0===p?void 0:p.screen)||void 0===v?void 0:v.value)||void 0===f?void 0:f.viewportWidth)||("undefined"!=typeof window?window.innerWidth:0),viewportHeight:(null===(m=null===(w=null===(g=this.fingerprint)||void 0===g?void 0:g.screen)||void 0===w?void 0:w.value)||void 0===m?void 0:m.viewportHeight)||("undefined"!=typeof window?window.innerHeight:0),gdprMode:this.config.gdprMode,isDev:this.t},b=await this.makeRequest(`/tracking/event?token=${encodeURIComponent(this.config.token)}`,k);if(b.visitorId){if(this.backendVisitorId=b.visitorId,this.visitorIdentityManager&&(null===(y=this.fingerprint)||void 0===y?void 0:y.stableCoreHash))try{await this.visitorIdentityManager.updateVisitorIdFromBackend(b.visitorId,this.fingerprint.stableCoreHash,this.sessionId)}catch(t){this.config.debug&&console.error("[Zaplier] Failed to save backend visitor ID to storage:",t)}this.config.debug&&b.visitorId}if(!b.sessionId||this.sessionId&&!this.sessionId.includes("temp_")){if(this.backendVisitorId&&(!this.sessionId||this.sessionId.includes("temp_"))){const t=this.sessionId;this.sessionId=i(this.backendVisitorId),t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}}else{const t=this.sessionId;this.sessionId=b.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return b}catch(i){if(this.config.debug&&console.error("[Zaplier] Event sending failed:",i),this.config.retryEnabled){const i=t.h||0;if(i<this.config.maxRetries){const e=null!==(k=this.config.retryDelays[i])&&void 0!==k?k:5e3;setTimeout(()=>{this.sendEvent({...t,h:i+1})},e)}else this.config.debug&&console.warn("[Zaplier] Event dropped after max retries:",t.eventType)}}}async sendReplayBatch(t){var i;if(!this.isInitialized)return{success:!1,error:"SDK not initialized"};try{const e={sessionId:t.sessionId,userId:this.backendVisitorId,events:t.events,metadata:{...t.metadata,visitorId:this.backendVisitorId,fingerprintHash:null===(i=this.fingerprint)||void 0===i?void 0:i.hash}};this.config.debug&&(e.sessionId,e.events.length);const n=await this.makeRequest(`/replays/record?token=${encodeURIComponent(this.config.token)}`,e,"POST");if(n.sessionId&&n.sessionId!==this.sessionId){const t=this.sessionId;this.sessionId=n.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return n}catch(t){return this.config.debug&&console.error("[Zaplier] Replay batch sending failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async makeRequest(t,i,e="POST"){const n=`${this.config.apiEndpoint}${t}`,s={method:e,headers:{"Content-Type":"application/json"}};"POST"===e&&i&&(s.body=JSON.stringify(i),s.keepalive=!0);try{const t=Promise.race([fetch(n,s),new Promise((t,i)=>setTimeout(()=>i(new Error("Fetch timeout - possibly blocked")),5e3))]),i=await t;if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return await i.json()}catch(n){if(this.antiAdblockManager&&"POST"===e){this.config.debug&&console.warn(`[Zaplier] Standard fetch failed (${n instanceof Error?n.message:String(n)}), trying anti-adblock fallback`);try{const e=await this.antiAdblockManager.send(i,t);if(e.success)return this.config.debug&&(e.method,e.latency),{success:!0,method:e.method}}catch(t){this.config.debug&&console.warn("[Zaplier] Both standard fetch and anti-adblock failed:",t)}}throw n}}updateTrackingEnginesSessionId(t){try{if(this.o){const i=this.o.isRecording();this.o.stop(),import("./session-replay-DsIhuKDJ.min.js").then(({SessionReplayEngine:e})=>{this.o=new e(t,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),i&&this.o.start()})}if(this.l){const i=this.l.isRecording();this.l.stop(),import("./heatmap-BxbXSH7M.min.js").then(({HeatmapEngine:e})=>{this.l=new e(t,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1}),this.antiAdblockManager&&this.l.setAntiAdblockManager(this.antiAdblockManager),i&&this.l.start()})}this.config.debug}catch(t){console.error("[Zaplier] Failed to update tracking engines session ID:",t)}}processEventQueue(){if(0===this.eventQueue.length)return;const t=[...this.eventQueue];this.eventQueue=[],t.forEach(t=>this.sendEvent(t))}isLocalhost(){return!("undefined"==typeof window||!window.location)&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||window.location.hostname.startsWith("192.168.")||window.location.hostname.startsWith("10.")||window.location.hostname.includes("local"))}isDevEnvironment(){if("undefined"==typeof window)return!1;const t=window.location.hostname;return"localhost"===t||"127.0.0.1"===t||"[::1]"===t||t.endsWith(".local")||t.endsWith(".test")||!0===this.config.debug}generateTempSessionId(){const t=new Date,i=t.getFullYear()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0"),e=t.getHours().toString().padStart(2,"0");return`temp_${Date.now()}_${i}_${e}`}generateTempVisitorId(){return`temp_visitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateSessionId(){return this.backendVisitorId?i(this.backendVisitorId):i(this.visitorId||"temp-"+Date.now().toString(36))}track(t,i){this.sendEvent({eventType:t,eventName:t,customData:i})}trackCustomEvent(t,i){return this.sendEvent({eventType:"custom",eventName:t,customData:i}),!0}trackConversion(t,i,e,n){return this.sendEvent({eventType:"conversion",eventName:t,revenue:i,currency:e||"USD",customData:n}),!0}trackPageView(t){this.sendEvent({eventType:"page_view",eventName:"page_view",...t})}trackSPANavigation(t,i){this.trackPageView({url:t||("undefined"!=typeof window&&window.location?window.location.href:""),pageTitle:i||("undefined"!=typeof document?document.title:"")})}trackPurchase(t){this.sendEvent({eventType:"purchase",eventName:"purchase",revenue:t.value||t.revenue,currency:t.currency||"USD",quantity:t.quantity||1,productId:t.productId,customData:{productName:t.productName,orderId:t.orderId,...t.customData}})}trackAddToCart(t){this.sendEvent({eventType:"add_to_cart",eventName:"add_to_cart",revenue:null==t?void 0:t.price,quantity:(null==t?void 0:t.quantity)||1,productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,...null==t?void 0:t.customData}})}trackViewContent(t){this.sendEvent({eventType:"view_content",eventName:"view_content",productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,category:null==t?void 0:t.category,...null==t?void 0:t.customData}})}trackInitiateCheckout(t){this.sendEvent({eventType:"initiate_checkout",eventName:"initiate_checkout",revenue:null==t?void 0:t.value,currency:(null==t?void 0:t.currency)||"USD",quantity:null==t?void 0:t.numItems,customData:null==t?void 0:t.customData})}trackLead(t){this.sendEvent({eventType:"lead",eventName:"lead",customData:t})}identify(t){this.sendEvent({eventType:"identify",eventName:"identify",email:t.email,phone:t.phone,customData:t})}startPresenceTracking(){this.config.presenceTracking=!0,this.config.debug}stopPresenceTracking(){this.config.presenceTracking=!1,this.config.debug}enableAdvancedFeatures(){return this.loadFingerprint()}enableEnhancedTracking(){return this.config.enhancedTracking="true",this.config.gdprMode=!1,this.loadFingerprint(),this.config.debug,!0}disableEnhancedTracking(){this.config.enhancedTracking="false",this.config.gdprMode=!0,this.config.debug}isEnhancedMode(){return"true"===this.config.enhancedTracking&&!this.config.gdprMode}resetScrollTracking(){this.config.debug}getVisitorId(){if(this.backendVisitorId)return this.backendVisitorId;if(this.visitorId)return this.visitorId;if(this.visitorIdentityManager){const t=this.visitorIdentityManager.getCurrentVisitorId();if(t)return this.backendVisitorId=t,this.visitorId=t,t}return null}getUserData(){var t,i,e,n,s,o,a;const r="undefined"!=typeof navigator?{userAgent:navigator.userAgent,language:navigator.language,screen:{width:null!==(i=null===(t=window.screen)||void 0===t?void 0:t.width)&&void 0!==i?i:0,height:null!==(n=null===(e=window.screen)||void 0===e?void 0:e.height)&&void 0!==n?n:0}}:{userAgent:"",language:"",screen:{width:0,height:0}};return{sessionId:null!==(s=this.sessionId)&&void 0!==s?s:"",visitorId:null!==(o=this.getVisitorId())&&void 0!==o?o:void 0,location:{},device:r,journey:[],fingerprint:null===(a=this.fingerprint)||void 0===a?void 0:a.hash}}async getVisitorInfo(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID yet. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;if(this.cachedVisitorInfo)return this.cachedVisitorInfo;try{const i=await this.makeRequest(`/tracking/visitor/${t}?token=${encodeURIComponent(this.config.token)}`,null,"GET");return this.cachedVisitorInfo=i,i}catch{return null}}async getVisitorHistory(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID available. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;try{return await this.makeRequest(`/tracking/visitor/${t}/history?token=${encodeURIComponent(this.config.token)}`,null,"GET")}catch(t){return this.config.debug&&console.error("[Zaplier] Failed to get visitor history:",t),null}}getConversionLikelihood(){return{score:0,level:"unknown",factors:[]}}getUserSegment(){return{segment:"unknown",confidence:0,traits:[]}}}function s(t){return new n(t)}const o=s;if("undefined"!=typeof window){window.Zaplier={init:s,version:"1.9.0"};const t=()=>{const t=document.getElementsByTagName("script");for(const i of Array.from(t))if(i.src&&(i.src.includes("zaplier")||i.src.includes("core.min.js")||i.src.includes("sdk.min.js"))&&i.dataset.token){const t=s({token:i.dataset.token,debug:"true"===i.dataset.debug,replay:"true"===i.dataset.replay,heatmap:"true"===i.dataset.heatmap,gdprMode:"true"===i.dataset.gdprMode,allow_localhost:"true"===i.dataset.allowLocalhost});return window.Zaplier.instance=t,void t.trackPageView()}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}export{n as Z,o as a,i as g,s as i};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
function r(){var r,n,t,e;try{const o=screen,i=null!==(r=o.availTop)&&void 0!==r?r:0,a=null!==(n=o.availLeft)&&void 0!==n?n:0,u=null!==(t=o.availWidth)&&void 0!==t?t:o.width,c=null!==(e=o.availHeight)&&void 0!==e?e:o.height,l=i||null,d=o.width-u-a||null,v=o.height-c-i||null,f=a||null;if(null===l&&null===d&&null===v&&null===f)return null;const s=r=>null===r?null:10*Math.round(r/10);return{top:s(l),right:s(d),bottom:s(v),left:s(f)}}catch{return null}}function n(){var r,n,t,e;try{const o=(null===(r=navigator.platform)||void 0===r?void 0:r.toLowerCase())||"",i=(null===(n=navigator.userAgent)||void 0===n?void 0:n.toLowerCase())||"";if(o.includes("win")&&(i.includes("wow64")||i.includes("x64")||i.includes("x86_64")))return 0;if(o.includes("linux")&&(o.includes("x86_64")||i.includes("x86_64")))return 0;if(o.includes("mac")&&(o.includes("intel")||i.includes("intel mac")))return 0;if(o.includes("x86")||o.includes("x64")||o.includes("intel")||o.includes("amd64")||i.includes("x86")||i.includes("amd64"))return 0;if(o.includes("arm")||i.includes("arm")||i.includes("aarch64")||o.includes("aarch64"))return 255;try{const r=document.createElement("canvas"),n=r.getContext("webgl")||r.getContext("experimental-webgl");if(n&&"getExtension"in n&&"getParameter"in n){const r=n.getExtension("WEBGL_debug_renderer_info");if(r){const o=(null===(t=n.getParameter(r.UNMASKED_VENDOR_WEBGL))||void 0===t?void 0:t.toLowerCase())||"",i=(null===(e=n.getParameter(r.UNMASKED_RENDERER_WEBGL))||void 0===e?void 0:e.toLowerCase())||"";if(o.includes("intel")||o.includes("nvidia")||o.includes("amd")||i.includes("intel")||i.includes("nvidia")||i.includes("amd")||i.includes("radeon")||i.includes("geforce")||i.includes("quadro")||i.includes("iris")||i.includes("uhd")||i.includes("hd graphics"))return 0;if(i.includes("mali")||i.includes("adreno")||i.includes("powervr")||i.includes("tegra")||i.includes("apple gpu")||o.includes("arm")||i.includes("videocore"))return 255}}}catch{}try{const r=new Float32Array(1),n=new Uint8Array(r.buffer);r[0]=1/0,r[0]=r[0]-r[0];const t=n[3];return o.includes("linux"),t}catch{return}}catch{return}}function t(){try{const r=navigator;let n=0;void 0!==r.maxTouchPoints?n=r.maxTouchPoints:void 0!==r.msMaxTouchPoints&&(n=r.msMaxTouchPoints);let t=!1;try{document.createEvent("TouchEvent"),t=!0}catch{t=!1}return{maxTouchPoints:n,touchEvent:t,touchStart:"ontouchstart"in window}}catch{return}}function e(){const r=[],n=["chrome","safari","__crWeb","__gCrWeb","yandex","__yb","__ybro","__firefox__","__edgeTrackingPreventionStatistics","webkit","oprt","samsungAr","ucweb","UCShellJava","puffinDevice"];for(const t of n){const n=window[t];n&&"object"==typeof n&&r.push(t)}return r.sort()}function o(){try{const r=navigator.deviceMemory;if("number"==typeof r)return Math.round(r);if("string"==typeof r){const n=parseFloat(r);return isNaN(n)?void 0:Math.round(n)}return}catch{return}}function i(){try{return screen.colorDepth||void 0}catch{return}}function a(){try{for(const r of["rec2020","p3","srgb"])if(window.matchMedia(`(color-gamut: ${r})`).matches)return r;return}catch{return}}function u(){return{screenFrame:r(),hardwareConcurrency:navigator.hardwareConcurrency||void 0,deviceMemory:o(),architecture:n(),touchSupport:t(),vendorFlavors:e(),cpuClass:navigator.cpuClass||void 0,colorDepth:i(),colorGamut:a()}}export{u as collectDeviceSignals};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Zaplier SDK v3.0.0 - Unified SDK
|
|
3
|
+
* Advanced privacy-first tracking with code splitting
|
|
4
|
+
* (c) 2026 Zaplier Team
|
|
5
|
+
*/
|
|
6
|
+
import{g as t}from"./fingerprint-C1MH_xUr.min.js";function e(){const t=atob;return{adBlock:["#ad-banner",".advertisement",t("I2FkLWNvbnRhaW5lcg=="),t("LmFkdmVydGlzZW1lbnQ="),t("W2NsYXNzKj0iYWQtIl0=")],uBlockOrigin:["#ublock-stats",".adsbygoogle",t("I2dvb2dsZV9hZHM="),t("LmFkc2J5Z29vZ2xl"),t("LnVibG9jay1ibG9ja2Vk")],adGuardBase:[".BetterJsPopOverlay",t("I2FkXzMwMFgyNTA="),t("I2Jhbm5lcmZsb2F0"),t("I2NhbXBhaWduLWJhbm5lcg=="),t("I0FkLUNvbnRlbnQ=")],adGuardAnnoyances:[".hs-sosyal","#cookieconsentdiv",'div[class^="app_gdpr"]',".as-oil",'[data-cypress="soft-push-notification-modal"]'],easyList:[".yb-floorad",t("LndpZGdldF9wb19hZHNfd2lkZ2V0"),t("LnRyYWZmaWNqdW5reS1hZA=="),".textad_headline",t("LnNwb25zb3JlZC10ZXh0LWxpbmtz")],privacyBadger:["#privacy-badger-popup",".privacy-badger-blocked",t("LnByaXZhY3ktYmFkZ2Vy")],ghostery:["#ghostery-popup",".ghostery-blocking",t("Lmdob3N0ZXJ5LWJsb2NrZWQ=")],brave:["#brave-ads-blocked",".brave-blocked",t("LmJyYXZlLWFkLWJsb2Nr")],facebookContainer:[".facebook-container-blocked",t("LmZiLWJsb2NrZWQ=")],cookieBlockers:[".cookie-notice-blocked","#cookie-banner-hidden",t("LmNvb2tpZS1ibG9ja2Vy")],trackingProtection:[".tracking-blocked","#tracking-protection-enabled",t("LnRyYWNrZXItYmxvY2tlZA==")]}}function o(t){const e=document.createElement("div");if(t.startsWith("#"))e.id=t.substring(1);else if(t.startsWith("."))e.className=t.substring(1);else if(t.includes("["))try{const o=t.match(/\[([^=]+)([*^$|~]?=)"([^"]+)"\]/);if(o&&o[1]&&o[3]){const[,t,r,n]=o;"*="===r?e.setAttribute(t,`test-${n}-test`):e.setAttribute(t,n)}}catch{e.className="test-element"}else e.className=t.replace(/[^a-zA-Z0-9-_]/g,"");return e}function r(t){const e=t.style;e.setProperty("visibility","hidden","important"),e.setProperty("display","block","important"),e.setProperty("position","absolute","important"),e.setProperty("left","-9999px","important"),e.setProperty("width","1px","important"),e.setProperty("height","1px","important"),e.setProperty("pointer-events","none","important"),e.setProperty("z-index","-1","important")}function n(t){return new Promise(e=>setTimeout(e,t))}async function i(t){var e,i;const a=document,c=a.createElement("div"),s=new Array(t.length),d={};r(c);const l=a.createDocumentFragment();for(let n=0;n<t.length;n++){const c=t[n];if(c)try{const t=o(c),d=a.createElement("div");"DIALOG"===t.tagName&&(null===(i=(e=t).show)||void 0===i||i.call(e)),r(d),d.appendChild(t),l.appendChild(d),s[n]=t}catch(t){s[n]=void 0}}c.appendChild(l);let b=0;for(;!a.body&&b<100;)await n(50),b++;if(!a.body)throw new Error("Document body not available for DOM blockers detection");a.body.appendChild(c);try{await n(50),await new Promise(e=>{requestAnimationFrame(()=>{for(let e=0;e<t.length;e++){const o=s[e],r=t[e];o&&r&&!o.offsetParent&&(d[r]=!0)}e()})})}finally{try{c.parentNode&&c.parentNode.removeChild(c)}catch(t){setTimeout(()=>{try{c.parentNode&&c.parentNode.removeChild(c)}catch{}},0)}}return d}async function a(t={}){const{debug:o=!1,timeout:r=5e3}=t;try{if(!c())return"BROWSER_INCOMPATIBLE";if(!document||!document.body)return"DOM_NOT_AVAILABLE";const t=e(),n=Object.keys(t),a=[].concat(...n.map(e=>t[e]||[])),s=new Promise((t,e)=>{setTimeout(()=>e(new Error("DOM blockers detection timeout")),r)}),d=await Promise.race([i(a),s]);return o&&(a.length,Object.keys(d).length),n.filter(e=>{const o=t[e];return!(!o||0===o.length)&&o.map(t=>d[t]).filter(Boolean).length>.6*o.length}).sort()}catch(t){if(o&&console.error("[RabbitTracker] DOM Blockers detection failed:",t),t instanceof Error){if(t.message.includes("timeout"))return"TIMEOUT";if("SecurityError"===t.name||t.message.includes("SecurityError"))return"SECURITY_ERROR"}return"NOT_SUPPORTED"}}function c(){return t().canRunDOMBlockers}async function s(t={}){const e=await a(t),o=Array.isArray(e)?e:[];return{activeBlockers:o,blockerCount:o.length,hasAdBlocker:o.some(t=>["adBlock","uBlockOrigin","adGuardBase","easyList"].includes(t)),hasPrivacyExtension:o.some(t=>["privacyBadger","ghostery","brave"].includes(t)),hasTrackingProtection:o.includes("trackingProtection")}}export{i as getBlockedSelectors,e as getBlockerFilters,a as getDomBlockers,s as getDomBlockersFingerprint,c as isDomBlockersDetectionAvailable};
|