sitepong 0.0.14 → 0.0.16
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/cdn/sitepong.min.js +8 -0
- package/dist/cdn/sitepong.min.js.map +1 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +209 -48
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +209 -48
- package/dist/index.mjs.map +1 -1
- package/dist/react/index.js +209 -48
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +209 -48
- package/dist/react/index.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
var SitePong=(function(exports){'use strict';var A="sitepong_anonymous_id";function G(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}var w=null;function T(){if(typeof window<"u"&&typeof localStorage<"u")try{let r=localStorage.getItem(A);return r||(r=G(),localStorage.setItem(A,r)),r}catch{return w||(w=G()),w}return w||(w=G()),w}function de(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(A);}catch{}w=null;}function fe(r){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.setItem(A,r);}catch{w=r;}else w=r;}function pe(r){let e=r.toLowerCase();return /ipad/.test(e)||/android/.test(e)&&!/mobile/.test(e)||/tablet/.test(e)?"tablet":/mobile/.test(e)||/iphone/.test(e)||/ipod/.test(e)||/android/.test(e)||/blackberry/.test(e)||/windows phone/.test(e)?"mobile":"desktop"}function he(r){let e=r.toLowerCase();return /edg/.test(e)?"edge":/opr|opera/.test(e)?"opera":/samsungbrowser/.test(e)?"samsung":/chrome|chromium|crios/.test(e)?"chrome":/safari/.test(e)&&!/chrome/.test(e)?"safari":/firefox|fxios/.test(e)?"firefox":/msie|trident/.test(e)?"ie":"other"}function ge(r){let e=r.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/mac os|macos|macintosh/.test(e)?"macos":/windows/.test(e)?"windows":/linux/.test(e)?"linux":"other"}function Q(){let r=typeof navigator<"u"?navigator.userAgent:"";return {anonymous_id:T(),device_type:r?pe(r):void 0,browser:r?he(r):void 0,os:r?ge(r):void 0,user_agent:r||void 0,timestamp:new Date}}function me(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e^r.charCodeAt(t);return e>>>0}function He(r){return Math.random()*100<r.percentage}function Be(r,e,t){let n=`${e.anonymous_id}:${t}`;return me(n)%100<r.percentage}function L(r){let[e,t]=r.split(":").map(Number);return e*60+t}function Ue(r,e){let t=e.timestamp||new Date,i=new Intl.DateTimeFormat("en-US",{timeZone:r.timezone,weekday:"short",hour:"2-digit",minute:"2-digit",hour12:false}).formatToParts(t),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].indexOf(i.find(u=>u.type==="weekday")?.value||""),o=parseInt(i.find(u=>u.type==="hour")?.value||"0",10),l=parseInt(i.find(u=>u.type==="minute")?.value||"0",10),c=o*60+l;if(r.days_of_week&&r.days_of_week.length>0&&!r.days_of_week.includes(s))return false;if(r.start_time&&r.end_time){let u=L(r.start_time),f=L(r.end_time);if(u>f){if(c<u&&c>=f)return false}else if(c<u||c>=f)return false}else if(r.start_time){let u=L(r.start_time);if(c<u)return false}else if(r.end_time){let u=L(r.end_time);if(c>=u)return false}return true}function Ve(r,e){return e.device_type?r.types.includes(e.device_type):false}function $e(r,e){return e.browser?r.browsers.includes(e.browser):false}function ze(r,e){return e.os?r.operating_systems.includes(e.os):false}function Ke(r,e,t,n){switch(r){case "percentage_rollout":return He(e);case "userbase_percentage":return Be(e,t,n);case "time_based":return Ue(e,t);case "device_type":return Ve(e,t);case "browser":return $e(e,t);case "os":return ze(e,t);default:return false}}function O(r,e){if(r.override==="force_on")return true;if(r.override==="force_off"||!r.enabled)return false;if(!r.rules||r.rules.length===0)return true;for(let t of r.rules)if(!Ke(t.rule_type,t.config,e,r.key))return false;return true}function ve(r,e){if(!O(r,e)||r.flag_type!=="multivariate"||!r.variants||r.variants.length===0)return null;let t=`${e.anonymous_id}:${r.key}:variant`,n=me(t),i=r.variants.reduce((l,c)=>l+c.weight,0),s=n%i,o=0;for(let l of r.variants)if(o+=l.weight,s<o)return l.key;return r.variants[0].key}function ye(r,e){return r.variant_payloads&&r.variant_payloads[e]!==void 0?r.variant_payloads[e]:r.variants?.find(n=>n.key===e)?.payload||null}var qe="https://api.sitepong.com",x=class{constructor(e){this.flags=new Map;this.evaluatedFlags=new Map;this.evaluatedVariants=new Map;this.context=null;this.initialized=false;this.initPromise=null;this.config={endpoint:qe,debug:false,...e};}async init(){if(!this.initialized){if(this.initPromise)return this.initPromise;this.initPromise=this.fetchAndEvaluateFlags();try{await this.initPromise,this.initialized=!0;}catch(e){this.log("Failed to initialize flags:",e),this.initialized=true;}finally{this.initPromise=null;}}}async fetchAndEvaluateFlags(){try{let e=await fetch(`${this.config.endpoint}/api/sdk/flags`,{method:"GET",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey}});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let t=await e.json();this.log("Fetched flags:",t.flags.length),this.context=Q(),this.log("Evaluation context:",this.context),this.flags.clear(),this.evaluatedFlags.clear(),this.evaluatedVariants.clear();for(let n of t.flags){this.flags.set(n.key,n);let i=O(n,this.context);if(this.evaluatedFlags.set(n.key,i),n.flag_type==="multivariate"&&n.variants){let s=ve(n,this.context);this.evaluatedVariants.set(n.key,s),this.log(`Flag "${n.key}": ${i}, variant: ${s}`);}else this.log(`Flag "${n.key}": ${i}`);}}catch(e){throw this.log("Error fetching flags:",e),e}}getFlag(e,t=false){if(!this.initialized)return this.log(`Flag "${e}" requested before init, returning default:`,t),t;let n=this.evaluatedFlags.get(e);return n===void 0?(this.log(`Flag "${e}" not found, returning default:`,t),t):n}getVariant(e,t=null){if(!this.initialized)return this.log(`Variant "${e}" requested before init, returning default:`,t),t;let n=this.evaluatedVariants.get(e);return n===void 0?(this.log(`Variant "${e}" not found, returning default:`,t),t):n}getVariantPayload(e,t=null){let n=this.getVariant(e);if(!n)return t;let i=this.flags.get(e);return i?ye(i,n)??t:t}getAllFlags(){let e={};for(let[t,n]of this.evaluatedFlags)e[t]=n;return e}hasFlag(e){return this.flags.has(e)}isInitialized(){return this.initialized}async waitForInit(){this.initialized||await this.init();}async refresh(){this.initialized=false,await this.init();}getContext(){return this.context}log(...e){this.config.debug&&console.log("[SitePong Flags]",...e);}};var j="sitepong_session_id",N="sitepong_session_ts";var k=null,E=null;function we(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}function Se(r){return Date.now()-r>18e5}function Y(){if(typeof window<"u"&&typeof sessionStorage<"u")try{let r=sessionStorage.getItem(j),e=sessionStorage.getItem(N);if(r&&e&&!Se(parseInt(e,10)))return sessionStorage.setItem(N,String(Date.now())),r;let t=we();return sessionStorage.setItem(j,t),sessionStorage.setItem(N,String(Date.now())),t}catch{return be()}return be()}function be(){return k&&E&&!Se(E)?(E=Date.now(),k):(k=we(),E=Date.now(),k)}function J(){if(typeof window<"u"&&typeof sessionStorage<"u")try{sessionStorage.removeItem(j),sessionStorage.removeItem(N);}catch{}k=null,E=null;}var Te=["[data-sp-no-capture]",".sp-no-capture"];var M=class{constructor(e,t){this.clickHandler=null;this.submitHandler=null;this.active=false;this.config={clicks:true,forms:true,pageviews:true,blockSelectors:Te,maxTextLength:255,debug:false,...e},this.callback=t;}start(){this.active||typeof window>"u"||(this.active=true,this.config.clicks&&this.setupClickCapture(),this.config.forms&&this.setupFormCapture(),this.log("Autocapture started"));}stop(){this.active&&(this.active=false,this.clickHandler&&(document.removeEventListener("click",this.clickHandler,true),this.clickHandler=null),this.submitHandler&&(document.removeEventListener("submit",this.submitHandler,true),this.submitHandler=null),this.log("Autocapture stopped"));}setupClickCapture(){this.clickHandler=e=>{let t=e.target;if(!t||!this.shouldCapture(t))return;let n=this.getElementProperties(t);n.$event_type="click",n.$x=e.clientX,n.$y=e.clientY,this.callback({type:"click",timestamp:new Date().toISOString(),properties:n});},document.addEventListener("click",this.clickHandler,true);}setupFormCapture(){this.submitHandler=e=>{let t=e.target;if(!t||!this.shouldCapture(t))return;let n={$event_type:"form_submit",$form_action:t.action||void 0,$form_method:t.method||"get",$form_name:t.name||t.id||void 0,$field_names:this.getFormFieldNames(t),$field_count:t.elements.length},i=this.getElementProperties(t);Object.assign(n,i),this.callback({type:"form_submit",timestamp:new Date().toISOString(),properties:n});},document.addEventListener("submit",this.submitHandler,true);}shouldCapture(e){let t=this.config.blockSelectors||Te;for(let n of t)if(e.matches(n)||e.closest(n))return false;return !(this.config.allowSelectors&&this.config.allowSelectors.length>0&&!this.config.allowSelectors.some(i=>e.matches(i)||e.closest(i)!==null)||e.offsetParent===null&&e.tagName!=="BODY")}getElementProperties(e){let t={};t.$tag_name=e.tagName.toLowerCase(),t.$el_id=e.id||void 0,e.classList.length>0&&(t.$el_classes=Array.from(e.classList).slice(0,5));let n=this.getElementText(e);n&&(t.$el_text=n),e instanceof HTMLAnchorElement&&(t.$href=e.href||void 0,t.$target=e.target||void 0),(e instanceof HTMLInputElement||e instanceof HTMLButtonElement)&&(t.$el_type=e.type||void 0,t.$el_name=e.name||void 0);let i=e.getAttribute("aria-label");i&&(t.$aria_label=this.truncate(i));let s=e.getAttribute("role");return s&&(t.$el_role=s),t.$selector=this.getSelector(e),t.$current_url=window.location.href,t.$pathname=window.location.pathname,t}getElementText(e){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return;let t="";if(e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement)t=e.innerText||e.textContent||"";else for(let n of Array.from(e.childNodes))n.nodeType===Node.TEXT_NODE&&(t+=n.textContent||"");return t=t.trim().replace(/\s+/g," "),t?this.truncate(t):void 0}getFormFieldNames(e){let t=[];for(let n of Array.from(e.elements)){let i=n;i.name&&i.type!=="password"&&i.type!=="hidden"&&t.push(i.name);}return t.slice(0,20)}getSelector(e){let t=[],n=e,i=0;for(;n&&n!==document.body&&i<5;){let s=n.tagName.toLowerCase();if(n.id){s=`#${n.id}`,t.unshift(s);break}n.classList.length>0&&(s+=`.${Array.from(n.classList).slice(0,2).join(".")}`);let o=n.parentElement;if(o){let l=Array.from(o.children).filter(c=>c.tagName===n.tagName);if(l.length>1){let c=l.indexOf(n)+1;s+=`:nth-of-type(${c})`;}}t.unshift(s),n=n.parentElement,i++;}return t.join(" > ")}truncate(e){let t=this.config.maxTextLength||255;return e.length>t?e.slice(0,t)+"...":e}log(...e){this.config.debug&&console.log("[SitePong Autocapture]",...e);}};var We="https://ingest.sitepong.com",Xe=20,Ge=1e4,Z=3,C=class{constructor(e){this.eventQueue=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.userId=null;this.groupId=null;this.userTraits=null;this.groupTraits=null;this.lastUrl=null;this.popstateHandler=null;this.autocaptureModule=null;this.config={endpoint:We,enabled:true,autocapturePageviews:false,maxBatchSize:Xe,flushInterval:Ge,debug:false,...e};}init(){this.config.enabled&&(this.startFlushTimer(),this.setupPageHideListener(),this.config.autocapturePageviews&&this.setupSPATracking(),this.setupAutocapture(),this.log("Analytics initialized"));}setupAutocapture(){let e=this.config.autocapture,t=this.config.autocaptureClicks,n=this.config.autocaptureForms,i=t||false,s=n||false,o,l;e===true?(i=true,s=true):e&&typeof e=="object"&&(i=e.clicks!==false,s=e.forms!==false,o=e.blockSelectors,l=e.allowSelectors,e.pageviews!==false&&!this.config.autocapturePageviews&&this.setupSPATracking()),!(!i&&!s)&&(this.autocaptureModule=new M({clicks:i,forms:s,pageviews:false,blockSelectors:o,allowSelectors:l,debug:this.config.debug},c=>{let u=c.type==="click"?"$autocapture_click":c.type==="form_submit"?"$autocapture_form_submit":"$autocapture";this.track(u,c.properties);}),this.autocaptureModule.start());}track(e,t){if(!this.config.enabled)return;let n=this.createEvent("track",{name:e,properties:t});this.enqueue(n),this.log("Track:",e,t);}trackPageView(e,t){if(!this.config.enabled)return;let n=e||(typeof window<"u"?window.location.href:void 0),i=this.createEvent("page",{properties:{url:n,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,...t}});this.enqueue(i),this.log("Page view:",n);}identify(e,t){if(!this.config.enabled)return;this.userId=e,t&&(this.userTraits={...this.userTraits,...t});let n=this.createEvent("identify",{traits:this.userTraits||void 0});this.enqueue(n),this.log("Identify:",e,t);}group(e,t){if(!this.config.enabled)return;this.groupId=e,t&&(this.groupTraits={...this.groupTraits,...t});let n=this.createEvent("group",{traits:this.groupTraits||void 0});this.enqueue(n),this.log("Group:",e,t);}reset(){this.userId=null,this.groupId=null,this.userTraits=null,this.groupTraits=null,J(),this.log("Analytics state reset");}async flush(){if(this.eventQueue.length===0)return;if(this.disabled){this.eventQueue=[];return}let e=[...this.eventQueue];this.eventQueue=[];let t=this.config.eventsEndpoint||`${this.config.endpoint}/api/events`;try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({events:e})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} events`);}catch(n){if(this.flushFailures++,this.flushFailures>=Z){this.disabled=true,console.warn(`[SitePong Analytics] Disabled after ${Z} consecutive failures. Check that ${t} is accessible and has proper CORS headers.`);return}this.eventQueue.unshift(...e),this.log(`Failed to flush events (attempt ${this.flushFailures}/${Z}):`,n);}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.popstateHandler&&typeof window<"u"&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.autocaptureModule&&(this.autocaptureModule.stop(),this.autocaptureModule=null),this.flushWithBeacon();}createEvent(e,t){return {type:e,name:t.name,properties:t.properties,userId:this.userId||void 0,anonymousId:T(),groupId:this.groupId||void 0,traits:t.traits,sessionId:Y(),timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0,referrer:typeof document<"u"?document.referrer:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}}enqueue(e){this.eventQueue.push(e),this.eventQueue.length>=this.config.maxBatchSize&&this.flush();}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval);}setupPageHideListener(){typeof window>"u"||window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();});}flushWithBeacon(){if(this.eventQueue.length===0||typeof navigator?.sendBeacon!="function")return;let e=[...this.eventQueue];this.eventQueue=[];let t=this.config.eventsEndpoint||`${this.config.endpoint}/api/events`,n=new Blob([JSON.stringify({events:e,apiKey:this.config.apiKey})],{type:"application/json"});navigator.sendBeacon(t,n),this.log(`Flushed ${e.length} events via beacon`);}setupSPATracking(){if(typeof window>"u")return;this.lastUrl=window.location.href,this.trackPageView(),this.popstateHandler=()=>{let n=window.location.href;n!==this.lastUrl&&(this.lastUrl=n,this.trackPageView(n));},window.addEventListener("popstate",this.popstateHandler);let e=history.pushState.bind(history),t=history.replaceState.bind(history);history.pushState=(...n)=>{e(...n),this.handleUrlChange();},history.replaceState=(...n)=>{t(...n),this.handleUrlChange();};}handleUrlChange(){if(typeof window>"u")return;let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,this.trackPageView(e));}log(...e){this.config.debug&&console.log("[SitePong Analytics]",...e);}};function ee(){let r={uaSpoofed:false,antiDetectBrowser:false,canvasNoise:false,canvasBlocked:false,webglSpoofed:false,webglBlocked:false,vmIndicators:[],platformMismatch:false,pluginAnomaly:false,featureAnomaly:false,geolocationSpoofed:false,mitmIndicators:[]},e=0,t=Qe(r);e+=t;let n=je(r);e+=n;let i=Ye(r);e+=i;let s=Je(r);e+=s;let o=Ze(r);e+=o;let l=et(r);return e+=l,e=Math.min(e,1),{browserTampered:r.uaSpoofed||r.antiDetectBrowser||r.platformMismatch,canvasTampered:r.canvasNoise||r.canvasBlocked,webglTampered:r.webglSpoofed||r.webglBlocked,vmDetected:r.vmIndicators.length>=2,geolocationSpoofed:r.geolocationSpoofed,mitmDetected:r.mitmIndicators.length>=1,confidence:e,signals:r}}function Qe(r){if(typeof navigator>"u"||typeof window>"u")return 0;let e=0,t=navigator.userAgent,n=navigator.platform||"",i=/Windows/.test(t),s=/Mac/.test(t),o=/Linux/.test(t)&&!/Android/.test(t),l=/Win/.test(n),c=/Mac/.test(n),u=/Linux/.test(n);(i&&!l||s&&!c||o&&!u)&&(r.platformMismatch=true,r.uaSpoofed=true,e+=.3);let f=/Chrome\/\d+/.test(t)&&!/Edge|OPR|Brave/.test(t);f&&!("chrome"in window||"CSS"in window&&"paintWorklet"in window.CSS)&&!("brave"in navigator)&&(r.uaSpoofed=true,e+=.2),/Firefox\/\d+/.test(t)&&!/Seamonkey/.test(t)&&("InstallTrigger"in window||CSS.supports("-moz-appearance","none")||(r.uaSpoofed=true,e+=.2));let p=navigator;if(p.userAgentData?.brands){let m=p.userAgentData.brands.map(S=>S.brand);(m.length===0||m.every(S=>S===""||S==="Not A;Brand"))&&(r.antiDetectBrowser=true,e+=.25);}/mobile|android|iphone|ipad/i.test(t)||(navigator.plugins?.length||0)===0&&f&&(r.pluginAnomaly=true,e+=.1);let d=navigator.hardwareConcurrency||0,h=navigator.deviceMemory||0;return d>0&&h>0&&d>=16&&h<=1&&(r.featureAnomaly=true,e+=.15),Math.min(e,.5)}function je(r){if(typeof document>"u")return 0;let e=0;try{let t=document.createElement("canvas");t.width=100,t.height=20;let n=t.getContext("2d");if(!n)return r.canvasBlocked=!0,.1;n.fillStyle="#ff0000",n.fillRect(0,0,100,20),n.fillStyle="#00ff00",n.font="12px Arial",n.fillText("SitePong",5,14);let i=t.toDataURL();n.clearRect(0,0,100,20),n.fillStyle="#ff0000",n.fillRect(0,0,100,20),n.fillStyle="#00ff00",n.font="12px Arial",n.fillText("SitePong",5,14);let s=t.toDataURL();i!==s&&(r.canvasNoise=!0,e+=.35);let l=n.getImageData(0,0,100,20).data,c=!0,u=!0,f=l[0];for(let p=0;p<l.length;p+=4)(l[p]!==0||l[p+1]!==0||l[p+2]!==0)&&(c=!1),l[p]!==f&&(u=!1);(c||u)&&(r.canvasBlocked=!0,e+=.2);let g=Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,"toDataURL");g&&g.value!==HTMLCanvasElement.prototype.toDataURL&&(r.canvasNoise=!0,e+=.3);}catch{r.canvasBlocked=true,e+=.1;}return Math.min(e,.4)}function Ye(r){if(typeof document>"u")return 0;let e=0;try{let t=document.createElement("canvas"),n=t.getContext("webgl")||t.getContext("experimental-webgl");if(!n||!(n instanceof WebGLRenderingContext))return r.webglBlocked=!0,.1;let i=n.getExtension("WEBGL_debug_renderer_info");if(!i)return r.webglBlocked=!0,.1;let s=n.getParameter(i.UNMASKED_VENDOR_WEBGL),o=n.getParameter(i.UNMASKED_RENDERER_WEBGL),l=["Brian Paul","Mesa","VMware"];["llvmpipe","softpipe","Mesa","SwiftShader"].some(h=>o.includes(h))&&!l.some(h=>s.includes(h))&&(r.webglSpoofed=!0,e+=.25);let u=navigator.userAgent,f=/mobile|android|iphone|ipad/i.test(u),g=/GeForce|Radeon|Intel.*HD|GTX|RTX|Vega/i.test(o);f&&g&&(r.webglSpoofed=!0,e+=.3);let p=Object.getOwnPropertyDescriptor(WebGLRenderingContext.prototype,"getParameter");p&&typeof p.value=="function"&&(p.value.toString().includes("[native code]")||(r.webglSpoofed=!0,e+=.35)),(n.getSupportedExtensions()||[]).length<5&&g&&(r.webglSpoofed=!0,e+=.1);}catch{r.webglBlocked=true,e+=.1;}return Math.min(e,.4)}function Je(r){if(typeof navigator>"u"||typeof window>"u")return 0;let e=[],t=navigator.userAgent;try{let o=document.createElement("canvas"),l=o.getContext("webgl")||o.getContext("experimental-webgl");if(l&&l instanceof WebGLRenderingContext){let c=l.getExtension("WEBGL_debug_renderer_info");if(c){let u=l.getParameter(c.UNMASKED_RENDERER_WEBGL).toLowerCase(),f=l.getParameter(c.UNMASKED_VENDOR_WEBGL).toLowerCase(),g=["vmware","virtualbox","hyper-v","parallels","qemu","llvmpipe","mesa"],p=["vmware","innotek","microsoft basic","parallels"];for(let d of g)u.includes(d)&&e.push(`webgl_renderer:${d}`);for(let d of p)f.includes(d)&&e.push(`webgl_vendor:${d}`);}}}catch{}if(typeof screen<"u"){let o=screen.width,l=screen.height;[[800,600],[1024,768],[1280,800]].some(([u,f])=>o===u&&l===f)&&screen.colorDepth===24&&navigator.hardwareConcurrency<=2&&e.push("vm_resolution");}let n=navigator.hardwareConcurrency||0,i=navigator.deviceMemory||0;if(n>0&&n<=2&&i>0&&i<=2&&(/mobile|android|iphone/i.test(t)||e.push("low_hw_specs")),typeof performance<"u"){let o=[];for(let c=0;c<10;c++)o.push(performance.now());new Set(o.map(c=>Math.floor(c*1e3))).size<=3&&o.length===10&&e.push("coarse_timing");}if(typeof navigator<"u"){let o=navigator.connection;o&&o.downlink&&o.downlink>=10&&o.rtt&&o.rtt<=5&&e.push("cloud_vm_network");}return r.vmIndicators=e,Math.min(e.length*.15,.5)}function Ze(r){if(typeof navigator>"u")return 0;let e=0;if("geolocation"in navigator){let t=Object.getOwnPropertyDescriptor(navigator,"geolocation");t&&t.configurable===false&&t.get&&(t.get.toString().includes("[native code]")||(r.geolocationSpoofed=true,e+=.3));try{let n=Object.getOwnPropertyDescriptor(Geolocation.prototype,"getCurrentPosition");n?.value&&(n.value.toString().includes("[native code]")||(r.geolocationSpoofed=!0,e+=.3));}catch{}}if(typeof window<"u")try{let t=Object.getPrototypeOf(navigator),n=Object.getOwnPropertyDescriptor(t,"geolocation");n&&n.get&&!n.get.toString().includes("[native code]")&&(r.geolocationSpoofed=!0,e+=.2);}catch{}return Math.min(e,.4)}function et(r){if(typeof window>"u"||typeof document>"u")return 0;let e=[];if(window.location?.protocol==="https:"){let n=document.querySelectorAll("script[src]");for(let i=0;i<n.length;i++){let s=n[i].getAttribute("src")||"";if(s.startsWith("http://")&&!s.includes("localhost")){e.push("mixed_content_script");break}}}let t=document.querySelectorAll("iframe");for(let n=0;n<t.length;n++){let i=t[n].getAttribute("src")||"";if(i&&!i.startsWith(window.location?.origin||"")&&!i.startsWith("about:")&&!i.startsWith("javascript:")){let s=window.getComputedStyle(t[n]);(s.display==="none"||s.visibility==="hidden"||parseInt(s.width)<=1||parseInt(s.height)<=1)&&e.push("hidden_iframe");}}if("serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(n=>{for(let i of n){let s=i.active?.scriptURL||"";s&&!s.startsWith(window.location?.origin||"")&&e.push("foreign_service_worker");}}).catch(()=>{}),typeof performance<"u"&&performance.getEntriesByType)try{let n=performance.getEntriesByType("navigation")[0];if(n){let i=n.connectEnd-n.connectStart,s=n.requestStart-n.secureConnectionStart;i>1e3&&s>500&&e.push("slow_tls_handshake");}}catch{}if(window.location?.protocol==="https:"&&typeof performance<"u")try{let n=performance.getEntriesByType("resource");for(let i of n.slice(0,20))if(i.transferSize===0&&i.encodedBodySize>0&&!i.name.includes("cache")){e.push("intercepted_resource");break}}catch{}return r.mitmIndicators=e,Math.min(e.length*.2,.5)}function xe(){return {userAgent:typeof navigator<"u"?navigator.userAgent:"",language:typeof navigator<"u"?navigator.language:"",languages:typeof navigator<"u"?Array.from(navigator.languages||[]):[],platform:typeof navigator<"u"&&navigator.platform||"",screenWidth:typeof screen<"u"?screen.width:0,screenHeight:typeof screen<"u"?screen.height:0,screenColorDepth:typeof screen<"u"?screen.colorDepth:0,devicePixelRatio:typeof window<"u"&&window.devicePixelRatio||1,timezoneOffset:new Date().getTimezoneOffset(),timezone:Intl?.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"",sessionStorage:tt(),localStorage:nt(),indexedDB:typeof indexedDB<"u",cookieEnabled:typeof navigator<"u"?navigator.cookieEnabled:false,hardwareConcurrency:typeof navigator<"u"&&navigator.hardwareConcurrency||0,maxTouchPoints:typeof navigator<"u"&&navigator.maxTouchPoints||0,deviceMemory:typeof navigator<"u"?navigator.deviceMemory:void 0}}function ke(){let r={};r.canvasFingerprint=rt();let e=it();return r.webglVendor=e.vendor,r.webglRenderer=e.renderer,r.audioFingerprint=st(),r}function te(r){let t={...xe()};r&&(t.extended=ke());let n=Ee();return t.smart=n,t.incognito=n.incognito,t.bot=n.bot,t}function Ee(){let r={};r.incognito=ot(),r.bot=at(),r.privacyBrowser=lt(),r.devToolsOpen=ct(),r.connectionType=ut(),r.doNotTrack=dt(),r.notificationsEnabled=ft();let e=pt();r.deviceFirstSeen=e.firstSeen,r.deviceVisitCount=e.visitCount;let t=ee();return r.browserTampered=t.browserTampered,r.canvasTampered=t.canvasTampered,r.webglTampered=t.webglTampered,r.vmDetected=t.vmDetected,r.vmIndicators=t.signals.vmIndicators,r}function tt(){try{let r="__sp_test__";return sessionStorage.setItem(r,"1"),sessionStorage.removeItem(r),!0}catch{return false}}function nt(){try{let r="__sp_test__";return localStorage.setItem(r,"1"),localStorage.removeItem(r),!0}catch{return false}}function rt(){if(!(typeof document>"u"))try{let r=document.createElement("canvas"),e=r.getContext("2d");return e?(r.width=200,r.height=50,e.textBaseline="top",e.font="14px Arial",e.fillStyle="#f60",e.fillRect(0,0,200,50),e.fillStyle="#069",e.fillText("SitePong fingerprint",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("SitePong fingerprint",4,17),Me(r.toDataURL())):void 0}catch{return}}function it(){if(typeof document>"u")return {};try{let r=document.createElement("canvas"),e=r.getContext("webgl")||r.getContext("experimental-webgl");if(!e||!(e instanceof WebGLRenderingContext))return {};let t=e.getExtension("WEBGL_debug_renderer_info");return t?{vendor:e.getParameter(t.UNMASKED_VENDOR_WEBGL),renderer:e.getParameter(t.UNMASKED_RENDERER_WEBGL)}:{}}catch{return {}}}function st(){if(!(typeof window>"u"||typeof OfflineAudioContext>"u"))try{let r=new OfflineAudioContext(1,44100,44100),e=r.createOscillator();e.type="triangle",e.frequency.setValueAtTime(1e4,r.currentTime);let t=r.createDynamicsCompressor();return t.threshold.setValueAtTime(-50,r.currentTime),t.knee.setValueAtTime(40,r.currentTime),t.ratio.setValueAtTime(12,r.currentTime),t.attack.setValueAtTime(0,r.currentTime),t.release.setValueAtTime(.25,r.currentTime),e.connect(t),t.connect(r.destination),e.start(0),Me(`audio:${r.sampleRate}:${r.length}`)}catch{return}}function ot(){if(typeof window>"u")return false;try{let r="__sp_incognito_test__";try{localStorage.setItem(r,new Array(100).join("x")),localStorage.removeItem(r);}catch{return !0}if(typeof indexedDB<"u")try{let t=indexedDB.open("__sp_test__");t.onerror=()=>{};}catch{return !0}if("webkitRequestFileSystem"in window){let t=!1;try{window.webkitRequestFileSystem(0,1,()=>{t=!1;},()=>{t=!0;});}catch{}if(t)return !0}let e=performance;if(e.memory){let t=e.memory.jsHeapSizeLimit||0;if(t>0&&t<1073741824)return !0}return !1}catch{return false}}function at(){if(typeof navigator>"u")return false;let r=navigator.userAgent.toLowerCase();return !!(["bot","crawler","spider","headless","phantom","puppeteer","selenium","webdriver","playwright"].some(t=>r.includes(t))||"webdriver"in navigator&&navigator.webdriver||navigator.plugins&&navigator.plugins.length===0&&!/mobile|android|iphone/i.test(r))}function lt(){if(typeof navigator>"u")return false;let r=navigator.userAgent.toLowerCase();return !!("brave"in navigator||r.includes("focus")&&r.includes("firefox")||r.includes("duckduckgo")||typeof window<"u"&&(screen.width===1e3&&screen.height===1e3||new Date().getTimezoneOffset()===0&&navigator.language!=="en"))}function ct(){if(typeof window>"u")return false;try{let r=window.outerWidth-window.innerWidth>160,e=window.outerHeight-window.innerHeight>160;if(r||e)return !0}catch{}return false}function ut(){if(typeof navigator>"u")return;let r=navigator.connection;if(r)return r.effectiveType||r.type||void 0}function dt(){if(typeof navigator>"u")return false;let r=navigator.doNotTrack;return r==="1"||r==="yes"}function ft(){return typeof Notification>"u"?false:Notification.permission==="granted"}function pt(){let r="sitepong_device_age",e={visitCount:1};if(typeof localStorage>"u")return e;try{let t=localStorage.getItem(r);if(t){let n=JSON.parse(t);e.firstSeen=n.firstSeen,e.visitCount=(n.visitCount||0)+1;}else e.firstSeen=new Date().toISOString();localStorage.setItem(r,JSON.stringify({firstSeen:e.firstSeen,visitCount:e.visitCount}));}catch{}return e}function Me(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);e=(e<<5)-e+n,e=e&e;}return Math.abs(e).toString(16)}var P=class{constructor(){this.mousePoints=[];this.keyDownTimes=new Map;this.keyIntervals=[];this.keyHoldTimes=[];this.lastKeyTime=0;this.scrollEvents=[];this.clickTimes=[];this.running=false;this.maxSamples=500;this.handleMouseMove=e=>{this.mousePoints.length>=this.maxSamples||this.mousePoints.push({x:e.clientX,y:e.clientY,t:Date.now()});};this.handleKeyDown=e=>{if(this.keyIntervals.length>=this.maxSamples)return;let t=Date.now();this.keyDownTimes.set(e.key,t),this.lastKeyTime>0&&this.keyIntervals.push(t-this.lastKeyTime),this.lastKeyTime=t;};this.handleKeyUp=e=>{let t=this.keyDownTimes.get(e.key);t&&(this.keyHoldTimes.push(Date.now()-t),this.keyDownTimes.delete(e.key));};this.handleScroll=()=>{this.scrollEvents.length>=this.maxSamples||this.scrollEvents.push({deltaY:window.scrollY,t:Date.now()});};this.handleClick=()=>{this.clickTimes.length>=this.maxSamples||this.clickTimes.push(Date.now());};}start(){this.running||typeof window>"u"||(this.running=true,window.addEventListener("mousemove",this.handleMouseMove,{passive:true}),window.addEventListener("keydown",this.handleKeyDown,{passive:true}),window.addEventListener("keyup",this.handleKeyUp,{passive:true}),window.addEventListener("scroll",this.handleScroll,{passive:true}),window.addEventListener("click",this.handleClick,{passive:true}));}stop(){!this.running||typeof window>"u"||(this.running=false,window.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),window.removeEventListener("scroll",this.handleScroll),window.removeEventListener("click",this.handleClick));}getMetrics(){let e=this.analyzeMouseMovement(),t=this.analyzeKeyboard(),n=this.analyzeScroll(),i=this.analyzeClicks(),s=this.calculateHumanScore(e,t,n,i);return {mouse:e,keyboard:t,scroll:n,clicks:i,score:s}}reset(){this.mousePoints=[],this.keyDownTimes.clear(),this.keyIntervals=[],this.keyHoldTimes=[],this.lastKeyTime=0,this.scrollEvents=[],this.clickTimes=[];}analyzeMouseMovement(){if(this.mousePoints.length<3)return {totalMovements:this.mousePoints.length,averageSpeed:0,maxSpeed:0,averageAcceleration:0,straightLineRatio:0,jitter:0,hasMovement:false};let e=[],t=[],n=0,i=0,s=0;for(let u=1;u<this.mousePoints.length;u++){let f=this.mousePoints[u-1],g=this.mousePoints[u],p=g.t-f.t||1,d=g.x-f.x,h=g.y-f.y,m=Math.sqrt(d*d+h*h),S=m/p;if(e.push(S),m<3&&m>0&&s++,u>=2){let y=this.mousePoints[u-2],Le=y.x+(g.x-y.x)*((f.t-y.t)/(g.t-y.t)),Oe=y.y+(g.y-y.y)*((f.t-y.t)/(g.t-y.t)),Ne=Math.sqrt((f.x-Le)**2+(f.y-Oe)**2);i++,Ne<2&&n++;}if(u>=2){let y=e[e.length-2]||0;t.push(Math.abs(S-y)/p);}}let o=e.reduce((u,f)=>u+f,0)/e.length,l=Math.max(...e),c=t.length>0?t.reduce((u,f)=>u+f,0)/t.length:0;return {totalMovements:this.mousePoints.length,averageSpeed:Math.round(o*1e3)/1e3,maxSpeed:Math.round(l*1e3)/1e3,averageAcceleration:Math.round(c*1e3)/1e3,straightLineRatio:i>0?n/i:0,jitter:this.mousePoints.length>0?s/this.mousePoints.length:0,hasMovement:true}}analyzeKeyboard(){if(this.keyIntervals.length<2)return {totalKeystrokes:this.keyIntervals.length,averageInterval:0,intervalVariance:0,holdTimeAverage:0,holdTimeVariance:0,hasKeystrokes:false};let e=this.keyIntervals.reduce((s,o)=>s+o,0)/this.keyIntervals.length,t=this.variance(this.keyIntervals),n=this.keyHoldTimes.length>0?this.keyHoldTimes.reduce((s,o)=>s+o,0)/this.keyHoldTimes.length:0,i=this.keyHoldTimes.length>0?this.variance(this.keyHoldTimes):0;return {totalKeystrokes:this.keyIntervals.length+1,averageInterval:Math.round(e),intervalVariance:Math.round(t),holdTimeAverage:Math.round(n),holdTimeVariance:Math.round(i),hasKeystrokes:true}}analyzeScroll(){if(this.scrollEvents.length<2)return {totalScrolls:this.scrollEvents.length,averageSpeed:0,smoothness:0,hasScroll:false};let e=[];for(let o=1;o<this.scrollEvents.length;o++){let l=this.scrollEvents[o].t-this.scrollEvents[o-1].t||1,c=Math.abs(this.scrollEvents[o].deltaY-this.scrollEvents[o-1].deltaY);e.push(c/l);}let n=e.reduce((o,l)=>o+l,0)/e.length,i=this.variance(e),s=n>0?Math.min(1,n/(i+n)):0;return {totalScrolls:this.scrollEvents.length,averageSpeed:Math.round(n*100)/100,smoothness:Math.round(s*100)/100,hasScroll:true}}analyzeClicks(){if(this.clickTimes.length<2)return {totalClicks:this.clickTimes.length,averageInterval:0,intervalVariance:0,doubleClickCount:0,hasClicks:this.clickTimes.length>0};let e=[],t=0;for(let s=1;s<this.clickTimes.length;s++){let o=this.clickTimes[s]-this.clickTimes[s-1];e.push(o),o<500&&t++;}let n=e.reduce((s,o)=>s+o,0)/e.length,i=this.variance(e);return {totalClicks:this.clickTimes.length,averageInterval:Math.round(n),intervalVariance:Math.round(i),doubleClickCount:t,hasClicks:true}}calculateHumanScore(e,t,n,i){let s=.5,o=0;if(e.hasMovement){o++;let l=.5;e.jitter>.05&&(l+=.15),e.straightLineRatio<.5?l+=.15:e.straightLineRatio>.9&&(l-=.2),e.averageSpeed>0&&e.maxSpeed/e.averageSpeed>3&&(l+=.1),e.averageAcceleration>0&&(l+=.1),s+=Math.max(0,Math.min(1,l))-.5;}if(t.hasKeystrokes){o++;let l=.5;t.intervalVariance>1e3?l+=.2:t.intervalVariance<100&&(l-=.2),(t.averageInterval>0?Math.sqrt(t.intervalVariance)/t.averageInterval:0)>.3&&(l+=.15),t.holdTimeVariance>500&&(l+=.1),s+=Math.max(0,Math.min(1,l))-.5;}if(n.hasScroll){o++;let l=.5;n.smoothness>.3&&n.smoothness<.9&&(l+=.2),s+=Math.max(0,Math.min(1,l))-.5;}if(i.hasClicks){o++;let l=.5;i.intervalVariance>5e4?l+=.15:i.intervalVariance<100&&(l-=.2),s+=Math.max(0,Math.min(1,l))-.5;}return o===0?.3:Math.max(0,Math.min(1,s))}variance(e){if(e.length<2)return 0;let t=e.reduce((n,i)=>n+i,0)/e.length;return e.reduce((n,i)=>n+(i-t)**2,0)/(e.length-1)}};async function ne(){let r={webrtcLeak:null,timezoneIPMismatch:false,dnsLeak:null,connectionType:null,multipleIPs:false,torBrowser:false,knownVPNExtension:false},e=0,t=false,n=false,i=false;r.torBrowser=ht(),r.torBrowser&&(i=true,e+=.9);try{r.webrtcLeak=await gt(),r.webrtcLeak&&(t=!0,e+=.3);}catch{r.webrtcLeak=null;}r.connectionType=mt(),(r.connectionType==="unknown"||r.connectionType===null)&&(e+=.05),r.knownVPNExtension=vt(),r.knownVPNExtension&&(t=true,e+=.4);let s=Intl.DateTimeFormat().resolvedOptions().timeZone,o=navigator.language;if(s&&o){let l=yt(s),c=o.split("-")[1]?.toUpperCase();l&&c&&l!==c&&(r.timezoneIPMismatch=true,e+=.1);}return e=Math.min(e,1),e<.3&&(t=false,n=false),{vpnDetected:t,proxyDetected:n,torDetected:i,confidence:e,signals:r}}function ht(){if(typeof window>"u")return false;let r=[];r.push(window.screen.width===1e3&&window.screen.height===1e3),r.push(!window.MediaDevices),r.push(navigator.plugins.length===0),r.push(new Date().getTimezoneOffset()===0);let e=navigator.userAgent;return r.push(e.includes("Firefox")&&!e.includes("Chrome")),r.filter(Boolean).length>=3}async function gt(){return typeof window>"u"||!window.RTCPeerConnection?false:new Promise(r=>{let e=setTimeout(()=>r(false),3e3),t=new Set;try{let n=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]});n.createDataChannel(""),n.onicecandidate=i=>{if(!i.candidate){clearTimeout(e),n.close(),r(t.size>1);return}let o=i.candidate.candidate.match(/(\d{1,3}\.){3}\d{1,3}/);o&&t.add(o[0]);},n.createOffer().then(i=>n.setLocalDescription(i)).catch(()=>{clearTimeout(e),r(!1);});}catch{clearTimeout(e),r(false);}})}function mt(){if(typeof navigator>"u")return null;let r=navigator;return r.connection&&(r.connection.type||r.connection.effectiveType)||null}function vt(){if(typeof document>"u"||!document.body)return false;let e=["[data-windscribe]","[data-nord]",".surfshark-extension","#vpn-indicator","[data-expressvpn]"];for(let t of e)try{if(document.querySelector(t))return !0}catch{}return false}function yt(r){return {"America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","Europe/London":"GB","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Asia/Tokyo":"JP","Asia/Shanghai":"CN","Asia/Kolkata":"IN","Asia/Seoul":"KR","Australia/Sydney":"AU","America/Toronto":"CA","America/Sao_Paulo":"BR","America/Mexico_City":"MX"}[r]||null}var bt="https://ingest.sitepong.com",re="sitepong_visitor",Ce=1440*60*1e3,I=class{constructor(e){this.cachedVisitor=null;this.pendingRequest=null;this.config={endpoint:bt,enabled:true,debug:false,...e},this.behaviorAnalyzer=new P,this.config.enabled&&typeof window<"u"&&this.behaviorAnalyzer.start(),this.loadFromStorage();}async getVisitorId(){if(!this.config.enabled)throw new Error("Fingerprint is not enabled");if(this.cachedVisitor&&!this.isCacheExpired())return this.log("Returning cached visitor ID:",this.cachedVisitor.result.visitorId),this.cachedVisitor.result;if(this.pendingRequest)return this.pendingRequest;this.pendingRequest=this.fetchVisitorId();try{return await this.pendingRequest}finally{this.pendingRequest=null;}}async getDeviceSignals(){return te(this.config.extendedSignals??false)}async getFraudCheck(){let[e,t,n]=await Promise.all([this.getVisitorId(),this.getDeviceSignals(),ne().catch(()=>null)]),i=this.behaviorAnalyzer.getMetrics();t.behavior={score:i.score,mouseMovements:i.mouse.totalMovements,keystrokes:i.keyboard.totalKeystrokes,scrolls:i.scroll.totalScrolls,clicks:i.clicks.totalClicks,isHuman:i.score>.6};let s=n?.vpnDetected||n?.torDetected||false;return {visitorId:e.visitorId,riskScore:this.calculateRiskScore(t,s),signals:t,flags:{incognito:t.smart?.incognito||t.incognito,bot:t.smart?.bot||t.bot||!t.behavior.isHuman,vpn:s||t.smart?.timezoneMismatch,tampered:t.smart?.privacyBrowser}}}stopBehaviorTracking(){this.behaviorAnalyzer.stop();}async fetchVisitorId(){let e=await this.getDeviceSignals(),t=this.config.visitorEndpoint||`${this.config.endpoint}/api/visitors`;try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({signals:e})});if(!n.ok)throw new Error(`HTTP ${n.status}`);let i=await n.json();return this.cachedVisitor={result:i,signals:e,cachedAt:Date.now()},this.saveToStorage(),this.log("Visitor ID fetched:",i.visitorId),i}catch(n){throw this.log("Failed to fetch visitor ID:",n),n}}calculateRiskScore(e,t=false){let n=0,i=e.smart;return (i?.bot||e.bot)&&(n+=.8),e.behavior&&(e.behavior.score<.3?n+=.4:e.behavior.score<.5&&(n+=.2)),t&&(n+=.25),(i?.incognito||e.incognito)&&(n+=.2),i?.devToolsOpen&&(n+=.1),i?.privacyBrowser&&(n+=.1),e.hardwareConcurrency===0&&(n+=.1),e.maxTouchPoints===0&&/mobile|android|iphone/i.test(e.userAgent)&&(n+=.15),e.cookieEnabled||(n+=.1),i?.doNotTrack&&(n+=.05),i?.deviceVisitCount===1&&(n+=.05),Math.round(Math.min(n,1)*100)/100}isCacheExpired(){return this.cachedVisitor?Date.now()-this.cachedVisitor.cachedAt>Ce:true}loadFromStorage(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(re);if(!e)return;let t=JSON.parse(e);this.isCacheExpiredAt(t.cachedAt)?localStorage.removeItem(re):(this.cachedVisitor=t,this.log("Loaded cached visitor from storage"));}catch{}}saveToStorage(){if(!(typeof window>"u"||typeof localStorage>"u")&&this.cachedVisitor)try{localStorage.setItem(re,JSON.stringify(this.cachedVisitor));}catch{}}isCacheExpiredAt(e){return Date.now()-e>Ce}log(...e){this.config.debug&&console.log("[SitePong Fingerprint]",...e);}};var Re=0,Pe=new WeakMap;function wt(){Re=0;}function v(r){let e=Pe.get(r);return e===void 0&&(e=++Re,Pe.set(r,e)),e}var St=new Set(["script","noscript"]),Tt=new Set(["src","href","action","poster"]);function De(r,e){if(!r||r.startsWith("data:")||r.startsWith("blob:")||r.startsWith("#"))return r;try{return new URL(r,e).href}catch{return r}}function ie(r,e){return r.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(t,n,i)=>{let s=i.trim();if(s.startsWith("data:")||s.startsWith("blob:")||s.startsWith("http://")||s.startsWith("https://")||s.startsWith("//"))return `url(${n}${s}${n})`;try{let o=new URL(s,e).href;return `url(${n}${o}${n})`}catch{return `url(${n}${s}${n})`}})}function Ie(r){try{let e=r.cssRules,t="";for(let n=0;n<e.length;n++)t+=e[n].cssText+`
|
|
2
|
+
`;return t}catch{return null}}function H(r){let e=r.tagName.toLowerCase(),t=location.href;if(e==="style"){let n=r;if(n.sheet){let s=Ie(n.sheet);if(s!==null)return ie(s,t)}let i=r.textContent||"";return i?ie(i,t):null}if(e==="link"){let n=r;if(n.rel!=="stylesheet")return null;let i=n.href||t;if(n.sheet){let s=Ie(n.sheet);if(s!==null)return ie(s,i)}return null}return null}function xt(r,e){return r.split(",").map(t=>{let n=t.trim().split(/\s+/);return n[0]&&(n[0]=De(n[0],e)),n.join(" ")}).join(", ")}function B(r,e,t=false){let n=v(r);if(r.nodeType===Node.TEXT_NODE){let i=r.parentElement,s=r.textContent||"";return i&&e.maskSelector&&i.matches(e.maskSelector)&&(s=s.replace(/\S/g,"*")),{id:n,type:"text",textContent:s}}if(r.nodeType===Node.COMMENT_NODE)return {id:n,type:"comment",textContent:""};if(r.nodeType===Node.ELEMENT_NODE){let i=r,s=i;if(e.blockSelector&&i.matches(e.blockSelector))return {id:n,type:"element",tagName:"div",attributes:{"data-blocked":"true",style:`width:${s.offsetWidth}px;height:${s.offsetHeight}px;background:#f0f0f0;`}};let o=i.tagName.toLowerCase();if(St.has(o))return null;let l=t||o==="svg"||i instanceof SVGElement,c={},u=location.href;for(let p=0;p<i.attributes.length;p++){let d=i.attributes[p],h=d.name,m=d.value;h.startsWith("on")||m&&m.toLowerCase().startsWith("javascript:")||(Tt.has(h)&&(m=De(m,u)),h==="srcset"&&(m=xt(m,u)),c[h]=m);}if(o==="style"||o==="link"&&i.getAttribute("rel")==="stylesheet"){let p=H(i);p&&(c._cssText=p);}if(o==="input"){let p=i,d=(p.type||"").toLowerCase();if(d==="checkbox"||d==="radio")c._checked=String(p.checked);else {let h=e.maskInputs?"***":p.value;h&&(c._value=h);}}else if(o==="textarea"){let p=i,d=e.maskInputs?"***":p.value;d&&(c._value=d);}else if(o==="select"){let p=i;c._selectedIndex=String(p.selectedIndex);}if(o==="canvas")try{let d=i.toDataURL("image/webp",.4);d&&d!=="data:,"&&(c._canvasDataUrl=d);}catch{}e.maskSelector&&i.matches(e.maskSelector);let f=[];for(let p of Array.from(i.childNodes)){let d=B(p,e,l);d&&f.push(d);}let g={id:n,type:"element",tagName:o,attributes:Object.keys(c).length>0?c:void 0,children:f.length>0?f:void 0};return l&&(g.isSVG=true),g}return null}function se(r){if(typeof document>"u")return null;wt();let e=B(document.documentElement,r);return e?{_version:2,doctype:document.doctype?`<!DOCTYPE ${document.doctype.name}>`:void 0,html:e,width:window.innerWidth,height:window.innerHeight}:null}var U=["authorization","cookie","set-cookie","x-api-key","x-auth-token"],R=class{constructor(e,t){this.originalFetch=null;this.originalXhrOpen=null;this.originalXhrSend=null;this.active=false;this.callback=e,this.captureHeaders=t?.captureHeaders??false,this.urlFilter=t?.urlFilter;}start(){this.active||typeof window>"u"||(this.active=true,this.interceptFetch(),this.interceptXHR());}stop(){this.active&&(this.active=false,this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXhrOpen&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,this.originalXhrOpen=null),this.originalXhrSend&&(XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrSend=null));}interceptFetch(){if(typeof window.fetch!="function")return;this.originalFetch=window.fetch;let e=this;window.fetch=async function(t,n){let i=typeof t=="string"?t:t instanceof URL?t.toString():t.url;if(e.urlFilter&&!e.urlFilter(i))return e.originalFetch.call(window,t,n);let s=Date.now(),o=n?.method||(t instanceof Request?t.method:"GET"),l;n?.body&&(typeof n.body=="string"?l=n.body.length:n.body instanceof Blob&&(l=n.body.size));try{let c=await e.originalFetch.call(window,t,n),u=Date.now()-s,f={method:o.toUpperCase(),url:e.truncateUrl(i),status:c.status,statusText:c.statusText,duration:u,requestSize:l,initiator:"fetch"};return e.captureHeaders&&(f.requestHeaders=e.safeHeaders(n?.headers),f.responseHeaders=e.headersToObject(c.headers)),e.emit(f),c}catch(c){let u=Date.now()-s;throw e.emit({method:o.toUpperCase(),url:e.truncateUrl(i),duration:u,requestSize:l,error:c instanceof Error?c.message:"Network error",initiator:"fetch"}),c}};}interceptXHR(){if(typeof XMLHttpRequest>"u")return;this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send;let e=this;XMLHttpRequest.prototype.open=function(t,n,...i){return this._spMethod=t,this._spUrl=typeof n=="string"?n:n.toString(),e.originalXhrOpen.apply(this,[t,n,...i])},XMLHttpRequest.prototype.send=function(t){let n=this,i=n._spUrl;if(e.urlFilter&&!e.urlFilter(i))return e.originalXhrSend.call(this,t);let s=Date.now(),o;typeof t=="string"&&(o=t.length);let l=()=>{let c=Date.now()-s,u;try{n.responseType===""||n.responseType==="text"?u=n.responseText?.length:n.responseType==="json"&&n.response!=null?u=JSON.stringify(n.response).length:n.responseType==="arraybuffer"&&n.response?u=n.response.byteLength:n.responseType==="blob"&&n.response&&(u=n.response.size);}catch{}let f={method:(n._spMethod||"GET").toUpperCase(),url:e.truncateUrl(i),status:n.status,statusText:n.statusText,duration:c,requestSize:o,responseSize:u,initiator:"xhr"};n.status===0&&(f.error="Network error"),e.emit(f),n.removeEventListener("loadend",l);};return n.addEventListener("loadend",l),e.originalXhrSend.call(this,t)};}emit(e){this.active&&this.callback({type:"network",timestamp:Date.now(),data:e});}truncateUrl(e){try{let t=new URL(e,window.location.origin),n=t.pathname+t.search;return n.length>500?n.slice(0,500)+"...":t.origin+n}catch{return e.length>500?e.slice(0,500)+"...":e}}safeHeaders(e){if(!e)return;let t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i]=U.includes(i.toLowerCase())?"[REDACTED]":n;});else if(Array.isArray(e))for(let[n,i]of e)t[n]=U.includes(n.toLowerCase())?"[REDACTED]":i;else for(let[n,i]of Object.entries(e))t[n]=U.includes(n.toLowerCase())?"[REDACTED]":i;return t}headersToObject(e){let t={};return e.forEach((n,i)=>{t[i]=U.includes(i.toLowerCase())?"[REDACTED]":n;}),t}};var D=class{constructor(e,t){this.originals={};this.active=false;this.callback=e,this.levels=t?.levels||["log","info","warn","error","debug"];}start(){if(!(this.active||typeof console>"u")){this.active=true;for(let e of this.levels)this.originals[e]=console[e].bind(console),console[e]=(...t)=>{this.originals[e](...t),this.record(e,t);};}}stop(){if(this.active){this.active=false;for(let e of this.levels)this.originals[e]&&(console[e]=this.originals[e]);this.originals={};}}record(e,t){if(!this.active||t.length>0&&typeof t[0]=="string"&&t[0].startsWith("[SitePong"))return;let n=t.slice(0,10).map(s=>this.serialize(s)),i={level:e,args:n};if(e==="error"){let s=this.getStackTrace();s&&(i.trace=s.slice(0,2e3));}this.callback({type:"console",timestamp:Date.now(),data:i});}serialize(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Error)return `Error: ${e.message}${e.stack?`
|
|
3
|
+
`+e.stack:""}`.slice(0,1e3);if(typeof e=="string")return e.slice(0,1e3);if(typeof e=="number"||typeof e=="boolean")return String(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof HTMLElement)return `<${e.tagName.toLowerCase()}${e.id?"#"+e.id:""}${e.className?"."+e.className.split(" ").join("."):""}>`;try{let t=JSON.stringify(e,this.getReplacer(),0);return t?t.slice(0,1e3):String(e)}catch{return String(e).slice(0,1e3)}}getReplacer(){let e=new WeakSet;return (t,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return "[Circular]";e.add(n);}return typeof n=="function"?"[Function]":n instanceof RegExp?n.toString():n}}getStackTrace(){try{let e=new Error;return e.stack&&e.stack.split(`
|
|
4
|
+
`).slice(4).join(`
|
|
5
|
+
`)||void 0}catch{return}}};var kt="https://ingest.sitepong.com",Et=5e3,Mt=100,Ct=3600*1e3,oe=3,F=class{constructor(e){this.recording=false;this.sessionId=null;this.events=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.sessionStartTime=0;this.observer=null;this.mouseMoveBuffer=[];this.mouseMoveFlushTimer=null;this.cleanupFns=[];this.networkRecorder=null;this.consoleRecorder=null;this.lastSnapshotTime=0;this.snapshotCooldown=500;this.userContext=null;this.mutationBuffer=null;this.mutationFlushTimer=null;this.lastScrollTime=0;this.config={endpoint:kt,enabled:true,maskInputs:true,maxSessionDuration:Ct,flushInterval:Et,maxBatchSize:Mt,sampleRate:1,debug:false,...e};}start(){if(typeof window>"u")return false;if(this.recording)return true;if(!this.config.enabled)return false;if(Math.random()>this.config.sampleRate)return this.log("Session not sampled"),false;this.sessionId=this.getOrCreateSessionId(),this.sessionStartTime=this.getOrCreateStartTime(),this.recording=true,this.events=[];let e=se({maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});return e&&this.addEvent("snapshot",e),this.setupMutationObserver(),this.setupEventListeners(),this.setupNetworkRecording(),this.setupConsoleRecording(),this.startFlushTimer(),this.log("Recording started:",this.sessionId),true}stop(){if(this.recording){this.recording=false,this.flush(),this.observer&&(this.observer.disconnect(),this.observer=null),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.mouseMoveFlushTimer&&(clearTimeout(this.mouseMoveFlushTimer),this.mouseMoveFlushTimer=null),this.mutationFlushTimer&&this.flushMutationBuffer(),this.networkRecorder&&(this.networkRecorder.stop(),this.networkRecorder=null),this.consoleRecorder&&(this.consoleRecorder.stop(),this.consoleRecorder=null);for(let e of this.cleanupFns)e();this.cleanupFns=[],this.log("Recording stopped:",this.sessionId),this.sessionId=null;}}isRecording(){return this.recording}getSessionId(){return this.sessionId}setUser(e){this.userContext=e;}addEvent(e,t){if(this.recording){if(Date.now()-this.sessionStartTime>this.config.maxSessionDuration){this.stop();return}this.events.push({type:e,timestamp:Date.now()-this.sessionStartTime,data:t}),this.events.length>=this.config.maxBatchSize&&this.flush();}}flushMutationBuffer(){this.mutationBuffer&&(this.mutationBuffer.adds.length||this.mutationBuffer.removes.length||this.mutationBuffer.attributes.length||this.mutationBuffer.texts.length)&&this.addEvent("mutation",this.mutationBuffer),this.mutationBuffer=null,this.mutationFlushTimer=null;}setupMutationObserver(){typeof MutationObserver>"u"||(this.observer=new MutationObserver(e=>{this.mutationBuffer||(this.mutationBuffer={adds:[],removes:[],attributes:[],texts:[]});for(let t of e)switch(t.type){case "childList":{for(let n of Array.from(t.addedNodes)){let i=B(n,{maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});i&&this.mutationBuffer.adds.push({parentId:v(t.target),nextId:t.nextSibling?v(t.nextSibling):null,node:i});}for(let n of Array.from(t.removedNodes))this.mutationBuffer.removes.push({parentId:v(t.target),id:v(n)});break}case "attributes":{let n=t.target,i=t.attributeName||"",s=n.getAttribute(i),o={[i]:s},l=n.tagName?.toLowerCase();if(l==="style"||l==="link"&&n.getAttribute("rel")==="stylesheet"){let c=H(n);c&&(o._cssText=c);}this.mutationBuffer.attributes.push({id:v(t.target),attributes:o});break}case "characterData":{let n=t.target.textContent||"",i=t.target.parentElement;if(i&&this.config.maskSelector&&i.matches(this.config.maskSelector)&&(n=n.replace(/\S/g,"*")),this.mutationBuffer.texts.push({id:v(t.target),value:n}),i&&i.tagName?.toLowerCase()==="style"){let s=H(i);s&&this.mutationBuffer.attributes.push({id:v(i),attributes:{_cssText:s}});}break}}this.mutationFlushTimer||(this.mutationFlushTimer=setTimeout(()=>this.flushMutationBuffer(),1e3));}),this.observer.observe(document.documentElement,{childList:true,subtree:true,attributes:true,characterData:true,attributeOldValue:false}));}setupEventListeners(){let e=d=>{this.mouseMoveBuffer.push({x:d.clientX,y:d.clientY,t:Date.now()-this.sessionStartTime}),this.mouseMoveFlushTimer||(this.mouseMoveFlushTimer=setTimeout(()=>{if(this.mouseMoveBuffer.length>0){let h={positions:[...this.mouseMoveBuffer]};this.addEvent("mouse_move",h),this.mouseMoveBuffer=[];}this.mouseMoveFlushTimer=null;},1e3));},t=d=>{let h=d.target;this.addEvent("mouse_click",{x:d.clientX,y:d.clientY,targetId:v(h),button:d.button}),this.takeInteractionSnapshot();},n=d=>{let h=d.target;this.addEvent("mouse_click",{x:d.clientX,y:d.clientY,targetId:v(h),button:2}),this.takeInteractionSnapshot();},i=()=>{this.addEvent("mouse_leave",{});},s=d=>{let h=d.touches[0];if(!h)return;let m=d.target;this.addEvent("touch",{x:h.clientX,y:h.clientY,targetId:v(m)}),this.takeInteractionSnapshot();},o=null,l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{let d={id:0,x:window.scrollX,y:window.scrollY};this.addEvent("scroll",d),this.takeInteractionSnapshot();},1e3);},c=d=>{let h=d.target;if(!h)return;let m={id:v(h),value:this.config.maskInputs?"***":h.value};"checked"in h&&(m.isChecked=h.checked),this.addEvent("input",m);},u=()=>{this.addEvent("resize",{width:window.innerWidth,height:window.innerHeight});},f=d=>{d.target&&d.target!==document&&this.addEvent("focus",{id:v(d.target)});},g=d=>{d.target&&d.target!==document&&this.addEvent("blur",{id:v(d.target)});},p=()=>{document.visibilityState==="hidden"&&this.flush();};document.addEventListener("mousemove",e,{passive:true}),document.addEventListener("click",t,{passive:true}),document.addEventListener("contextmenu",n,{passive:true}),document.documentElement.addEventListener("mouseleave",i,{passive:true}),document.addEventListener("touchstart",s,{passive:true}),window.addEventListener("scroll",l,{passive:true}),document.addEventListener("input",c,{passive:true}),window.addEventListener("resize",u,{passive:true}),document.addEventListener("focus",f,{passive:true,capture:true}),document.addEventListener("blur",g,{passive:true,capture:true}),document.addEventListener("visibilitychange",p),this.cleanupFns.push(()=>document.removeEventListener("mousemove",e),()=>document.removeEventListener("click",t),()=>document.removeEventListener("contextmenu",n),()=>document.documentElement.removeEventListener("mouseleave",i),()=>document.removeEventListener("touchstart",s),()=>window.removeEventListener("scroll",l),()=>document.removeEventListener("input",c),()=>window.removeEventListener("resize",u),()=>document.removeEventListener("focus",f,{capture:true}),()=>document.removeEventListener("blur",g,{capture:true}),()=>document.removeEventListener("visibilitychange",p));}setupNetworkRecording(){if(!this.config.recordNetwork)return;let e=this.config.replayEndpoint||this.config.endpoint;this.networkRecorder=new R(t=>{this.addEvent("network",t.data);},{captureHeaders:this.config.captureNetworkHeaders,urlFilter:t=>!t.startsWith(e)}),this.networkRecorder.start();}setupConsoleRecording(){this.config.recordConsole&&(this.consoleRecorder=new D(e=>{this.addEvent("console",e.data);},{levels:this.config.consoleLevels}),this.consoleRecorder.start());}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval);}async flush(){if(this.events.length===0||!this.sessionId)return;if(this.disabled){this.events=[];return}let e=[...this.events];this.events=[];let t=this.config.replayEndpoint||`${this.config.endpoint}/api/replays`;try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({sessionId:this.sessionId,events:e,startedAt:new Date(this.sessionStartTime).toISOString(),pageUrl:typeof location<"u"?location.href:void 0,pageTitle:typeof document<"u"?document.title:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,userId:this.userContext?.id})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} replay events`);}catch(n){if(this.flushFailures++,this.flushFailures>=oe){this.disabled=true,console.warn(`[SitePong Replay] Disabled after ${oe} consecutive failures. Check that ${t} is accessible and has proper CORS headers.`);return}this.events.unshift(...e),this.log(`Failed to flush replay events (attempt ${this.flushFailures}/${oe}):`,n);}}takeInteractionSnapshot(){let e=Date.now();if(e-this.lastSnapshotTime<this.snapshotCooldown)return;this.lastSnapshotTime=e;let t=se({maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});t&&this.addEvent("snapshot",t);}getOrCreateSessionId(){let e="__sp_replay_session";try{let n=sessionStorage.getItem(e);if(n)return n}catch{}let t=`rep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`;try{sessionStorage.setItem(e,t);}catch{}return t}getOrCreateStartTime(){let e="__sp_replay_start";try{let n=sessionStorage.getItem(e);if(n)return parseInt(n,10)}catch{}let t=Date.now();try{sessionStorage.setItem(e,String(t));}catch{}return t}log(...e){this.config.debug&&console.log("[SitePong Replay]",...e);}};var Pt="https://ingest.sitepong.com";var _=class{constructor(e){this.metrics=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.vitals={};this.activeTransactions=new Map;this.config={endpoint:Pt,enabled:true,webVitals:true,navigationTiming:true,resourceTiming:false,flushInterval:1e4,sampleRate:1,debug:false,...e},this.sampled=Math.random()<=this.config.sampleRate;}init(){!this.config.enabled||!this.sampled||typeof window>"u"||(this.config.webVitals&&this.observeWebVitals(),this.config.navigationTiming&&this.collectNavigationTiming(),this.startFlushTimer(),this.log("Performance monitoring initialized"));}startTransaction(e,t){let n=`txn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,i={id:n,name:e,startTime:performance.now(),status:"running",spans:[],data:t};return this.activeTransactions.set(n,i),this.log("Transaction started:",e,n),n}endTransaction(e,t="ok"){let n=this.activeTransactions.get(e);if(!n){this.log("Transaction not found:",e);return}n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.status=t;for(let i of n.spans)i.status==="running"&&(i.endTime=n.endTime,i.duration=i.endTime-i.startTime,i.status=t);this.activeTransactions.delete(e),this.addMetric({type:"transaction",name:n.name,value:n.duration,unit:"ms",timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0,transaction:n}),this.log("Transaction ended:",n.name,`${n.duration.toFixed(1)}ms`);}startSpan(e,t,n){let i=this.activeTransactions.get(e);if(!i)return this.log("Transaction not found for span:",e),"";let s={id:`span_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,name:t,startTime:performance.now(),status:"running",data:n};return i.spans.push(s),s.id}endSpan(e,t,n="ok"){let i=this.activeTransactions.get(e);if(!i)return;let s=i.spans.find(o=>o.id===t);s&&(s.endTime=performance.now(),s.duration=s.endTime-s.startTime,s.status=n);}getVitals(){return {...this.vitals}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush();}observeWebVitals(){if(!(typeof PerformanceObserver>"u")){try{new PerformanceObserver(t=>{let n=t.getEntries(),i=n[n.length-1];i&&(this.vitals.lcp=i.startTime,this.reportVital("LCP",i.startTime));}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let n=t.getEntries()[0];if(n){let i=n.processingStart-n.startTime;this.vitals.fid=i,this.reportVital("FID",i);}}).observe({type:"first-input",buffered:!0});}catch{}try{let e=0;new PerformanceObserver(n=>{for(let i of n.getEntries()){let s=i;s.hadRecentInput||(e+=s.value);}this.vitals.cls=e;}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e>0&&this.reportVital("CLS",e,"score");});}catch{}try{new PerformanceObserver(t=>{let n=t.getEntries().find(i=>i.name==="first-contentful-paint");n&&(this.vitals.fcp=n.startTime,this.reportVital("FCP",n.startTime));}).observe({type:"paint",buffered:!0});}catch{}try{let e=0;new PerformanceObserver(n=>{for(let i of n.getEntries()){let s=i.duration;s>e&&(e=s,this.vitals.inp=e);}}).observe({type:"event",buffered:!0});}catch{}}}collectNavigationTiming(){if(typeof window>"u"||!window.performance)return;let e=()=>{let t=performance.getEntriesByType("navigation")[0];if(!t)return;let n=t.responseStart-t.requestStart;this.vitals.ttfb=n,this.reportVital("TTFB",n),this.addMetric({type:"navigation",name:"page_load",value:t.loadEventEnd-t.startTime,unit:"ms",timestamp:new Date().toISOString(),url:window.location.href,data:{dns:t.domainLookupEnd-t.domainLookupStart,tcp:t.connectEnd-t.connectStart,ttfb:n,domContentLoaded:t.domContentLoadedEventEnd-t.startTime,domComplete:t.domComplete-t.startTime,transferSize:t.transferSize,encodedBodySize:t.encodedBodySize,decodedBodySize:t.decodedBodySize}});};document.readyState==="complete"?setTimeout(e,0):window.addEventListener("load",()=>setTimeout(e,0));}reportVital(e,t,n="ms"){this.addMetric({type:"web_vital",name:e,value:t,unit:n,timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0});}addMetric(e){this.metrics.push(e);}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush();});}async flush(){if(this.metrics.length===0)return;if(this.disabled){this.metrics=[];return}let e=[...this.metrics];this.metrics=[];let t=this.config.performanceEndpoint||`${this.config.endpoint}/api/performance`;try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} performance metrics`);}catch(n){if(this.flushFailures++,this.flushFailures>=3){this.disabled=true,console.warn(`[SitePong Performance] Disabled after 3 consecutive failures. Check that ${t} is accessible and has proper CORS headers.`);return}this.metrics.unshift(...e),this.log(`Failed to flush metrics (attempt ${this.flushFailures}/3):`,n);}}log(...e){this.config.debug&&console.log("[SitePong Performance]",...e);}};function Fe(r){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}}catch{}let e="";for(let t=0;t<r;t++)e+=Math.floor(Math.random()*256).toString(16).padStart(2,"0");return e}function ae(){return Fe(16)}function z(){return Fe(8)}function le(){return {traceId:ae(),spanId:z(),parentSpanId:null,sampled:true}}function V(r){let e=r.sampled?"01":"00";return {traceparent:`00-${r.traceId}-${r.spanId}-${e}`,tracestate:`sitepong=${r.spanId}`}}function _e(r){let e=r.traceparent||r.Traceparent;if(!e)return null;let t=e.split("-");if(t.length!==4)return null;let[n,i,s,o]=t;if(n!=="00"||i.length!==32||!/^[0-9a-f]{32}$/.test(i)||s.length!==16||!/^[0-9a-f]{16}$/.test(s)||o.length!==2||!/^[0-9a-f]{2}$/.test(o))return null;let l=(parseInt(o,16)&1)===1;return {traceId:i,spanId:z(),parentSpanId:s,sampled:l}}var $=class{constructor(e){this.originalFetch=null;this.targets=e;}shouldPropagate(e){return this.targets.some(t=>{if(t.includes("*")){let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}return e.startsWith(t)})}injectHeaders(e,t,n){if(!this.shouldPropagate(e))return t;let i=V(n);return {...t,...i}}start(){if(typeof window>"u"||!window.fetch||this.originalFetch)return;this.originalFetch=window.fetch;let e=this;window.fetch=function(t,n){let i=typeof t=="string"?t:t instanceof URL?t.toString():t.url;if(e.shouldPropagate(i)){let s=le(),o=V(s),l={};if(n?.headers)if(n.headers instanceof Headers)n.headers.forEach((f,g)=>{l[g]=f;});else if(Array.isArray(n.headers))for(let[f,g]of n.headers)l[f]=g;else Object.assign(l,n.headers);let c={...l,...o},u={...n,headers:c};return e.originalFetch.call(window,t,u)}return e.originalFetch.call(window,t,n)};}stop(){typeof window>"u"||this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null);}};var K=class{constructor(e){this.apiKey=e.apiKey,this.endpoint=e.endpoint,this.debug=e.debug||false;}async checkin(e,t={}){try{let n=await fetch(`${this.endpoint}/api/sdk/crons`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({slug:e,status:t.status||"ok",duration_ms:t.duration_ms,message:t.message,environment:t.environment})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.log(`Check-in sent for "${e}" (${t.status||"ok"})`);}catch(n){this.log("Failed to send check-in:",n);}}start(e,t){let n=Date.now();return this.checkin(e,{status:"in_progress",environment:t}),{ok:async i=>{let s=Date.now()-n;await this.checkin(e,{status:"ok",duration_ms:s,message:i,environment:t});},error:async i=>{let s=Date.now()-n;await this.checkin(e,{status:"error",duration_ms:s,message:i,environment:t});}}}wrap(e,t,n){let i=this.start(e,n);return t().then(async s=>(await i.ok(),s),async s=>{throw await i.error(s?.message||String(s)),s})}log(...e){this.debug&&console.log("[SitePong:Cron]",...e);}};var q=class{constructor(e){this.queue=[];this.flushTimer=null;this.apiKey=e.apiKey,this.endpoint=e.endpoint,this.debug=e.debug||false,this.flushInterval=e.flushInterval||1e4,this.maxBatchSize=e.maxBatchSize||100,this.startFlushTimer();}increment(e,t=1,n){this.enqueue(e,t,"counter",n);}decrement(e,t=1,n){this.enqueue(e,-t,"counter",n);}gauge(e,t,n){this.enqueue(e,t,"gauge",n);}histogram(e,t,n){this.enqueue(e,t,"histogram",n);}distribution(e,t,n){this.enqueue(e,t,"distribution",n);}async time(e,t,n){let i=Date.now();try{let s=await t();return this.distribution(e,Date.now()-i,{...n,unit:n?.unit||"ms"}),s}catch(s){throw this.distribution(e,Date.now()-i,{...n,unit:n?.unit||"ms",tags:{...n?.tags,error:"true"}}),s}}startTimer(e,t){let n=Date.now();return {stop:()=>{this.distribution(e,Date.now()-n,{...t,unit:t?.unit||"ms"});}}}async flush(){if(this.queue.length===0)return;let e=[...this.queue];this.queue=[];try{let t=await fetch(`${this.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({metrics:e})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} metrics`);}catch(t){this.queue.unshift(...e),this.log("Failed to flush metrics:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}enqueue(e,t,n,i){this.queue.push({name:e,value:t,type:n,unit:i?.unit,tags:i?.tags,timestamp:i?.timestamp||new Date().toISOString()}),this.queue.length>=this.maxBatchSize&&this.flush();}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.flushInterval),typeof window<"u"&&window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();});}flushWithBeacon(){if(this.queue.length===0||typeof navigator?.sendBeacon!="function")return;let e=[...this.queue];this.queue=[];let t=new Blob([JSON.stringify({metrics:e,apiKey:this.apiKey})],{type:"application/json"});navigator.sendBeacon(`${this.endpoint}/api/sdk/metrics`,t),this.log(`Flushed ${e.length} metrics via beacon`);}log(...e){this.debug&&console.log("[SitePong:Metrics]",...e);}};var W=class{constructor(e){this.queue=[];this.flushTimer=null;this.queryCounter=0;this.nPlusOneDetector=new Map;this.config={slowQueryThreshold:1e3,maxBatchSize:50,flushInterval:1e4,redactParams:true,...e},this.startFlushTimer();}async track(e,t,n){let i=Date.now();this.queryCounter++;try{let s=await t(),o=Date.now()-i;return this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:o,timestamp:new Date().toISOString(),source:n,is_slow:o>=(this.config.slowQueryThreshold||1e3)}),this.detectNPlusOne(e),s}catch(s){let o=Date.now()-i;throw this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:o,timestamp:new Date().toISOString(),source:n,error:s instanceof Error?s.message:String(s)}),s}}trackSync(e,t,n){let i=Date.now();this.queryCounter++;try{let s=t(),o=Date.now()-i;return this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:o,timestamp:new Date().toISOString(),source:n,is_slow:o>=(this.config.slowQueryThreshold||1e3)}),s}catch(s){let o=Date.now()-i;throw this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:o,timestamp:new Date().toISOString(),source:n,error:s instanceof Error?s.message:String(s)}),s}}getQueryCount(){return this.queryCounter}resetQueryCount(){this.queryCounter=0,this.nPlusOneDetector.clear();}getNPlusOnePatterns(){let e=[];for(let[t,{count:n}]of this.nPlusOneDetector.entries())n>=5&&e.push({query:t,count:n});return e}async flush(){if(this.queue.length===0)return;let e=[...this.queue];this.queue=[];try{let t=await fetch(`${this.config.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e.map(n=>({name:"db.query",value:n.duration_ms,type:"distribution",unit:"ms",tags:{query:n.query.substring(0,200),source:n.source||"unknown",is_slow:String(n.is_slow||!1),...n.error?{error:"true"}:{}},timestamp:n.timestamp}))})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} query events`);}catch(t){this.queue.unshift(...e),this.log("Failed to flush query events:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}recordQuery(e){this.queue.push(e),this.queue.length>=(this.config.maxBatchSize||50)&&this.flush(),e.is_slow&&this.log(`Slow query (${e.duration_ms}ms):`,e.query.substring(0,100));}detectNPlusOne(e){let t=this.normalizeQuery(e),n=Date.now(),i=this.nPlusOneDetector.get(t);if(i?n-i.since<1e3?(i.count++,i.count===5&&this.log(`N+1 query detected! Pattern repeated ${i.count} times:`,t.substring(0,100))):this.nPlusOneDetector.set(t,{count:1,since:n}):this.nPlusOneDetector.set(t,{count:1,since:n}),this.nPlusOneDetector.size>100){let s=[...this.nPlusOneDetector.entries()];s.sort((o,l)=>o[1].since-l[1].since);for(let o=0;o<50;o++)this.nPlusOneDetector.delete(s[o][0]);}}normalizeQuery(e){return e.replace(/\s+/g," ").replace(/'[^']*'/g,"?").replace(/\b\d+\b/g,"?").trim().substring(0,300)}redactQuery(e){return e.replace(/'[^']*'/g,"'***'").replace(/\b\d{4,}\b/g,"***")}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval||1e4);}log(...e){this.config.debug&&console.log("[SitePong:DB]",...e);}};var X=class{constructor(e){this.profiles=[];this.activeProfile=null;this.frameStack=[];this.flushTimer=null;this.config={sampleRate:.1,maxDuration:3e4,flushInterval:3e4,...e},this.startFlushTimer();}async profile(e,t,n){if(Math.random()>(this.config.sampleRate||.1))return t();let i=this.generateId(),s=performance.now();this.activeProfile={id:i,name:e,startTime:s,duration_ms:0,frames:[],metadata:n},this.frameStack=[];let o={name:e,start_ms:0,duration_ms:0,children:[],metadata:n};this.frameStack.push(o);try{let l=await t();return o.duration_ms=performance.now()-s,this.activeProfile.duration_ms=o.duration_ms,this.activeProfile.frames=[o],o.duration_ms<=(this.config.maxDuration||3e4)&&this.profiles.push(this.activeProfile),this.activeProfile=null,this.frameStack=[],l}catch(l){throw o.duration_ms=performance.now()-s,o.metadata={...o.metadata,error:true},this.activeProfile&&(this.activeProfile.duration_ms=o.duration_ms,this.activeProfile.frames=[o],this.profiles.push(this.activeProfile)),this.activeProfile=null,this.frameStack=[],l}}startSpan(e,t){if(!this.activeProfile)return ()=>{};let n=performance.now()-this.activeProfile.startTime,i={name:e,start_ms:n,duration_ms:0,children:[],metadata:t},s=this.frameStack[this.frameStack.length-1];return s&&s.children.push(i),this.frameStack.push(i),()=>{i.duration_ms=performance.now()-this.activeProfile.startTime-i.start_ms,this.frameStack.pop();}}getProfiles(){return [...this.profiles]}getLatestProfile(){return this.profiles.length>0?this.profiles[this.profiles.length-1]:null}async flush(){if(this.profiles.length===0)return;let e=[...this.profiles];this.profiles=[];try{let t=await fetch(`${this.config.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e.map(n=>({name:`profile.${n.name}`,value:n.duration_ms,type:"distribution",unit:"ms",tags:{profile_id:n.id,frame_count:String(Ae(n.frames)),...n.metadata||{}},timestamp:new Date(Date.now()-n.duration_ms).toISOString()}))})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} profiles`);}catch(t){this.profiles.unshift(...e),this.log("Failed to flush profiles:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval||3e4);}generateId(){return `prof_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,8)}`}log(...e){this.config.debug&&console.log("[SitePong:Profiler]",...e);}};function Ae(r){let e=r.length;for(let t of r)e+=Ae(t.children);return e}var b="https://ingest.sitepong.com",It=10,Rt=5e3,ce=3,ue=class{constructor(){this.errorQueue=[];this.flushTimer=null;this.context={};this.initialized=false;this.flushFailures=0;this.disabled=false;this.flagManager=null;this.analyticsManager=null;this.fingerprintManager=null;this.replayManager=null;this.performanceManager=null;this.cronManager=null;this.metricsManager=null;this.databaseTracker=null;this.profiler=null;this.config={apiKey:"",endpoint:b,environment:"production",release:"",autoCapture:true,maxBatchSize:It,flushInterval:Rt,debug:false};}init(e){if(!e.apiKey){console.error("[SitePong] API key is required");return}this.config={...this.config,...e},this.initialized=true,this.config.autoCapture&&this.setupAutoCapture(),this.startFlushTimer(),this.log("Initialized with endpoint:",this.config.endpoint),e.enableFlags&&(this.flagManager=new x({apiKey:e.apiKey,endpoint:e.flagsEndpoint||e.endpoint||b,debug:e.debug}),this.flagManager.init().catch(t=>{this.log("Failed to initialize flags:",t);})),e.analytics?.enabled&&(this.analyticsManager&&this.analyticsManager.destroy(),this.analyticsManager=new C({apiKey:e.apiKey,endpoint:e.endpoint||b,enabled:true,autocapturePageviews:e.analytics.autocapturePageviews,autocaptureClicks:e.analytics.autocaptureClicks,autocaptureForms:e.analytics.autocaptureForms,autocapture:e.analytics.autocapture,maxBatchSize:e.analytics.maxBatchSize,flushInterval:e.analytics.flushInterval,eventsEndpoint:e.analytics.eventsEndpoint,debug:e.debug}),this.analyticsManager.init()),e.fingerprint?.enabled&&(this.fingerprintManager=new I({apiKey:e.apiKey,endpoint:e.endpoint||b,enabled:true,extendedSignals:e.fingerprint.extendedSignals,visitorEndpoint:e.fingerprint.visitorEndpoint,debug:e.debug})),e.performance?.enabled&&(this.performanceManager&&this.performanceManager.destroy(),this.performanceManager=new _({apiKey:e.apiKey,endpoint:e.endpoint||b,enabled:true,webVitals:e.performance.webVitals,navigationTiming:e.performance.navigationTiming,resourceTiming:e.performance.resourceTiming,sampleRate:e.performance.sampleRate,flushInterval:e.performance.flushInterval,performanceEndpoint:e.performance.performanceEndpoint,debug:e.debug}),this.performanceManager.init()),e.replay?.enabled&&(this.replayManager&&this.replayManager.stop(),this.replayManager=new F({apiKey:e.apiKey,endpoint:e.endpoint||b,enabled:true,maskInputs:e.replay.maskInputs,blockSelector:e.replay.blockSelector,maskSelector:e.replay.maskSelector,sampleRate:e.replay.sampleRate,maxSessionDuration:e.replay.maxSessionDuration,flushInterval:e.replay.flushInterval,replayEndpoint:e.replay.replayEndpoint,recordNetwork:e.replay.recordNetwork,captureNetworkHeaders:e.replay.captureNetworkHeaders,recordConsole:e.replay.recordConsole,consoleLevels:e.replay.consoleLevels,debug:e.debug}),this.replayManager.start()),e.crons?.enabled&&(this.cronManager=new K({apiKey:e.apiKey,endpoint:e.endpoint||b,debug:e.debug})),e.database?.enabled&&(this.databaseTracker=new W({apiKey:e.apiKey,endpoint:e.endpoint||b,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.metrics?.enabled&&(this.metricsManager=new q({apiKey:e.apiKey,endpoint:e.endpoint||b,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.profiling?.enabled&&(this.profiler=new X({apiKey:e.apiKey,endpoint:e.endpoint||b,debug:e.debug,sampleRate:e.profiling.sampleRate,maxDuration:e.profiling.maxDuration,flushInterval:e.profiling.flushInterval}));}isInitialized(){return this.initialized}getFlag(e,t=false){return this.flagManager?this.flagManager.getFlag(e,t):(this.log("Flags not enabled. Set enableFlags: true in init()"),t)}getAllFlags(){return this.flagManager?this.flagManager.getAllFlags():{}}async waitForFlags(){this.flagManager&&await this.flagManager.waitForInit();}areFlagsReady(){return this.flagManager?.isInitialized()??false}getVariant(e,t=null){return this.flagManager?this.flagManager.getVariant(e,t):(this.log("Flags not enabled. Set enableFlags: true in init()"),t)}getVariantPayload(e,t=null){return this.flagManager?this.flagManager.getVariantPayload(e,t):t}async refreshFlags(){this.flagManager&&await this.flagManager.refresh();}track(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.track(e,t);}trackPageView(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.trackPageView(e,t);}identify(e,t){if(this.replayManager&&this.replayManager.setUser({id:e}),!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.identify(e,t);}group(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.group(e,t);}resetAnalytics(){this.analyticsManager&&this.analyticsManager.reset();}async getVisitorId(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getVisitorId()}async getDeviceSignals(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getDeviceSignals()}async getFraudCheck(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getFraudCheck()}startReplay(){return this.replayManager?this.replayManager.start():(this.log("Replay not enabled. Set replay.enabled: true in init()"),false)}stopReplay(){this.replayManager&&this.replayManager.stop();}isReplayRecording(){return this.replayManager?.isRecording()??false}getReplaySessionId(){return this.replayManager?.getSessionId()??null}startTransaction(e,t){return this.performanceManager?this.performanceManager.startTransaction(e,t):(this.log("Performance not enabled. Set performance.enabled: true in init()"),"")}endTransaction(e,t="ok"){this.performanceManager&&this.performanceManager.endTransaction(e,t);}startSpan(e,t,n){return this.performanceManager?this.performanceManager.startSpan(e,t,n):""}endSpan(e,t,n="ok"){this.performanceManager&&this.performanceManager.endSpan(e,t,n);}getWebVitals(){return this.performanceManager?this.performanceManager.getVitals():{}}cronCheckin(e,t){return this.cronManager?this.cronManager.checkin(e,t):(this.log("Cron monitoring not enabled. Set crons.enabled: true in init()"),Promise.resolve())}cronStart(e,t){return this.cronManager?this.cronManager.start(e,t):(this.log("Cron monitoring not enabled. Set crons.enabled: true in init()"),{ok:()=>Promise.resolve(),error:()=>Promise.resolve()})}cronWrap(e,t,n){return this.cronManager?this.cronManager.wrap(e,t,n):t()}metricIncrement(e,t,n){if(!this.metricsManager){this.log("Metrics not enabled. Set metrics.enabled: true in init()");return}this.metricsManager.increment(e,t,n);}metricGauge(e,t,n){this.metricsManager&&this.metricsManager.gauge(e,t,n);}metricHistogram(e,t,n){this.metricsManager&&this.metricsManager.histogram(e,t,n);}metricDistribution(e,t,n){this.metricsManager&&this.metricsManager.distribution(e,t,n);}async metricTime(e,t,n){return this.metricsManager?this.metricsManager.time(e,t,n):t()}metricStartTimer(e,t){return this.metricsManager?this.metricsManager.startTimer(e,t):{stop:()=>{}}}async flushMetrics(){if(this.metricsManager)return this.metricsManager.flush()}async dbTrack(e,t,n){return this.databaseTracker?this.databaseTracker.track(e,t,n):t()}dbTrackSync(e,t,n){return this.databaseTracker?this.databaseTracker.trackSync(e,t,n):t()}getDbQueryCount(){return this.databaseTracker?this.databaseTracker.getQueryCount():0}resetDbQueryCount(){this.databaseTracker&&this.databaseTracker.resetQueryCount();}getDbNPlusOnePatterns(){return this.databaseTracker?this.databaseTracker.getNPlusOnePatterns():[]}async profile(e,t,n){return this.profiler?this.profiler.profile(e,t,n):t()}startProfileSpan(e,t){return this.profiler?this.profiler.startSpan(e,t):()=>{}}getProfiles(){return this.profiler?this.profiler.getProfiles():[]}getLatestProfile(){return this.profiler?this.profiler.getLatestProfile():null}async flushProfiles(){if(this.profiler)return this.profiler.flush()}setContext(e){this.context={...this.context,...e};}setUser(e){this.context.user=e,this.replayManager&&this.replayManager.setUser(e?{id:e.id}:null);}setTags(e){this.context.tags={...this.context.tags,...e};}clearUser(){this.context.user=void 0,this.replayManager&&this.replayManager.setUser(null);}addBreadcrumb(e){this.log("Breadcrumb added:",e);}captureError(e,t){if(!this.initialized){console.warn("[SitePong] SDK not initialized. Call init() first.");return}let n=this.formatError(e,t);this.errorQueue.push(n),this.log("Captured error:",n.message),this.errorQueue.length>=this.config.maxBatchSize&&this.flush();}captureMessage(e,t="info",n){if(!this.initialized){console.warn("[SitePong] SDK not initialized. Call init() first.");return}let i={message:e,type:t,timestamp:new Date().toISOString(),url:this.getUrl(),userAgent:this.getUserAgent(),environment:this.config.environment,release:this.config.release,context:{...this.context,...n},replaySessionId:this.replayManager?.isRecording()&&this.replayManager.getSessionId()||void 0};this.errorQueue.push(i),this.log("Captured message:",e),this.errorQueue.length>=this.config.maxBatchSize&&this.flush();}async flush(){if(this.errorQueue.length===0)return;if(this.disabled){this.errorQueue=[];return}let e=[...this.errorQueue];this.errorQueue=[];try{let t=await fetch(`${this.config.endpoint}/api/errors/batch`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({errors:e})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} errors`);}catch(t){if(this.flushFailures++,this.flushFailures>=ce){this.disabled=true,console.warn(`[SitePong] SDK disabled after ${ce} consecutive failures. Events will no longer be sent. This may be due to CORS issues or network problems. Check that ${this.config.endpoint} is accessible and has proper CORS headers.`);return}this.errorQueue.unshift(...e),this.log(`Failed to flush errors (attempt ${this.flushFailures}/${ce}):`,t);}}formatError(e,t){let n=e instanceof Error,i=n?e.message:String(e),s=n?e.stack:new Error(i).stack,o=n?e.name:"Error";return {message:i,stack:s,type:o,timestamp:new Date().toISOString(),url:this.getUrl(),userAgent:this.getUserAgent(),environment:this.config.environment,release:this.config.release,context:{...this.context,...t},fingerprint:this.generateFingerprint(i,s,o),replaySessionId:this.replayManager?.isRecording()&&this.replayManager.getSessionId()||void 0}}generateFingerprint(e,t,n){let i=n||"Error",s=this.normalizeMessage(e),o=t?this.extractTopFrame(t):"",l=[i,s,o].join(`
|
|
6
|
+
`),c=2166136261;for(let u=0;u<l.length;u++)c^=l.charCodeAt(u),c=Math.imul(c,16777619);return (c>>>0).toString(16).padStart(8,"0")}normalizeMessage(e){return e.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"<uuid>").replace(/\b0x[0-9a-f]{4,}\b/gi,"<hex>").replace(/\b[0-9a-f]{8,}\b/gi,"<hex>").replace(/https?:\/\/[^\s)"']+/g,"<url>").replace(/\b\d+(\.\d+)?\b/g,"<n>").replace(/\s+/g," ").trim()}extractTopFrame(e){let t=e.split(`
|
|
7
|
+
`);for(let n=1;n<t.length;n++){let i=t[n].trim();if(i&&(i.startsWith("at ")||/^\w+@/.test(i)))return i.replace(/:\d+\)?\s*$/,")")}return ""}setupAutoCapture(){typeof window<"u"?(window.addEventListener("error",e=>{this.captureError(e.error||e.message);}),window.addEventListener("unhandledrejection",e=>{let t=e.reason instanceof Error?e.reason:new Error(String(e.reason));this.captureError(t);}),this.log("Auto-capture enabled for browser")):typeof process<"u"&&(process.on("uncaughtException",e=>{this.captureError(e),this.flush().finally(()=>process.exit(1));}),process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));this.captureError(t);}),this.log("Auto-capture enabled for Node.js"));}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof window<"u"&&(window.addEventListener("beforeunload",()=>{this.flush();}),window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();}));}flushWithBeacon(){if(this.errorQueue.length===0||typeof navigator?.sendBeacon!="function")return;let e=[...this.errorQueue];this.errorQueue=[];let t=new Blob([JSON.stringify({errors:e,apiKey:this.config.apiKey})],{type:"application/json"});navigator.sendBeacon(`${this.config.endpoint}/api/errors/batch`,t),this.log(`Flushed ${e.length} errors via beacon`);}getUrl(){if(typeof window<"u")return window.location.href}getUserAgent(){if(typeof navigator<"u")return navigator.userAgent}log(...e){this.config.debug&&console.log("[SitePong]",...e);}},a=new ue,Yn=a.init.bind(a),Jn=a.captureError.bind(a),Zn=a.captureMessage.bind(a),er=a.setContext.bind(a),tr=a.setUser.bind(a),nr=a.setTags.bind(a),rr=a.flush.bind(a),ir=a.isInitialized.bind(a),sr=a.clearUser.bind(a),or=a.addBreadcrumb.bind(a);var ar=a.getFlag.bind(a),lr=a.getAllFlags.bind(a),cr=a.getVariant.bind(a),ur=a.getVariantPayload.bind(a),dr=a.waitForFlags.bind(a),fr=a.areFlagsReady.bind(a),pr=a.refreshFlags.bind(a),hr=a.track.bind(a),gr=a.trackPageView.bind(a),mr=a.identify.bind(a),vr=a.group.bind(a),yr=a.resetAnalytics.bind(a),br=a.getVisitorId.bind(a),wr=a.getDeviceSignals.bind(a),Sr=a.getFraudCheck.bind(a),Tr=a.startReplay.bind(a),xr=a.stopReplay.bind(a),kr=a.isReplayRecording.bind(a),Er=a.getReplaySessionId.bind(a),Mr=a.startTransaction.bind(a),Cr=a.endTransaction.bind(a),Pr=a.startSpan.bind(a),Ir=a.endSpan.bind(a),Rr=a.getWebVitals.bind(a),Dr=a.dbTrack.bind(a),Fr=a.dbTrackSync.bind(a),_r=a.getDbQueryCount.bind(a),Ar=a.resetDbQueryCount.bind(a),Lr=a.getDbNPlusOnePatterns.bind(a),Or=a.cronCheckin.bind(a),Nr=a.cronStart.bind(a),Hr=a.cronWrap.bind(a),Br=a.metricIncrement.bind(a),Ur=a.metricGauge.bind(a),Vr=a.metricHistogram.bind(a),$r=a.metricDistribution.bind(a),zr=a.metricTime.bind(a),Kr=a.metricStartTimer.bind(a),qr=a.flushMetrics.bind(a),Wr=a.profile.bind(a),Xr=a.startProfileSpan.bind(a),Gr=a.getProfiles.bind(a),Qr=a.getLatestProfile.bind(a),jr=a.flushProfiles.bind(a),Yr=a;exports.TracePropagator=$;exports.addBreadcrumb=or;exports.areFlagsReady=fr;exports.captureError=Jn;exports.captureMessage=Zn;exports.clearAnonymousId=de;exports.clearUser=sr;exports.client=a;exports.createTraceContext=le;exports.cronCheckin=Or;exports.cronStart=Nr;exports.cronWrap=Hr;exports.dbTrack=Dr;exports.dbTrackSync=Fr;exports.default=Yr;exports.endSpan=Ir;exports.endTransaction=Cr;exports.extractTrace=_e;exports.flush=rr;exports.flushMetrics=qr;exports.flushProfiles=jr;exports.generateSpanId=z;exports.generateTraceId=ae;exports.getAllFlags=lr;exports.getAnonymousId=T;exports.getDbNPlusOnePatterns=Lr;exports.getDbQueryCount=_r;exports.getDeviceSignals=wr;exports.getFlag=ar;exports.getFraudCheck=Sr;exports.getLatestProfile=Qr;exports.getProfiles=Gr;exports.getReplaySessionId=Er;exports.getVariant=cr;exports.getVariantPayload=ur;exports.getVisitorId=br;exports.getWebVitals=Rr;exports.group=vr;exports.identify=mr;exports.init=Yn;exports.isInitialized=ir;exports.isReplayRecording=kr;exports.metricDistribution=$r;exports.metricGauge=Ur;exports.metricHistogram=Vr;exports.metricIncrement=Br;exports.metricStartTimer=Kr;exports.metricTime=zr;exports.profile=Wr;exports.propagateTrace=V;exports.refreshFlags=pr;exports.resetAnalytics=yr;exports.resetDbQueryCount=Ar;exports.setAnonymousId=fe;exports.setContext=er;exports.setTags=nr;exports.setUser=tr;exports.startProfileSpan=Xr;exports.startReplay=Tr;exports.startSpan=Pr;exports.startTransaction=Mr;exports.stopReplay=xr;exports.track=hr;exports.trackPageView=gr;exports.waitForFlags=dr;Object.defineProperty(exports,'__esModule',{value:true});return exports;})({});//# sourceMappingURL=sitepong.min.js.map
|
|
8
|
+
//# sourceMappingURL=sitepong.min.js.map
|