@clianta/sdk 1.6.0 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * Clianta SDK v1.6.0
2
+ * Clianta SDK v1.6.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
6
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Clianta={})}(this,function(e){"use strict";const t="1.6.0",i={projectId:"",apiEndpoint:"undefined"!=typeof process&&process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT?process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT:"undefined"!=typeof process&&process.env?.VITE_CLIANTA_API_ENDPOINT?process.env.VITE_CLIANTA_API_ENDPOINT:"undefined"!=typeof process&&process.env?.REACT_APP_CLIANTA_API_ENDPOINT?process.env.REACT_APP_CLIANTA_API_ENDPOINT:"undefined"!=typeof process&&process.env?.CLIANTA_API_ENDPOINT?process.env.CLIANTA_API_ENDPOINT:"http://localhost:5000",authToken:"",apiKey:"",debug:!1,autoPageView:!0,plugins:["pageView","forms","scroll","clicks","engagement","downloads","exitIntent"],sessionTimeout:18e5,batchSize:10,flushInterval:5e3,consent:{defaultConsent:{analytics:!0,marketing:!1,personalization:!1},waitForConsent:!1,storageKey:"mb_consent",anonymousMode:!1},cookieDomain:"",useCookies:!1,cookielessMode:!1,persistMode:"session"},n="mb_vid",s="mb_sid",r="mb_st",a="mb_consent",o="mb_queue",c=[25,50,75,100],d=[".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".rar",".tar",".gz",".7z",".csv",".txt",".json",".xml",".mp3",".mp4",".wav",".avi",".mov"];const l="[Clianta]",u={debug:"color: #6b7280; font-weight: normal;",info:"color: #3b82f6; font-weight: normal;",warn:"color: #f59e0b; font-weight: bold;",error:"color: #ef4444; font-weight: bold;"},h={debug:0,info:1,warn:2,error:3};const p=function(e=!1){let t="debug",i=e;const n=e=>!!i&&h[e]>=h[t],s=(e,t)=>"undefined"!=typeof console&&"undefined"!=typeof window?[`%c${l}`,u[e],...t]:[`${l} [${e.toUpperCase()}]`,...t];return{get enabled(){return i},set enabled(e){i=e},debug(...e){n("debug")&&"undefined"!=typeof console&&console.log(...s("debug",e))},info(...e){n("info")&&"undefined"!=typeof console&&console.info(...s("info",e))},warn(...e){n("warn")&&"undefined"!=typeof console&&console.warn(...s("warn",e))},error(...e){n("error")&&"undefined"!=typeof console&&console.error(...s("error",e))},setLevel(e){t=e}}}(!1);class g{constructor(e){this.config={apiEndpoint:e.apiEndpoint,maxRetries:e.maxRetries??3,retryDelay:e.retryDelay??1e3,timeout:e.timeout??1e4}}async sendEvents(e){const t=`${this.config.apiEndpoint}/api/public/track/event`,i=JSON.stringify({events:e});return this.send(t,i)}async sendIdentify(e){const t=`${this.config.apiEndpoint}/api/public/track/identify`;try{const i=await this.fetchWithTimeout(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}),n=await i.json().catch(()=>({}));return i.ok?(p.debug("Identify successful, contactId:",n.contactId),{success:!0,status:i.status,contactId:n.contactId??void 0}):(i.status>=500?p.warn(`Identify server error (${i.status})`):p.error(`Identify failed with status ${i.status}:`,n.message),{success:!1,status:i.status})}catch(e){return p.error("Identify request failed:",e),{success:!1,error:e}}}sendBeacon(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return p.warn("sendBeacon not available, events may be lost"),!1;const t=`${this.config.apiEndpoint}/api/public/track/event`,i=JSON.stringify({events:e}),n=new Blob([i],{type:"application/json"});try{const i=navigator.sendBeacon(t,n);return i?p.debug(`Beacon sent ${e.length} events`):p.warn("sendBeacon returned false"),i}catch(e){return p.error("sendBeacon error:",e),!1}}async fetchData(e,t){const i=new URL(`${this.config.apiEndpoint}${e}`);t&&Object.entries(t).forEach(([e,t])=>{null!=t&&i.searchParams.set(e,t)});try{const t=await this.fetchWithTimeout(i.toString(),{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const i=await t.json();return p.debug("Fetch successful:",e),{success:!0,data:i.data??i,status:t.status}}return p.error(`Fetch failed with status ${t.status}`),{success:!1,status:t.status}}catch(e){return p.error("Fetch request failed:",e),{success:!1,error:e}}}async send(e,t,i=1){try{const n=await this.fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0});return n.ok?(p.debug("Request successful:",e),{success:!0,status:n.status}):n.status>=500&&i<this.config.maxRetries?(p.warn(`Server error (${n.status}), retrying...`),await this.delay(this.config.retryDelay*i),this.send(e,t,i+1)):(p.error(`Request failed with status ${n.status}`),{success:!1,status:n.status})}catch(n){return i<this.config.maxRetries?(p.warn(`Network error, retrying (${i}/${this.config.maxRetries})...`),await this.delay(this.config.retryDelay*i),this.send(e,t,i+1)):(p.error("Request failed after retries:",n),{success:!1,error:n})}}async fetchWithTimeout(e,t){const i=new AbortController,n=setTimeout(()=>i.abort(),this.config.timeout);try{return await fetch(e,{...t,signal:i.signal})}finally{clearTimeout(n)}}delay(e){return new Promise(t=>setTimeout(t,e))}}function m(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function f(e){try{if("undefined"!=typeof sessionStorage)return sessionStorage.getItem(e)}catch{}return null}function y(e,t){try{if("undefined"!=typeof sessionStorage)return sessionStorage.setItem(e,t),!0}catch{}return!1}function w(e,t,i){if("undefined"==typeof document)return null;if(void 0===t){const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?t[2]:null}let n="";if(i){const e=new Date;e.setTime(e.getTime()+24*i*60*60*1e3),n="; expires="+e.toUTCString()}const s="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";return document.cookie=e+"="+t+n+"; path=/; SameSite=Lax"+s,t}function v(e=!1){const t=n;let i=null;return i=e?w(t):function(e){try{if("undefined"!=typeof localStorage)return localStorage.getItem(e)}catch{}return null}(t),i||(i=m(),e?w(t,i,365):function(e,t){try{if("undefined"!=typeof localStorage)return localStorage.setItem(e,t),!0}catch{}}(t,i)),i}function b(e=!1){const t=n;if(e)w(t,"",-1);else try{localStorage.removeItem(t)}catch{}try{sessionStorage.removeItem(s),sessionStorage.removeItem(r)}catch{}}function k(){if("undefined"==typeof window)return{};try{const e=new URLSearchParams(window.location.search);return{utmSource:e.get("utm_source")||void 0,utmMedium:e.get("utm_medium")||void 0,utmCampaign:e.get("utm_campaign")||void 0,utmTerm:e.get("utm_term")||void 0,utmContent:e.get("utm_content")||void 0}}catch{return{}}}function I(e){try{return e.split("/").pop()?.split("?")[0]||"unknown"}catch{return"unknown"}}function T(e){const t=I(e).split(".");return t.length>1&&t.pop()||"unknown"}function S(e,t=100){return(e.innerText||e.textContent||e.value||"").trim().substring(0,t)}class E{constructor(e,t={}){this.queue=[],this.flushTimer=null,this.isFlushing=!1,this.eventTimestamps=[],this.boundBeforeUnload=null,this.boundVisibilityChange=null,this.boundPageHide=null,this.transport=e,this.config={batchSize:t.batchSize??10,flushInterval:t.flushInterval??5e3,maxQueueSize:t.maxQueueSize??1e3,storageKey:t.storageKey??o},this.persistMode=t.persistMode||"session",this.restoreQueue(),this.startFlushTimer(),this.setupUnloadHandlers()}push(e){this.checkRateLimit()?(this.queue.length>=this.config.maxQueueSize&&(p.warn("Queue full, dropping oldest event"),this.queue.shift()),this.queue.push(e),p.debug("Event queued:",e.eventName,`(${this.queue.length} in queue)`),this.queue.length>=this.config.batchSize&&this.flush()):p.warn("Rate limit exceeded, event dropped:",e.eventName)}checkRateLimit(){const e=Date.now();return this.eventTimestamps=this.eventTimestamps.filter(t=>e-t<6e4),!(this.eventTimestamps.length>=100)&&(this.eventTimestamps.push(e),!0)}async flush(){if(this.isFlushing||0===this.queue.length)return;this.isFlushing=!0;const e=this.queue.length,t=this.queue.splice(0,e);try{p.debug(`Flushing ${t.length} events`),this.persistQueue([]);(await this.transport.sendEvents(t)).success?p.debug("Flush successful"):(p.warn("Flush failed, re-queuing events"),this.queue.unshift(...t),this.persistQueue(this.queue))}catch(e){p.error("Flush error:",e)}finally{this.isFlushing=!1}}flushSync(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.queue.length);p.debug(`Sync flushing ${e.length} events via beacon`);this.transport.sendBeacon(e)||(this.queue.unshift(...e),this.persistQueue(this.queue))}get length(){return this.queue.length}clear(){if(this.queue=[],this.persistQueue([]),"local"===this.persistMode&&"undefined"!=typeof localStorage)try{localStorage.removeItem(this.config.storageKey)}catch{}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"undefined"!=typeof window&&(this.boundBeforeUnload&&window.removeEventListener("beforeunload",this.boundBeforeUnload),this.boundVisibilityChange&&window.removeEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide&&window.removeEventListener("pagehide",this.boundPageHide))}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupUnloadHandlers(){"undefined"!=typeof window&&(this.boundBeforeUnload=()=>this.flushSync(),window.addEventListener("beforeunload",this.boundBeforeUnload),this.boundVisibilityChange=()=>{"hidden"===document.visibilityState&&this.flushSync()},window.addEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide=()=>this.flushSync(),window.addEventListener("pagehide",this.boundPageHide))}persistQueue(e){if("none"!==this.persistMode)try{const t=JSON.stringify(e);if("local"===this.persistMode&&"undefined"!=typeof localStorage)try{localStorage.setItem(this.config.storageKey,t)}catch{y(this.config.storageKey,t)}else y(this.config.storageKey,t)}catch{}}restoreQueue(){try{let e=null;if("local"===this.persistMode&&"undefined"!=typeof localStorage&&(e=localStorage.getItem(this.config.storageKey)),e||(e=f(this.config.storageKey)),e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.queue=t,p.debug(`Restored ${t.length} events from storage`))}}catch{}}}class x{constructor(){this.tracker=null}init(e){this.tracker=e}destroy(){this.tracker=null}track(e,t,i){this.tracker&&this.tracker.track(e,t,i)}}class C extends x{constructor(){super(...arguments),this.name="pageView",this.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=null}init(e){if(super.init(e),this.trackPageView(),"undefined"!=typeof window){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.trackPageView(),window.dispatchEvent(new Event("clianta:navigation"))},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.trackPageView(),window.dispatchEvent(new Event("clianta:navigation"))},this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler)}}destroy(){this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}trackPageView(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.track("page_view","Page Viewed",{title:document.title,path:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer||"direct",viewport:`${window.innerWidth}x${window.innerHeight}`})}}class $ extends x{constructor(){super(...arguments),this.name="scroll",this.milestonesReached=new Set,this.maxScrollDepth=0,this.pageLoadTime=0,this.scrollTimeout=null,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),"undefined"!=typeof window&&(this.boundHandler=this.handleScroll.bind(this),window.addEventListener("scroll",this.boundHandler,{passive:!0}),this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundHandler&&"undefined"!=typeof window&&window.removeEventListener("scroll",this.boundHandler),this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.milestonesReached.clear(),this.maxScrollDepth=0,this.pageLoadTime=Date.now()}handleScroll(){this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(()=>this.trackScrollDepth(),150)}trackScrollDepth(){if("undefined"==typeof window||"undefined"==typeof document)return;const e=window.innerHeight,t=document.documentElement.scrollHeight,i=window.pageYOffset||document.documentElement.scrollTop,n=t-e;if(n<=0)return;const s=Math.floor(i/n*100),r=Math.max(0,Math.min(100,s));r>this.maxScrollDepth&&(this.maxScrollDepth=r);for(const e of c)r>=e&&!this.milestonesReached.has(e)&&(this.milestonesReached.add(e),this.track("scroll_depth",`Scrolled ${e}%`,{depth:e,maxDepth:this.maxScrollDepth,timeToReach:Date.now()-this.pageLoadTime}))}}class L extends x{constructor(){super(...arguments),this.name="forms",this.trackedForms=new WeakSet,this.formInteractions=new Set,this.observer=null,this.listeners=[]}init(e){super.init(e),"undefined"!=typeof document&&(this.trackAllForms(),"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(()=>this.trackAllForms()),this.observer.observe(document.body,{childList:!0,subtree:!0})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null);for(const{element:e,event:t,handler:i}of this.listeners)e.removeEventListener(t,i);this.listeners=[],super.destroy()}addListener(e,t,i){e.addEventListener(t,i),this.listeners.push({element:e,event:t,handler:i})}trackAllForms(){document.querySelectorAll("form").forEach(e=>{this.setupFormTracking(e)})}setupFormTracking(e){if(this.trackedForms.has(e))return;this.trackedForms.add(e);const t=e.id||e.name||`form-${Math.random().toString(36).substr(2,9)}`;this.track("form_view","Form Viewed",{formId:t,action:e.action,method:e.method,fieldCount:e.elements.length}),Array.from(e.elements).forEach(e=>{if(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement){if(!e.name||"submit"===e.type||"button"===e.type)return;["focus","blur","change"].forEach(i=>{this.addListener(e,i,()=>{const n=`${t}-${e.name}-${i}`;this.formInteractions.has(n)||(this.formInteractions.add(n),this.track("form_interaction","Form Field Interaction",{formId:t,fieldName:e.name,fieldType:e.type,interactionType:i}))})})}});this.addListener(e,"submit",()=>{this.track("form_submit","Form Submitted",{formId:t,action:e.action,method:e.method}),this.autoIdentify(e)})}autoIdentify(e){const t=e.querySelector('input[type="email"], input[name*="email"]');if(!t?.value||!this.tracker)return;const i=t.value,n={},s=e.querySelector('[name*="first"], [name*="fname"]'),r=e.querySelector('[name*="last"], [name*="lname"]'),a=e.querySelector('[name*="company"], [name*="organization"]'),o=e.querySelector('[type="tel"], [name*="phone"]');s?.value&&(n.firstName=s.value),r?.value&&(n.lastName=r.value),a?.value&&(n.company=a.value),o?.value&&(n.phone=o.value),this.tracker.identify(i,n)}}class P extends x{constructor(){super(...arguments),this.name="clicks",this.boundHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),super.destroy()}handleClick(e){const t=e.target;if(!(t&&(i=t,["BUTTON","A","INPUT"].includes(i.tagName)||i.hasAttribute("data-track-click")||i.classList.contains("track-click"))))return;var i;const n=S(t,100),s=function(e){return{tag:e.tagName?.toLowerCase()||"unknown",id:e.id||"",className:e.className||"",text:S(e,50)}}(t);this.track("button_click","Button Clicked",{buttonText:n,elementType:t.tagName.toLowerCase(),elementId:s.id,elementClass:s.className,href:t.href||void 0,x:Math.round(e.clientX/window.innerWidth*100),y:Math.round(e.clientY/window.innerHeight*100),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight})}}class q extends x{constructor(){super(...arguments),this.name="engagement",this.pageLoadTime=0,this.engagementStartTime=0,this.isEngaged=!1,this.engagementTimeout=null,this.boundMarkEngaged=null,this.boundTrackTimeOnPage=null,this.boundVisibilityHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),this.engagementStartTime=Date.now(),"undefined"!=typeof document&&"undefined"!=typeof window&&(this.boundMarkEngaged=this.markEngaged.bind(this),this.boundTrackTimeOnPage=this.trackTimeOnPage.bind(this),this.boundVisibilityHandler=()=>{"hidden"===document.visibilityState?this.trackTimeOnPage():this.engagementStartTime=Date.now()},["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.addEventListener(e,this.boundMarkEngaged,{passive:!0})}),window.addEventListener("beforeunload",this.boundTrackTimeOnPage),document.addEventListener("visibilitychange",this.boundVisibilityHandler),this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundMarkEngaged&&"undefined"!=typeof document&&["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.removeEventListener(e,this.boundMarkEngaged)}),this.boundTrackTimeOnPage&&"undefined"!=typeof window&&window.removeEventListener("beforeunload",this.boundTrackTimeOnPage),this.boundVisibilityHandler&&"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.engagementTimeout&&clearTimeout(this.engagementTimeout),super.destroy()}resetForNavigation(){this.pageLoadTime=Date.now(),this.engagementStartTime=Date.now(),this.isEngaged=!1,this.engagementTimeout&&(clearTimeout(this.engagementTimeout),this.engagementTimeout=null)}markEngaged(){this.isEngaged||(this.isEngaged=!0,this.track("engagement","User Engaged",{timeToEngage:Date.now()-this.pageLoadTime})),this.engagementTimeout&&clearTimeout(this.engagementTimeout),this.engagementTimeout=setTimeout(()=>{this.isEngaged=!1},3e4)}trackTimeOnPage(){const e=Math.floor((Date.now()-this.engagementStartTime)/1e3);e>0&&this.track("time_on_page","Time Spent",{seconds:e,engaged:this.isEngaged})}}class H extends x{constructor(){super(...arguments),this.name="downloads",this.trackedDownloads=new Set,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0)),"undefined"!=typeof window&&(this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.trackedDownloads.clear()}handleClick(e){const t=e.target.closest("a");if(!t||!t.href)return;const i=t.href;(function(e){const t=e.toLowerCase();return d.some(e=>t.includes(e))})(i)&&(this.trackedDownloads.has(i)||(this.trackedDownloads.add(i),this.track("download","File Download",{url:i,filename:I(i),fileType:T(i),linkText:S(t,100)})))}}class A extends x{constructor(){super(...arguments),this.name="exitIntent",this.exitIntentShown=!1,this.pageLoadTime=0,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),"undefined"!=typeof navigator&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||("undefined"!=typeof document&&(this.boundHandler=this.handleMouseLeave.bind(this),document.addEventListener("mouseleave",this.boundHandler)),"undefined"!=typeof window&&(this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler)))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("mouseleave",this.boundHandler),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.exitIntentShown=!1,this.pageLoadTime=Date.now()}handleMouseLeave(e){e.clientY>0||this.exitIntentShown||(this.exitIntentShown=!0,this.track("exit_intent","Exit Intent Detected",{timeOnPage:Date.now()-this.pageLoadTime}))}}class N extends x{constructor(){super(...arguments),this.name="errors",this.boundErrorHandler=null,this.boundRejectionHandler=null}init(e){super.init(e),"undefined"!=typeof window&&(this.boundErrorHandler=this.handleError.bind(this),this.boundRejectionHandler=this.handleRejection.bind(this),window.addEventListener("error",this.boundErrorHandler),window.addEventListener("unhandledrejection",this.boundRejectionHandler))}destroy(){"undefined"!=typeof window&&(this.boundErrorHandler&&window.removeEventListener("error",this.boundErrorHandler),this.boundRejectionHandler&&window.removeEventListener("unhandledrejection",this.boundRejectionHandler)),super.destroy()}handleError(e){this.track("error","JavaScript Error",{message:e.message,filename:e.filename,line:e.lineno,column:e.colno,stack:e.error?.stack?.substring(0,500)})}handleRejection(e){this.track("error","Unhandled Promise Rejection",{reason:String(e.reason).substring(0,200)})}}class D extends x{constructor(){super(...arguments),this.name="performance",this.boundLoadHandler=null,this.observers=[],this.boundClsVisibilityHandler=null}init(e){super.init(e),"undefined"!=typeof window&&(this.boundLoadHandler=()=>{setTimeout(()=>this.trackPerformance(),100)},window.addEventListener("load",this.boundLoadHandler))}destroy(){this.boundLoadHandler&&"undefined"!=typeof window&&window.removeEventListener("load",this.boundLoadHandler);for(const e of this.observers)e.disconnect();this.observers=[],this.boundClsVisibilityHandler&&"undefined"!=typeof window&&window.removeEventListener("visibilitychange",this.boundClsVisibilityHandler),super.destroy()}trackPerformance(){if("undefined"==typeof performance)return;const e=performance.getEntriesByType("navigation");if(e.length>0){const t=e[0],i=Math.round(t.loadEventEnd-t.startTime),n=Math.round(t.domContentLoadedEventEnd-t.startTime),s=Math.round(t.responseStart-t.requestStart),r=Math.round(t.domInteractive-t.startTime);this.track("performance","Page Performance",{loadTime:i,domReady:n,ttfb:s,domInteractive:r,dns:Math.round(t.domainLookupEnd-t.domainLookupStart),connection:Math.round(t.connectEnd-t.connectStart),transferSize:t.transferSize})}else{const e=performance.timing;if(!e)return;const t=e.loadEventEnd-e.navigationStart,i=e.domContentLoadedEventEnd-e.navigationStart,n=e.responseStart-e.navigationStart,s=e.domInteractive-e.navigationStart;this.track("performance","Page Performance",{loadTime:t,domReady:i,ttfb:n,domInteractive:s})}this.trackWebVitals()}trackWebVitals(){if("PerformanceObserver"in window){try{const e=new PerformanceObserver(e=>{const t=e.getEntries(),i=t[t.length-1];i&&this.track("performance","Web Vital - LCP",{metric:"LCP",value:Math.round(i.startTime)})});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}try{const e=new PerformanceObserver(e=>{const t=e.getEntries()[0];t&&this.track("performance","Web Vital - FID",{metric:"FID",value:Math.round(t.processingStart-t.startTime)})});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}try{let e=0;const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{t.hadRecentInput||(e+=t.value||0)})});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t),this.boundClsVisibilityHandler=()=>{"hidden"===document.visibilityState&&e>0&&this.track("performance","Web Vital - CLS",{metric:"CLS",value:Math.round(1e3*e)/1e3})},window.addEventListener("visibilitychange",this.boundClsVisibilityHandler,{once:!0})}catch{}}}}class O extends x{constructor(){super(...arguments),this.name="popupForms",this.forms=[],this.shownForms=new Set,this.scrollHandler=null,this.exitHandler=null,this.delayTimers=[],this.clickTriggerListeners=[]}async init(e){super.init(e),"undefined"!=typeof window&&(this.loadShownForms(),await this.fetchForms(),this.setupTriggers())}destroy(){this.removeTriggers();for(const e of this.delayTimers)clearTimeout(e);this.delayTimers=[];for(const{element:e,handler:t}of this.clickTriggerListeners)e.removeEventListener("click",t);this.clickTriggerListeners=[],super.destroy()}loadShownForms(){try{const e=localStorage.getItem("clianta_shown_forms");if(e){const t=JSON.parse(e);this.shownForms=new Set(t.forms||[])}}catch(e){}}saveShownForms(){try{localStorage.setItem("clianta_shown_forms",JSON.stringify({forms:Array.from(this.shownForms),timestamp:Date.now()}))}catch(e){}}async fetchForms(){if(!this.tracker)return;const e=this.tracker.getConfig(),t=this.tracker.getWorkspaceId(),i=e.apiEndpoint||"http://localhost:5000";try{const e=encodeURIComponent(window.location.href),n=await fetch(`${i}/api/public/lead-forms/${t}?url=${e}`);if(!n.ok)return;const s=await n.json();s.success&&Array.isArray(s.data)&&(this.forms=s.data.filter(e=>this.shouldShowForm(e)))}catch(e){console.error("[Clianta] Failed to fetch forms:",e)}}shouldShowForm(e){if("once_per_visitor"===e.showFrequency){if(this.shownForms.has(e._id))return!1}else if("once_per_session"===e.showFrequency){const t=`clianta_form_${e._id}_shown`;if(sessionStorage.getItem(t))return!1}return!0}setupTriggers(){this.forms.forEach(e=>{switch(e.trigger.type){case"delay":this.delayTimers.push(setTimeout(()=>this.showForm(e),1e3*(e.trigger.value||5)));break;case"scroll":this.setupScrollTrigger(e);break;case"exit_intent":this.setupExitIntentTrigger(e);break;case"click":this.setupClickTrigger(e)}})}setupScrollTrigger(e){const t=e.trigger.value||50;this.scrollHandler=()=>{window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100>=t&&(this.showForm(e),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler))},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}setupExitIntentTrigger(e){this.exitHandler=t=>{t.clientY<=0&&(this.showForm(e),this.exitHandler&&document.removeEventListener("mouseout",this.exitHandler))},document.addEventListener("mouseout",this.exitHandler)}setupClickTrigger(e){if(!e.trigger.selector)return;document.querySelectorAll(e.trigger.selector).forEach(t=>{const i=()=>this.showForm(e);t.addEventListener("click",i),this.clickTriggerListeners.push({element:t,handler:i})})}removeTriggers(){this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.exitHandler&&document.removeEventListener("mouseout",this.exitHandler)}async showForm(e){this.shouldShowForm(e)&&(this.shownForms.add(e._id),this.saveShownForms(),sessionStorage.setItem(`clianta_form_${e._id}_shown`,"true"),await this.trackFormView(e._id),this.renderForm(e))}async trackFormView(e){if(!this.tracker)return;const t=this.tracker.getConfig().apiEndpoint||"http://localhost:5000";try{await fetch(`${t}/api/public/lead-forms/${e}/view`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch(e){}}renderForm(e){const t=document.createElement("div");t.id=`clianta-form-overlay-${e._id}`,t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 999998;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n ";const i=document.createElement("div");i.id=`clianta-form-${e._id}`;const n=e.style||{};i.style.cssText=`\n background: ${n.backgroundColor||"#FFFFFF"};\n border-radius: ${n.borderRadius||12}px;\n padding: 24px;\n max-width: 400px;\n width: 90%;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);\n transform: translateY(20px);\n opacity: 0;\n transition: all 0.3s ease;\n `,this.buildFormDOM(e,i),t.appendChild(i),document.body.appendChild(t),requestAnimationFrame(()=>{t.style.opacity="1",i.style.transform="translateY(0)",i.style.opacity="1"}),this.setupFormEvents(e,t,i)}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}buildFormDOM(e,t){const i=e.style||{},n=i.primaryColor||"#10B981",s=i.textColor||"#18181B",r=document.createElement("button");r.id="clianta-form-close",r.style.cssText="\n position: absolute;\n top: 12px;\n right: 12px;\n background: none;\n border: none;\n font-size: 20px;\n cursor: pointer;\n color: #71717A;\n padding: 4px;\n ",r.textContent="×",t.appendChild(r);const a=document.createElement("h2");a.style.cssText=`font-size: 20px; font-weight: 700; margin-bottom: 8px; color: ${this.escapeHTML(s)};`,a.textContent=e.headline||"Stay in touch",t.appendChild(a);const o=document.createElement("p");o.style.cssText="font-size: 14px; color: #71717A; margin-bottom: 16px;",o.textContent=e.subheadline||"Get the latest updates",t.appendChild(o);const c=document.createElement("form");c.id="clianta-form-element",e.fields.forEach(e=>{const t=document.createElement("div");if(t.style.marginBottom="12px","checkbox"===e.type){const i=document.createElement("label");i.style.cssText=`display: flex; align-items: center; gap: 8px; font-size: 14px; color: ${this.escapeHTML(s)}; cursor: pointer;`;const n=document.createElement("input");n.type="checkbox",n.name=e.name,e.required&&(n.required=!0),n.style.cssText="width: 16px; height: 16px;",i.appendChild(n);const r=document.createTextNode(e.label+" ");if(i.appendChild(r),e.required){const e=document.createElement("span");e.style.color="#EF4444",e.textContent="*",i.appendChild(e)}t.appendChild(i)}else{const i=document.createElement("label");if(i.style.cssText=`display: block; font-size: 14px; font-weight: 500; margin-bottom: 4px; color: ${this.escapeHTML(s)};`,i.textContent=e.label+" ",e.required){const e=document.createElement("span");e.style.color="#EF4444",e.textContent="*",i.appendChild(e)}if(t.appendChild(i),"textarea"===e.type){const i=document.createElement("textarea");i.name=e.name,e.placeholder&&(i.placeholder=e.placeholder),e.required&&(i.required=!0),i.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; resize: vertical; min-height: 80px; box-sizing: border-box;",t.appendChild(i)}else if("select"===e.type){const i=document.createElement("select");if(i.name=e.name,e.required&&(i.required=!0),i.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box; background: white; cursor: pointer;",e.placeholder){const t=document.createElement("option");t.value="",t.textContent=e.placeholder,t.disabled=!0,t.selected=!0,i.appendChild(t)}e.options&&Array.isArray(e.options)&&e.options.forEach(e=>{const t=document.createElement("option");"string"==typeof e?(t.value=e,t.textContent=e):(t.value=e.value,t.textContent=e.label),i.appendChild(t)}),t.appendChild(i)}else{const i=document.createElement("input");i.type=e.type,i.name=e.name,e.placeholder&&(i.placeholder=e.placeholder),e.required&&(i.required=!0),i.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box;",t.appendChild(i)}}c.appendChild(t)});const d=document.createElement("button");d.type="submit",d.style.cssText=`\n width: 100%;\n padding: 10px 16px;\n background: ${this.escapeHTML(n)};\n color: white;\n border: none;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n margin-top: 8px;\n `,d.textContent=e.submitButtonText||"Subscribe",c.appendChild(d),t.appendChild(c)}setupFormEvents(e,t,i){const n=i.querySelector("#clianta-form-close");n&&n.addEventListener("click",()=>this.closeForm(e._id,t,i)),t.addEventListener("click",n=>{n.target===t&&this.closeForm(e._id,t,i)});const s=i.querySelector("#clianta-form-element");s&&s.addEventListener("submit",async t=>{t.preventDefault(),await this.handleSubmit(e,s,i)})}closeForm(e,t,i){i.style.transform="translateY(20px)",i.style.opacity="0",t.style.opacity="0",setTimeout(()=>{t.remove()},300)}async handleSubmit(e,t,i){if(!this.tracker)return;const n=this.tracker.getConfig().apiEndpoint||"http://localhost:5000",s=this.tracker.getVisitorId(),r=new FormData(t),a={};r.forEach((e,t)=>{a[t]=e});const o=t.querySelector('button[type="submit"]');o&&(o.disabled=!0,o.textContent="Submitting...");try{const t=await fetch(`${n}/api/public/lead-forms/${e._id}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:s,data:a,url:window.location.href})});if((await t.json()).success){i.innerHTML="";const t=document.createElement("div");t.style.cssText="text-align: center; padding: 20px;";const n=document.createElement("div");n.style.cssText="width: 48px; height: 48px; background: #10B981; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center;";const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("width","24"),s.setAttribute("height","24"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","white"),s.setAttribute("stroke-width","2");const r=document.createElementNS("http://www.w3.org/2000/svg","polyline");r.setAttribute("points","20 6 9 17 4 12"),s.appendChild(r),n.appendChild(s);const o=document.createElement("p");if(o.style.cssText="font-size: 16px; font-weight: 500; color: #18181B;",o.textContent=e.successMessage||"Thank you!",t.appendChild(n),t.appendChild(o),i.appendChild(t),a.email&&this.tracker?.identify(a.email,a),e.redirectUrl)try{const t=new URL(e.redirectUrl,window.location.origin),i=t.origin===window.location.origin,n="https:"===t.protocol||"http:"===t.protocol;i||n?setTimeout(()=>{window.location.href=t.href},1500):console.warn("[Clianta] Blocked unsafe redirect URL:",e.redirectUrl)}catch{console.warn("[Clianta] Invalid redirect URL:",e.redirectUrl)}setTimeout(()=>{const t=document.getElementById(`clianta-form-overlay-${e._id}`);t&&this.closeForm(e._id,t,i)},2e3)}}catch(t){console.error("[Clianta] Form submit error:",t),o&&(o.disabled=!1,o.textContent=e.submitButtonText||"Subscribe")}}}function F(e){switch(e){case"pageView":return new C;case"scroll":return new $;case"forms":return new L;case"clicks":return new P;case"engagement":return new q;case"downloads":return new H;case"exitIntent":return new A;case"errors":return new N;case"performance":return new D;case"popupForms":return new O;default:throw new Error(`Unknown plugin: ${e}`)}}function _(e){try{if("undefined"==typeof localStorage)return!1;const t={state:e,timestamp:Date.now(),version:1};return localStorage.setItem(a,JSON.stringify(t)),!0}catch{return!1}}function R(){try{if("undefined"==typeof localStorage)return null;const e=localStorage.getItem(a);if(!e)return null;const t=JSON.parse(e);return 1!==t.version?(M(),null):t}catch{return null}}function M(){try{return"undefined"!=typeof localStorage&&(localStorage.removeItem(a),!0)}catch{return!1}}class V{constructor(e={}){this.eventBuffer=[],this.callbacks=[],this.hasExplicitConsent=!1,this.config={defaultConsent:{analytics:!0,marketing:!1,personalization:!1},waitForConsent:!1,storageKey:"mb_consent",...e};const t=R();t?(this.state=t.state,this.hasExplicitConsent=!0,p.debug("Loaded stored consent:",this.state)):(this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,p.debug("Using default consent:",this.state)),e.onConsentChange&&this.callbacks.push(e.onConsentChange)}grant(e){const t={...this.state};this.state={...this.state,...e},this.hasExplicitConsent=!0,_(this.state),p.info("Consent granted:",e),this.notifyChange(t)}revoke(e){const t={...this.state};for(const t of e)this.state[t]=!1;this.hasExplicitConsent=!0,_(this.state),p.info("Consent revoked:",e),this.notifyChange(t)}update(e){const t={...this.state};this.state={...e},this.hasExplicitConsent=!0,_(this.state),p.info("Consent updated:",this.state),this.notifyChange(t)}reset(){const e={...this.state};this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,this.eventBuffer=[],M(),p.info("Consent reset to defaults"),this.notifyChange(e)}getState(){return{...this.state}}hasConsent(e){return!0===this.state[e]}canTrack(){return!(this.config.waitForConsent&&!this.hasExplicitConsent)&&!0===this.state.analytics}hasExplicit(){return this.hasExplicitConsent}hasStored(){return null!==R()}bufferEvent(e){this.eventBuffer.length>=100&&(p.warn("Consent event buffer full, dropping oldest event"),this.eventBuffer.shift()),this.eventBuffer.push(e),p.debug("Event buffered (waiting for consent):",e.eventName)}flushBuffer(){const e=[...this.eventBuffer];return this.eventBuffer=[],e.length>0&&p.debug(`Flushing ${e.length} buffered events`),e}getBufferSize(){return this.eventBuffer.length}onChange(e){return this.callbacks.push(e),()=>{const t=this.callbacks.indexOf(e);t>-1&&this.callbacks.splice(t,1)}}notifyChange(e){for(const t of this.callbacks)try{t(this.state,e)}catch(e){p.error("Consent change callback error:",e)}}}class U{constructor(e,t,i){this.triggers=new Map,this.listeners=new Map,this.apiEndpoint=e,this.workspaceId=t,this.authToken=i}setAuthToken(e){this.authToken=e}async request(e,t={}){const i=`${this.apiEndpoint}${e}`,n={"Content-Type":"application/json",...t.headers||{}};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);try{const e=await fetch(i,{...t,headers:n}),s=await e.json();return e.ok?{success:!0,data:s.data||s,status:e.status}:{success:!1,error:s.message||"Request failed",status:e.status}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Network error",status:0}}}async getTriggers(){return this.request(`/api/workspaces/${this.workspaceId}/triggers`)}async getTrigger(e){return this.request(`/api/workspaces/${this.workspaceId}/triggers/${e}`)}async createTrigger(e){const t=await this.request(`/api/workspaces/${this.workspaceId}/triggers`,{method:"POST",body:JSON.stringify(e)});return t.success&&t.data?._id&&this.triggers.set(t.data._id,t.data),t}async updateTrigger(e,t){const i=await this.request(`/api/workspaces/${this.workspaceId}/triggers/${e}`,{method:"PUT",body:JSON.stringify(t)});return i.success&&i.data?._id&&this.triggers.set(i.data._id,i.data),i}async deleteTrigger(e){const t=await this.request(`/api/workspaces/${this.workspaceId}/triggers/${e}`,{method:"DELETE"});return t.success&&this.triggers.delete(e),t}async activateTrigger(e){return this.updateTrigger(e,{isActive:!0})}async deactivateTrigger(e){return this.updateTrigger(e,{isActive:!1})}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),p.debug(`Event listener registered: ${e}`)}off(e,t){const i=this.listeners.get(e);i&&i.delete(t)}emit(e,t){p.debug(`Event emitted: ${e}`,t);const i=this.listeners.get(e);i&&i.forEach(i=>{try{i(t)}catch(t){p.error(`Error in event listener for ${e}:`,t)}})}evaluateConditions(e,t){return!e||0===e.length||e.every(e=>{const i=e.field.includes(".")?this.getNestedValue(t,e.field):t[e.field],n=e.value;switch(e.operator){case"equals":return i===n;case"not_equals":return i!==n;case"contains":return String(i).includes(String(n));case"greater_than":return Number(i)>Number(n);case"less_than":return Number(i)<Number(n);case"in":return Array.isArray(n)&&n.includes(i);case"not_in":return Array.isArray(n)&&!n.includes(i);default:return!1}})}async executeActions(e,t){p.info(`Executing actions for trigger: ${e.name}`);for(const i of e.actions)try{await this.executeAction(i,t)}catch(e){p.error("Failed to execute action:",e)}}async executeAction(e,t){switch(e.type){case"send_email":await this.executeSendEmail(e,t);break;case"webhook":await this.executeWebhook(e,t);break;case"create_task":await this.executeCreateTask(e,t);break;case"update_contact":await this.executeUpdateContact(e,t);break;default:p.warn("Unknown action type:",e)}}async executeSendEmail(e,t){p.debug("Sending email:",e);const i={to:this.replaceVariables(e.to,t),subject:e.subject?this.replaceVariables(e.subject,t):void 0,body:e.body?this.replaceVariables(e.body,t):void 0,templateId:e.templateId,cc:e.cc,bcc:e.bcc,from:e.from,delayMinutes:e.delayMinutes};await this.request(`/api/workspaces/${this.workspaceId}/emails/send`,{method:"POST",body:JSON.stringify(i)})}async executeWebhook(e,t){p.debug("Calling webhook:",e.url);const i=e.body?this.replaceVariables(e.body,t):JSON.stringify(t);await fetch(e.url,{method:e.method,headers:{"Content-Type":"application/json",...e.headers},body:i})}async executeCreateTask(e,t){p.debug("Creating task:",e.title);const i=e.dueDays?new Date(Date.now()+24*e.dueDays*60*60*1e3).toISOString():void 0;await this.request(`/api/workspaces/${this.workspaceId}/tasks`,{method:"POST",body:JSON.stringify({title:this.replaceVariables(e.title,t),description:e.description?this.replaceVariables(e.description,t):void 0,priority:e.priority,dueDate:i,assignedTo:e.assignedTo,relatedContactId:"string"==typeof t.contactId?t.contactId:void 0})})}async executeUpdateContact(e,t){const i=t.contactId||t._id;i?(p.debug("Updating contact:",i),await this.request(`/api/workspaces/${this.workspaceId}/contacts/${i}`,{method:"PUT",body:JSON.stringify(e.updates)})):p.warn("Cannot update contact: no contactId in data")}replaceVariables(e,t){return e.replace(/\{\{([^}]+)\}\}/g,(e,i)=>{const n=this.getNestedValue(t,i.trim());return void 0!==n?String(n):e})}getNestedValue(e,t){return t.split(".").reduce((e,t)=>null!=e&&"object"==typeof e?e[t]:void 0,e)}extractAvailableFields(e,t="",i=3){if(i<=0)return[];const n=[];for(const s in e){if(!e.hasOwnProperty(s))continue;const r=e[s],a=t?`${t}.${s}`:s;if(n.push(a),null!==r&&"object"==typeof r&&!Array.isArray(r)){const e=this.extractAvailableFields(r,a,i-1);n.push(...e)}}return n}getAvailableFields(e){return this.extractAvailableFields(e)}async createEmailTrigger(e){return this.createTrigger({name:e.name,eventType:e.eventType,conditions:e.conditions,actions:[{type:"send_email",to:e.to,subject:e.subject,body:e.body}],isActive:!0})}async createTaskTrigger(e){return this.createTrigger({name:e.name,eventType:e.eventType,conditions:e.conditions,actions:[{type:"create_task",title:e.taskTitle,description:e.taskDescription,priority:e.priority,dueDays:e.dueDays}],isActive:!0})}async createWebhookTrigger(e){return this.createTrigger({name:e.name,eventType:e.eventType,conditions:e.conditions,actions:[{type:"webhook",url:e.webhookUrl,method:e.method||"POST"}],isActive:!0})}}class z{constructor(e,t,i,n){this.apiEndpoint=e,this.workspaceId=t,this.authToken=i,this.apiKey=n,this.triggers=new U(e,t,i)}setAuthToken(e){this.authToken=e,this.apiKey=void 0,this.triggers.setAuthToken(e)}setApiKey(e){this.apiKey=e,this.authToken=void 0}validateRequired(e,t,i){if(null==t||""===t)throw new Error(`[CRMClient.${i}] ${e} is required`)}async request(e,t={}){const i=`${this.apiEndpoint}${e}`,n={"Content-Type":"application/json",...t.headers||{}};this.apiKey?n["X-Api-Key"]=this.apiKey:this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);try{const e=await fetch(i,{...t,headers:n}),s=await e.json();return e.ok?{success:!0,data:s.data||s,status:e.status}:{success:!1,error:s.message||"Request failed",status:e.status}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Network error",status:0}}}async sendEvent(e){const t=`${this.apiEndpoint}/api/public/events`,i={"Content-Type":"application/json"};this.apiKey?i["X-Api-Key"]=this.apiKey:this.authToken&&(i.Authorization=`Bearer ${this.authToken}`);try{const n=await fetch(t,{method:"POST",headers:i,body:JSON.stringify(e)}),s=await n.json();return n.ok?{success:s.success,contactCreated:s.contactCreated,contactId:s.contactId,event:s.event}:{success:!1,contactCreated:!1,event:e.event,error:s.error||"Request failed"}}catch(t){return{success:!1,contactCreated:!1,event:e.event,error:t instanceof Error?t.message:"Network error"}}}async getContacts(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString()),e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status);const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/contacts${i?`?${i}`:""}`;return this.request(n)}async getContact(e){return this.validateRequired("contactId",e,"getContact"),this.request(`/api/workspaces/${this.workspaceId}/contacts/${e}`)}async createContact(e){return this.request(`/api/workspaces/${this.workspaceId}/contacts`,{method:"POST",body:JSON.stringify(e)})}async updateContact(e,t){return this.validateRequired("contactId",e,"updateContact"),this.request(`/api/workspaces/${this.workspaceId}/contacts/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteContact(e){return this.validateRequired("contactId",e,"deleteContact"),this.request(`/api/workspaces/${this.workspaceId}/contacts/${e}`,{method:"DELETE"})}async getOpportunities(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString()),e?.pipelineId&&t.set("pipelineId",e.pipelineId),e?.stageId&&t.set("stageId",e.stageId);const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/opportunities${i?`?${i}`:""}`;return this.request(n)}async getOpportunity(e){return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${e}`)}async createOpportunity(e){return this.request(`/api/workspaces/${this.workspaceId}/opportunities`,{method:"POST",body:JSON.stringify(e)})}async updateOpportunity(e,t){return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteOpportunity(e){return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${e}`,{method:"DELETE"})}async moveOpportunity(e,t){return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${e}/move`,{method:"POST",body:JSON.stringify({stageId:t})})}async getCompanies(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString()),e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.industry&&t.set("industry",e.industry);const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/companies${i?`?${i}`:""}`;return this.request(n)}async getCompany(e){return this.request(`/api/workspaces/${this.workspaceId}/companies/${e}`)}async createCompany(e){return this.request(`/api/workspaces/${this.workspaceId}/companies`,{method:"POST",body:JSON.stringify(e)})}async updateCompany(e,t){return this.request(`/api/workspaces/${this.workspaceId}/companies/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteCompany(e){return this.request(`/api/workspaces/${this.workspaceId}/companies/${e}`,{method:"DELETE"})}async getCompanyContacts(e,t){const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString());const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/companies/${e}/contacts${n?`?${n}`:""}`;return this.request(s)}async getCompanyDeals(e,t){const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString());const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/companies/${e}/deals${n?`?${n}`:""}`;return this.request(s)}async getPipelines(){return this.request(`/api/workspaces/${this.workspaceId}/pipelines`)}async getPipeline(e){return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${e}`)}async createPipeline(e){return this.request(`/api/workspaces/${this.workspaceId}/pipelines`,{method:"POST",body:JSON.stringify(e)})}async updatePipeline(e,t){return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deletePipeline(e){return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${e}`,{method:"DELETE"})}async getTasks(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString()),e?.status&&t.set("status",e.status),e?.priority&&t.set("priority",e.priority),e?.contactId&&t.set("contactId",e.contactId),e?.companyId&&t.set("companyId",e.companyId),e?.opportunityId&&t.set("opportunityId",e.opportunityId);const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/tasks${i?`?${i}`:""}`;return this.request(n)}async getTask(e){return this.request(`/api/workspaces/${this.workspaceId}/tasks/${e}`)}async createTask(e){return this.request(`/api/workspaces/${this.workspaceId}/tasks`,{method:"POST",body:JSON.stringify(e)})}async updateTask(e,t){return this.request(`/api/workspaces/${this.workspaceId}/tasks/${e}`,{method:"PUT",body:JSON.stringify(t)})}async completeTask(e){return this.request(`/api/workspaces/${this.workspaceId}/tasks/${e}/complete`,{method:"PATCH"})}async deleteTask(e){return this.request(`/api/workspaces/${this.workspaceId}/tasks/${e}`,{method:"DELETE"})}async getContactActivities(e,t){const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString()),t?.type&&i.set("type",t.type);const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/contacts/${e}/activities${n?`?${n}`:""}`;return this.request(s)}async getOpportunityActivities(e,t){const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString()),t?.type&&i.set("type",t.type);const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/opportunities/${e}/activities${n?`?${n}`:""}`;return this.request(s)}async createActivity(e){let t;return t=e.opportunityId?`/api/workspaces/${this.workspaceId}/opportunities/${e.opportunityId}/activities`:e.contactId?`/api/workspaces/${this.workspaceId}/contacts/${e.contactId}/activities`:`/api/workspaces/${this.workspaceId}/activities`,this.request(t,{method:"POST",body:JSON.stringify(e)})}async updateActivity(e,t){return this.request(`/api/workspaces/${this.workspaceId}/activities/${e}`,{method:"PATCH",body:JSON.stringify(t)})}async deleteActivity(e){return this.request(`/api/workspaces/${this.workspaceId}/activities/${e}`,{method:"DELETE"})}async logCall(e){return this.createActivity({type:"call",title:("inbound"===e.direction?"Inbound":"Outbound")+" Call",direction:e.direction,duration:e.duration,outcome:e.outcome,description:e.notes,contactId:e.contactId,opportunityId:e.opportunityId})}async logMeeting(e){return this.createActivity({type:"meeting",title:e.title,duration:e.duration,outcome:e.outcome,description:e.notes,contactId:e.contactId,opportunityId:e.opportunityId})}async addNote(e){return this.createActivity({type:"note",title:"Note",description:e.content,contactId:e.contactId,opportunityId:e.opportunityId})}async getEmailTemplates(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString());const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/email-templates${i?`?${i}`:""}`;return this.request(n)}async getEmailTemplate(e){return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${e}`)}async createEmailTemplate(e){return this.request(`/api/workspaces/${this.workspaceId}/email-templates`,{method:"POST",body:JSON.stringify(e)})}async updateEmailTemplate(e,t){return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteEmailTemplate(e){return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${e}`,{method:"DELETE"})}async sendEmail(e){return this.request(`/api/workspaces/${this.workspaceId}/emails/send`,{method:"POST",body:JSON.stringify(e)})}async getContactByEmail(e){this.validateRequired("email",e,"getContactByEmail");const t=new URLSearchParams({search:e,limit:"1"});return this.request(`/api/workspaces/${this.workspaceId}/contacts?${t.toString()}`)}async getContactActivity(e,t){this.validateRequired("contactId",e,"getContactActivity");const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString()),t?.type&&i.set("type",t.type),t?.startDate&&i.set("startDate",t.startDate),t?.endDate&&i.set("endDate",t.endDate);const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/contacts/${e}/activities${n?`?${n}`:""}`;return this.request(s)}async getContactEngagement(e){return this.validateRequired("contactId",e,"getContactEngagement"),this.request(`/api/workspaces/${this.workspaceId}/contacts/${e}/engagement`)}async getContactTimeline(e,t){this.validateRequired("contactId",e,"getContactTimeline");const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString());const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/contacts/${e}/timeline${n?`?${n}`:""}`;return this.request(s)}async searchContacts(e,t){const i=new URLSearchParams;i.set("search",e),t?.status&&i.set("status",t.status),t?.lifecycleStage&&i.set("lifecycleStage",t.lifecycleStage),t?.source&&i.set("source",t.source),t?.tags&&i.set("tags",t.tags.join(",")),t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString());const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/contacts${n?`?${n}`:""}`;return this.request(s)}async listWebhooks(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString());const i=t.toString();return this.request(`/api/workspaces/${this.workspaceId}/webhooks${i?`?${i}`:""}`)}async createWebhook(e){return this.request(`/api/workspaces/${this.workspaceId}/webhooks`,{method:"POST",body:JSON.stringify(e)})}async deleteWebhook(e){return this.validateRequired("webhookId",e,"deleteWebhook"),this.request(`/api/workspaces/${this.workspaceId}/webhooks/${e}`,{method:"DELETE"})}async getEventTriggers(){return this.triggers.getTriggers()}async createEventTrigger(e){return this.triggers.createTrigger(e)}async updateEventTrigger(e,t){return this.triggers.updateTrigger(e,t)}async deleteEventTrigger(e){return this.triggers.deleteTrigger(e)}}class j{constructor(e,t,i){this.transport=e,this.workspaceId=t,this.visitorId=i}setVisitorId(e){this.visitorId=e}basePath(){return`/api/public/track/visitor/${this.workspaceId}/${this.visitorId}`}async getProfile(){const e=await this.transport.fetchData(`${this.basePath()}/profile`);return e.success&&e.data?(p.debug("Visitor profile fetched:",e.data),e.data):(p.warn("Failed to fetch visitor profile:",e.error),null)}async getActivity(e){const t={};e?.page&&(t.page=e.page.toString()),e?.limit&&(t.limit=e.limit.toString()),e?.eventType&&(t.eventType=e.eventType),e?.startDate&&(t.startDate=e.startDate),e?.endDate&&(t.endDate=e.endDate);const i=await this.transport.fetchData(`${this.basePath()}/activity`,t);return i.success&&i.data?i.data:(p.warn("Failed to fetch visitor activity:",i.error),null)}async getTimeline(){const e=await this.transport.fetchData(`${this.basePath()}/timeline`);return e.success&&e.data?e.data:(p.warn("Failed to fetch visitor timeline:",e.error),null)}async getEngagement(){const e=await this.transport.fetchData(`${this.basePath()}/engagement`);return e.success&&e.data?e.data:(p.warn("Failed to fetch visitor engagement:",e.error),null)}}class B{constructor(e,n={}){if(this.plugins=[],this.isInitialized=!1,this.contactId=null,this.groupId=null,this.pendingIdentify=null,this.eventSchemas=new Map,this.middlewares=[],this.readyCallbacks=[],!e)throw new Error("[Clianta] Workspace ID is required");this.workspaceId=e,this.config=function(e={}){return{...i,...e,consent:{...i.consent,...e.consent}}}(n),p.enabled=this.config.debug,p.info(`Initializing SDK v${t}`,{workspaceId:e}),this.consentManager=new V({...this.config.consent,onConsentChange:(e,t)=>{this.onConsentChange(e,t)}}),this.transport=new g({apiEndpoint:this.config.apiEndpoint}),this.queue=new E(this.transport,{batchSize:this.config.batchSize,flushInterval:this.config.flushInterval}),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),p.debug("IDs created",{visitorId:this.visitorId,sessionId:this.sessionId}),this.visitor=new j(this.transport,this.workspaceId,this.visitorId),!this.config.apiEndpoint.startsWith("http://")||"undefined"==typeof window||window.location.hostname.includes("localhost")||window.location.hostname.includes("127.0.0.1")||p.warn("apiEndpoint uses HTTP — events and visitor data will be sent unencrypted. Use HTTPS in production."),this.config.apiKey&&"undefined"!=typeof window&&p.warn("API key is exposed in client-side code. Use API keys only in server-side (Node.js) environments."),this.initPlugins(),this.isInitialized=!0,p.info("SDK initialized successfully");for(const e of this.readyCallbacks)try{e()}catch(e){p.error("onReady callback error:",e)}this.readyCallbacks=[]}createVisitorId(){if(this.config.consent.anonymousMode&&!this.consentManager.hasExplicit()){const e=n+"_anon";let t=f(e);return t||(t="anon_"+m(),y(e,t)),t}if(this.config.cookielessMode){let e=f(n);return e||(e=m(),y(n,e)),e}return v(this.config.useCookies)}createSessionId(){return function(e){const t=s,i=r;let n=f(t);const a=parseInt(f(i)||"0",10),o=Date.now();return(!n||o-a>e)&&(n=m(),y(t,n)),y(i,o.toString()),n}(this.config.sessionTimeout)}onConsentChange(e,t){if(p.debug("Consent changed:",{from:t,to:e}),e.analytics&&!t.analytics){this.config.consent.anonymousMode&&(this.visitorId=v(this.config.useCookies),p.info("Upgraded from anonymous to persistent visitor ID"));const e=this.consentManager.flushBuffer();for(const t of e)t.visitorId=this.visitorId,this.queue.push(t)}}initPlugins(){const e=this.config.plugins,t=this.config.autoPageView?e:e.filter(e=>"pageView"!==e);for(const e of t)try{const t=F(e),i=t.init(this);i instanceof Promise&&i.catch(t=>{p.error(`Async plugin init failed: ${e}`,t)}),this.plugins.push(t),p.debug(`Plugin loaded: ${e}`)}catch(t){p.error(`Failed to load plugin: ${e}`,t)}}track(e,i,n={}){if(!this.isInitialized)return void p.warn("SDK not initialized, event dropped");const s={workspaceId:this.workspaceId,visitorId:this.visitorId,sessionId:this.sessionId,eventType:e,eventName:i,url:"undefined"!=typeof window?window.location.href:"",referrer:"undefined"!=typeof document&&document.referrer||void 0,properties:{...n,eventId:m(),websiteDomain:"undefined"!=typeof window?window.location.hostname:void 0},device:"undefined"==typeof window||"undefined"==typeof navigator?{userAgent:"unknown",screen:"unknown",language:"unknown",timezone:"unknown"}:{userAgent:navigator.userAgent,screen:`${screen.width}x${screen.height}`,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"unknown"},...k(),timestamp:(new Date).toISOString(),sdkVersion:t};if(this.contactId&&(s.contactId=this.contactId),this.groupId&&(s.groupId=this.groupId),this.validateEventSchema(e,n),!this.consentManager.canTrack())return this.config.consent.waitForConsent?void this.consentManager.bufferEvent(s):void p.debug("Event dropped (no consent):",i);this.runMiddleware(s,()=>{this.queue.push(s),p.debug("Event tracked:",i,n)})}page(e,t={}){const i=e||("undefined"!=typeof document?document.title:"Page View");this.track("page_view",i,{...t,path:"undefined"!=typeof window?window.location.pathname:""})}async identify(e,t={}){if(!e)return p.warn("Email is required for identification"),null;if(!function(e){return!("string"!=typeof e||!e)&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}(e))return p.warn("Invalid email format, identification skipped:",e),null;p.info("Identifying visitor:",e);const i=await this.transport.sendIdentify({workspaceId:this.workspaceId,visitorId:this.visitorId,email:e,properties:t});return i.success?(p.info("Visitor identified successfully, contactId:",i.contactId),this.contactId=i.contactId??null,this.pendingIdentify=null,this.contactId):(p.error("Failed to identify visitor:",i.error),this.pendingIdentify={email:e,traits:t},null)}async sendEvent(e){const t=this.config.apiKey;if(!t)return p.error("sendEvent() requires an apiKey in the SDK config"),{success:!1,contactCreated:!1,event:e.event,error:"No API key configured"};return new z(this.config.apiEndpoint,this.workspaceId,void 0,t).sendEvent(e)}async getVisitorProfile(){return this.isInitialized?this.visitor.getProfile():(p.warn("SDK not initialized"),null)}async getVisitorActivity(e){return this.isInitialized?this.visitor.getActivity(e):(p.warn("SDK not initialized"),null)}async getVisitorTimeline(){return this.isInitialized?this.visitor.getTimeline():(p.warn("SDK not initialized"),null)}async getVisitorEngagement(){return this.isInitialized?this.visitor.getEngagement():(p.warn("SDK not initialized"),null)}async retryPendingIdentify(){if(!this.pendingIdentify)return;const{email:e,traits:t}=this.pendingIdentify;this.pendingIdentify=null,await this.identify(e,t)}consent(e){this.consentManager.update(e)}getConsentState(){return this.consentManager.getState()}debug(e){p.enabled=e,p.info("Debug mode "+(e?"enabled":"disabled"))}group(e,t={}){e?(this.groupId=e,p.info("Visitor grouped:",e),this.track("group","Group Identified",{groupId:e,...t})):p.warn("groupId is required for group()")}async alias(e,t){if(!e)return p.warn("newId is required for alias()"),!1;const i=t||this.visitorId;p.info("Aliasing visitor:",{from:i,to:e});try{const t=`${this.config.apiEndpoint}/api/public/track/alias`,n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:this.workspaceId,previousId:i,newId:e})});return n.ok?(p.info("Alias successful"),!0):(p.error("Alias failed:",n.status),!1)}catch(e){return p.error("Alias request failed:",e),!1}}screen(e,t={}){this.track("screen_view",e,{...t,screenName:e})}use(e){this.middlewares.push(e),p.debug("Middleware registered")}runMiddleware(e,t){if(0===this.middlewares.length)return void t();let i=0;const n=this.middlewares,s=()=>{if(i++,i<n.length)try{n[i](e,s)}catch(e){p.error("Middleware error:",e),t()}else t()};try{n[0](e,s)}catch(e){p.error("Middleware error:",e),t()}}onReady(e){if(this.isInitialized)try{e()}catch(e){p.error("onReady callback error:",e)}else this.readyCallbacks.push(e)}isReady(){return this.isInitialized}registerEventSchema(e,t){this.eventSchemas.set(e,t),p.debug("Event schema registered:",e)}validateEventSchema(e,t){if(!this.config.debug)return;const i=this.eventSchemas.get(e);if(i)for(const[n,s]of Object.entries(i)){const i=t[n];if(void 0===i){p.warn(`[Schema] Missing property "${n}" for event type "${e}"`);continue}let r=!1;switch(s){case"string":r="string"==typeof i;break;case"number":r="number"==typeof i;break;case"boolean":r="boolean"==typeof i;break;case"object":r="object"==typeof i&&!Array.isArray(i);break;case"array":r=Array.isArray(i)}r||p.warn(`[Schema] Property "${n}" for event "${e}" expected ${s}, got ${typeof i}`)}}getVisitorId(){return this.visitorId}getSessionId(){return this.sessionId}getWorkspaceId(){return this.workspaceId}getConfig(){return{...this.config}}async flush(){await this.retryPendingIdentify(),await this.queue.flush()}reset(){p.info("Resetting visitor data"),b(this.config.useCookies),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),this.contactId=null,this.pendingIdentify=null,this.queue.clear()}deleteData(){if(p.info("Deleting all user data (GDPR request)"),this.queue.clear(),this.consentManager.reset(),b(this.config.useCookies),"undefined"!=typeof sessionStorage)try{sessionStorage.removeItem(n),sessionStorage.removeItem(n+"_anon"),sessionStorage.removeItem(s),sessionStorage.removeItem(r)}catch{}if("undefined"!=typeof localStorage)try{localStorage.removeItem(n),localStorage.removeItem(a),localStorage.removeItem(o)}catch{}this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),p.info("All user data deleted")}async createContact(e){return this.publicCrmRequest("/api/public/crm/contacts","POST",{workspaceId:this.workspaceId,...e})}async updateContact(e,t){return this.publicCrmRequest(`/api/public/crm/contacts/${e}`,"PUT",{workspaceId:this.workspaceId,...t})}async submitForm(e,t){const i={...t,metadata:{...t.metadata,visitorId:this.visitorId,sessionId:this.sessionId,pageUrl:"undefined"!=typeof window?window.location.href:void 0,referrer:"undefined"!=typeof document&&document.referrer||void 0}};return this.publicCrmRequest(`/api/public/crm/forms/${e}/submit`,"POST",i)}async logActivity(e){return this.publicCrmRequest("/api/public/crm/activities","POST",{workspaceId:this.workspaceId,...e})}async createOpportunity(e){return this.publicCrmRequest("/api/public/crm/opportunities","POST",{workspaceId:this.workspaceId,...e})}async publicCrmRequest(e,t,i){const n=`${this.config.apiEndpoint}${e}`;try{const s=await fetch(n,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),r=await s.json().catch(()=>({}));return s.ok?(p.debug(`Public CRM ${t} ${e} succeeded`),{success:!0,data:r.data??r,status:s.status}):(p.error(`Public CRM ${t} ${e} failed (${s.status}):`,r.message),{success:!1,error:r.message,status:s.status})}catch(i){return p.error(`Public CRM ${t} ${e} error:`,i),{success:!1,error:i.message}}}async destroy(){p.info("Destroying tracker"),await this.queue.flush();for(const e of this.plugins)e.destroy&&e.destroy();this.plugins=[],this.queue.destroy(),this.isInitialized=!1}}let J=null;function K(e,t){return J&&J.getWorkspaceId()===e||(J&&J.destroy(),J=new B(e,t)),J}"undefined"!=typeof window&&(window.clianta=K,window.Clianta={clianta:K,Tracker:B,CRMClient:z,ConsentManager:V,EventTriggersManager:U}),e.CRMClient=z,e.ConsentManager=V,e.EventTriggersManager=U,e.SDK_VERSION=t,e.Tracker=B,e.clianta=K,e.default=K,Object.defineProperty(e,"__esModule",{value:!0})});
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Clianta={})}(this,function(e){"use strict";const t="1.6.2",n={projectId:"",apiEndpoint:"undefined"!=typeof process&&process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT?process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT:"undefined"!=typeof process&&process.env?.VITE_CLIANTA_API_ENDPOINT?process.env.VITE_CLIANTA_API_ENDPOINT:"undefined"!=typeof process&&process.env?.REACT_APP_CLIANTA_API_ENDPOINT?process.env.REACT_APP_CLIANTA_API_ENDPOINT:"undefined"!=typeof process&&process.env?.CLIANTA_API_ENDPOINT?process.env.CLIANTA_API_ENDPOINT:"http://localhost:5000",debug:!1,autoPageView:!0,plugins:["pageView","forms","scroll","clicks","engagement","downloads","exitIntent","errors","performance"],sessionTimeout:18e5,batchSize:10,flushInterval:5e3,consent:{defaultConsent:{analytics:!0,marketing:!1,personalization:!1},waitForConsent:!1,storageKey:"mb_consent",anonymousMode:!1},cookieDomain:"",useCookies:!1,cookielessMode:!1,persistMode:"session"},i="mb_vid",s="mb_sid",o="mb_st",r="mb_consent",a="mb_queue",d=[25,50,75,100],c=[".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".rar",".tar",".gz",".7z",".csv",".txt",".json",".xml",".mp3",".mp4",".wav",".avi",".mov"];const l="[Clianta]",u={debug:"color: #6b7280; font-weight: normal;",info:"color: #3b82f6; font-weight: normal;",warn:"color: #f59e0b; font-weight: bold;",error:"color: #ef4444; font-weight: bold;"},h={debug:0,info:1,warn:2,error:3};const p=function(e=!1){let t="debug",n=e;const i=e=>!!n&&h[e]>=h[t],s=(e,t)=>"undefined"!=typeof console&&"undefined"!=typeof window?[`%c${l}`,u[e],...t]:[`${l} [${e.toUpperCase()}]`,...t];return{get enabled(){return n},set enabled(e){n=e},debug(...e){i("debug")&&"undefined"!=typeof console&&console.log(...s("debug",e))},info(...e){i("info")&&"undefined"!=typeof console&&console.info(...s("info",e))},warn(...e){i("warn")&&"undefined"!=typeof console&&console.warn(...s("warn",e))},error(...e){i("error")&&"undefined"!=typeof console&&console.error(...s("error",e))},setLevel(e){t=e}}}(!1);class f{constructor(e){this.config={apiEndpoint:e.apiEndpoint,maxRetries:e.maxRetries??3,retryDelay:e.retryDelay??1e3,timeout:e.timeout??1e4}}async sendEvents(e){const t=`${this.config.apiEndpoint}/api/public/track/event`,n=JSON.stringify({events:e});return this.send(t,n)}async sendIdentify(e){const t=`${this.config.apiEndpoint}/api/public/track/identify`;try{const n=await this.fetchWithTimeout(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}),i=await n.json().catch(()=>({}));return n.ok?(p.debug("Identify successful, contactId:",i.contactId),{success:!0,status:n.status,contactId:i.contactId??void 0}):(n.status>=500?p.warn(`Identify server error (${n.status})`):p.error(`Identify failed with status ${n.status}:`,i.message),{success:!1,status:n.status})}catch(e){return p.error("Identify request failed:",e),{success:!1,error:e}}}sendBeacon(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return p.warn("sendBeacon not available, events may be lost"),!1;const t=`${this.config.apiEndpoint}/api/public/track/event`,n=JSON.stringify({events:e}),i=new Blob([n],{type:"application/json"});try{const n=navigator.sendBeacon(t,i);return n?p.debug(`Beacon sent ${e.length} events`):p.warn("sendBeacon returned false"),n}catch(e){return p.error("sendBeacon error:",e),!1}}async fetchData(e,t){const n=new URL(`${this.config.apiEndpoint}${e}`);t&&Object.entries(t).forEach(([e,t])=>{null!=t&&n.searchParams.set(e,t)});try{const t=await this.fetchWithTimeout(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const n=await t.json();return p.debug("Fetch successful:",e),{success:!0,data:n.data??n,status:t.status}}return p.error(`Fetch failed with status ${t.status}`),{success:!1,status:t.status}}catch(e){return p.error("Fetch request failed:",e),{success:!1,error:e}}}async send(e,t,n=1){try{const i=await this.fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0});return i.ok?(p.debug("Request successful:",e),{success:!0,status:i.status}):i.status>=500&&n<this.config.maxRetries?(p.warn(`Server error (${i.status}), retrying...`),await this.delay(this.config.retryDelay*n),this.send(e,t,n+1)):(p.error(`Request failed with status ${i.status}`),{success:!1,status:i.status})}catch(i){return n<this.config.maxRetries?(p.warn(`Network error, retrying (${n}/${this.config.maxRetries})...`),await this.delay(this.config.retryDelay*n),this.send(e,t,n+1)):(p.error("Request failed after retries:",i),{success:!1,error:i})}}async fetchWithTimeout(e,t){const n=new AbortController,i=setTimeout(()=>n.abort(),this.config.timeout);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}delay(e){return new Promise(t=>setTimeout(t,e))}}function m(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function g(e){try{if("undefined"!=typeof sessionStorage)return sessionStorage.getItem(e)}catch{}return null}function w(e,t){try{if("undefined"!=typeof sessionStorage)return sessionStorage.setItem(e,t),!0}catch{}return!1}function y(e,t,n){if("undefined"==typeof document)return null;if(void 0===t){const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?t[2]:null}let i="";if(n){const e=new Date;e.setTime(e.getTime()+24*n*60*60*1e3),i="; expires="+e.toUTCString()}const s="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";return document.cookie=e+"="+t+i+"; path=/; SameSite=Lax"+s,t}function v(e=!1){const t=i;let n=null;return n=e?y(t):function(e){try{if("undefined"!=typeof localStorage)return localStorage.getItem(e)}catch{}return null}(t),n||(n=m(),e?y(t,n,365):function(e,t){try{if("undefined"!=typeof localStorage)return localStorage.setItem(e,t),!0}catch{}}(t,n)),n}function b(e=!1){const t=i;if(e)y(t,"",-1);else try{localStorage.removeItem(t)}catch{}try{sessionStorage.removeItem(s),sessionStorage.removeItem(o)}catch{}}function E(){if("undefined"==typeof window)return{};try{const e=new URLSearchParams(window.location.search);return{utmSource:e.get("utm_source")||void 0,utmMedium:e.get("utm_medium")||void 0,utmCampaign:e.get("utm_campaign")||void 0,utmTerm:e.get("utm_term")||void 0,utmContent:e.get("utm_content")||void 0}}catch{return{}}}function k(e){try{return e.split("/").pop()?.split("?")[0]||"unknown"}catch{return"unknown"}}function x(e){const t=k(e).split(".");return t.length>1&&t.pop()||"unknown"}function I(e,t=100){return(e.innerText||e.textContent||e.value||"").trim().substring(0,t)}class T{constructor(e,t={}){this.queue=[],this.flushTimer=null,this.isFlushing=!1,this.eventTimestamps=[],this.boundBeforeUnload=null,this.boundVisibilityChange=null,this.boundPageHide=null,this.transport=e,this.config={batchSize:t.batchSize??10,flushInterval:t.flushInterval??5e3,maxQueueSize:t.maxQueueSize??1e3,storageKey:t.storageKey??a},this.persistMode=t.persistMode||"session",this.restoreQueue(),this.startFlushTimer(),this.setupUnloadHandlers()}push(e){this.checkRateLimit()?(this.queue.length>=this.config.maxQueueSize&&(p.warn("Queue full, dropping oldest event"),this.queue.shift()),this.queue.push(e),p.debug("Event queued:",e.eventName,`(${this.queue.length} in queue)`),this.queue.length>=this.config.batchSize&&this.flush()):p.warn("Rate limit exceeded, event dropped:",e.eventName)}checkRateLimit(){const e=Date.now();return this.eventTimestamps=this.eventTimestamps.filter(t=>e-t<6e4),!(this.eventTimestamps.length>=100)&&(this.eventTimestamps.push(e),!0)}async flush(){if(this.isFlushing||0===this.queue.length)return;this.isFlushing=!0;const e=this.queue.length,t=this.queue.splice(0,e);try{p.debug(`Flushing ${t.length} events`),this.persistQueue([]);(await this.transport.sendEvents(t)).success?p.debug("Flush successful"):(p.warn("Flush failed, re-queuing events"),this.queue.unshift(...t),this.persistQueue(this.queue))}catch(e){p.error("Flush error:",e)}finally{this.isFlushing=!1}}flushSync(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.queue.length);p.debug(`Sync flushing ${e.length} events via beacon`);this.transport.sendBeacon(e)||(this.queue.unshift(...e),this.persistQueue(this.queue))}get length(){return this.queue.length}clear(){if(this.queue=[],this.persistQueue([]),"local"===this.persistMode&&"undefined"!=typeof localStorage)try{localStorage.removeItem(this.config.storageKey)}catch{}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"undefined"!=typeof window&&(this.boundBeforeUnload&&window.removeEventListener("beforeunload",this.boundBeforeUnload),this.boundVisibilityChange&&window.removeEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide&&window.removeEventListener("pagehide",this.boundPageHide))}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupUnloadHandlers(){"undefined"!=typeof window&&(this.boundBeforeUnload=()=>this.flushSync(),window.addEventListener("beforeunload",this.boundBeforeUnload),this.boundVisibilityChange=()=>{"hidden"===document.visibilityState&&this.flushSync()},window.addEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide=()=>this.flushSync(),window.addEventListener("pagehide",this.boundPageHide))}persistQueue(e){if("none"!==this.persistMode)try{const t=JSON.stringify(e);if("local"===this.persistMode&&"undefined"!=typeof localStorage)try{localStorage.setItem(this.config.storageKey,t)}catch{w(this.config.storageKey,t)}else w(this.config.storageKey,t)}catch{}}restoreQueue(){try{let e=null;if("local"===this.persistMode&&"undefined"!=typeof localStorage&&(e=localStorage.getItem(this.config.storageKey)),e||(e=g(this.config.storageKey)),e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.queue=t,p.debug(`Restored ${t.length} events from storage`))}}catch{}}}class S{constructor(){this.tracker=null}init(e){this.tracker=e}destroy(){this.tracker=null}track(e,t,n){this.tracker&&this.tracker.track(e,t,n)}}class C extends S{constructor(){super(...arguments),this.name="pageView",this.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=null}init(e){if(super.init(e),this.trackPageView(),"undefined"!=typeof window){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.trackPageView(),window.dispatchEvent(new Event("clianta:navigation"))},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.trackPageView(),window.dispatchEvent(new Event("clianta:navigation"))},this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler)}}destroy(){this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}trackPageView(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.track("page_view","Page Viewed",{title:document.title,path:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer||"direct",viewport:`${window.innerWidth}x${window.innerHeight}`})}}class H extends S{constructor(){super(...arguments),this.name="scroll",this.milestonesReached=new Set,this.maxScrollDepth=0,this.pageLoadTime=0,this.scrollTimeout=null,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),"undefined"!=typeof window&&(this.boundHandler=this.handleScroll.bind(this),window.addEventListener("scroll",this.boundHandler,{passive:!0}),this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundHandler&&"undefined"!=typeof window&&window.removeEventListener("scroll",this.boundHandler),this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.milestonesReached.clear(),this.maxScrollDepth=0,this.pageLoadTime=Date.now()}handleScroll(){this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(()=>this.trackScrollDepth(),150)}trackScrollDepth(){if("undefined"==typeof window||"undefined"==typeof document)return;const e=window.innerHeight,t=document.documentElement.scrollHeight,n=window.pageYOffset||document.documentElement.scrollTop,i=t-e;if(i<=0)return;const s=Math.floor(n/i*100),o=Math.max(0,Math.min(100,s));o>this.maxScrollDepth&&(this.maxScrollDepth=o);for(const e of d)o>=e&&!this.milestonesReached.has(e)&&(this.milestonesReached.add(e),this.track("scroll_depth",`Scrolled ${e}%`,{depth:e,maxDepth:this.maxScrollDepth,timeToReach:Date.now()-this.pageLoadTime}))}}class L extends S{constructor(){super(...arguments),this.name="forms",this.trackedForms=new WeakSet,this.formInteractions=new Set,this.observer=null,this.listeners=[]}init(e){super.init(e),"undefined"!=typeof document&&(this.trackAllForms(),"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(()=>this.trackAllForms()),this.observer.observe(document.body,{childList:!0,subtree:!0})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null);for(const{element:e,event:t,handler:n}of this.listeners)e.removeEventListener(t,n);this.listeners=[],super.destroy()}addListener(e,t,n){e.addEventListener(t,n),this.listeners.push({element:e,event:t,handler:n})}trackAllForms(){document.querySelectorAll("form").forEach(e=>{this.setupFormTracking(e)})}setupFormTracking(e){if(this.trackedForms.has(e))return;this.trackedForms.add(e);const t=e.id||e.name||`form-${Math.random().toString(36).substr(2,9)}`;this.track("form_view","Form Viewed",{formId:t,action:e.action,method:e.method,fieldCount:e.elements.length}),Array.from(e.elements).forEach(e=>{if(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement){if(!e.name||"submit"===e.type||"button"===e.type)return;["focus","blur","change"].forEach(n=>{this.addListener(e,n,()=>{const i=`${t}-${e.name}-${n}`;this.formInteractions.has(i)||(this.formInteractions.add(i),this.track("form_interaction","Form Field Interaction",{formId:t,fieldName:e.name,fieldType:e.type,interactionType:n}))})})}});this.addListener(e,"submit",()=>{this.track("form_submit","Form Submitted",{formId:t,action:e.action,method:e.method}),this.autoIdentify(e)})}autoIdentify(e){const t=e.querySelector('input[type="email"], input[name*="email"]');if(!t?.value||!this.tracker)return;const n=t.value,i={},s=e.querySelector('[name*="first"], [name*="fname"]'),o=e.querySelector('[name*="last"], [name*="lname"]'),r=e.querySelector('[name*="company"], [name*="organization"]'),a=e.querySelector('[type="tel"], [name*="phone"]');s?.value&&(i.firstName=s.value),o?.value&&(i.lastName=o.value),r?.value&&(i.company=r.value),a?.value&&(i.phone=a.value),this.tracker.identify(n,i)}}class F extends S{constructor(){super(...arguments),this.name="clicks",this.boundHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),super.destroy()}handleClick(e){const t=e.target;if(!(t&&(n=t,["BUTTON","A","INPUT"].includes(n.tagName)||n.hasAttribute("data-track-click")||n.classList.contains("track-click"))))return;var n;const i=I(t,100),s=function(e){return{tag:e.tagName?.toLowerCase()||"unknown",id:e.id||"",className:e.className||"",text:I(e,50)}}(t);this.track("button_click","Button Clicked",{buttonText:i,elementType:t.tagName.toLowerCase(),elementId:s.id,elementClass:s.className,href:t.href||void 0,x:Math.round(e.clientX/window.innerWidth*100),y:Math.round(e.clientY/window.innerHeight*100),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight})}}class P extends S{constructor(){super(...arguments),this.name="engagement",this.pageLoadTime=0,this.engagementStartTime=0,this.isEngaged=!1,this.engagementTimeout=null,this.boundMarkEngaged=null,this.boundTrackTimeOnPage=null,this.boundVisibilityHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),this.engagementStartTime=Date.now(),"undefined"!=typeof document&&"undefined"!=typeof window&&(this.boundMarkEngaged=this.markEngaged.bind(this),this.boundTrackTimeOnPage=this.trackTimeOnPage.bind(this),this.boundVisibilityHandler=()=>{"hidden"===document.visibilityState?this.trackTimeOnPage():this.engagementStartTime=Date.now()},["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.addEventListener(e,this.boundMarkEngaged,{passive:!0})}),window.addEventListener("beforeunload",this.boundTrackTimeOnPage),document.addEventListener("visibilitychange",this.boundVisibilityHandler),this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundMarkEngaged&&"undefined"!=typeof document&&["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.removeEventListener(e,this.boundMarkEngaged)}),this.boundTrackTimeOnPage&&"undefined"!=typeof window&&window.removeEventListener("beforeunload",this.boundTrackTimeOnPage),this.boundVisibilityHandler&&"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.engagementTimeout&&clearTimeout(this.engagementTimeout),super.destroy()}resetForNavigation(){this.pageLoadTime=Date.now(),this.engagementStartTime=Date.now(),this.isEngaged=!1,this.engagementTimeout&&(clearTimeout(this.engagementTimeout),this.engagementTimeout=null)}markEngaged(){this.isEngaged||(this.isEngaged=!0,this.track("engagement","User Engaged",{timeToEngage:Date.now()-this.pageLoadTime})),this.engagementTimeout&&clearTimeout(this.engagementTimeout),this.engagementTimeout=setTimeout(()=>{this.isEngaged=!1},3e4)}trackTimeOnPage(){const e=Math.floor((Date.now()-this.engagementStartTime)/1e3);e>0&&this.track("time_on_page","Time Spent",{seconds:e,engaged:this.isEngaged})}}class _ extends S{constructor(){super(...arguments),this.name="downloads",this.trackedDownloads=new Set,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0)),"undefined"!=typeof window&&(this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.trackedDownloads.clear()}handleClick(e){const t=e.target.closest("a");if(!t||!t.href)return;const n=t.href;(function(e){const t=e.toLowerCase();return c.some(e=>t.includes(e))})(n)&&(this.trackedDownloads.has(n)||(this.trackedDownloads.add(n),this.track("download","File Download",{url:n,filename:k(n),fileType:x(n),linkText:I(t,100)})))}}class M extends S{constructor(){super(...arguments),this.name="exitIntent",this.exitIntentShown=!1,this.pageLoadTime=0,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),"undefined"!=typeof navigator&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||("undefined"!=typeof document&&(this.boundHandler=this.handleMouseLeave.bind(this),document.addEventListener("mouseleave",this.boundHandler)),"undefined"!=typeof window&&(this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler)))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("mouseleave",this.boundHandler),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.exitIntentShown=!1,this.pageLoadTime=Date.now()}handleMouseLeave(e){e.clientY>0||this.exitIntentShown||(this.exitIntentShown=!0,this.track("exit_intent","Exit Intent Detected",{timeOnPage:Date.now()-this.pageLoadTime}))}}class A extends S{constructor(){super(...arguments),this.name="errors",this.boundErrorHandler=null,this.boundRejectionHandler=null}init(e){super.init(e),"undefined"!=typeof window&&(this.boundErrorHandler=this.handleError.bind(this),this.boundRejectionHandler=this.handleRejection.bind(this),window.addEventListener("error",this.boundErrorHandler),window.addEventListener("unhandledrejection",this.boundRejectionHandler))}destroy(){"undefined"!=typeof window&&(this.boundErrorHandler&&window.removeEventListener("error",this.boundErrorHandler),this.boundRejectionHandler&&window.removeEventListener("unhandledrejection",this.boundRejectionHandler)),super.destroy()}handleError(e){this.track("error","JavaScript Error",{message:e.message,filename:e.filename,line:e.lineno,column:e.colno,stack:e.error?.stack?.substring(0,500)})}handleRejection(e){this.track("error","Unhandled Promise Rejection",{reason:String(e.reason).substring(0,200)})}}class q extends S{constructor(){super(...arguments),this.name="performance",this.boundLoadHandler=null,this.observers=[],this.boundClsVisibilityHandler=null}init(e){super.init(e),"undefined"!=typeof window&&(this.boundLoadHandler=()=>{setTimeout(()=>this.trackPerformance(),100)},window.addEventListener("load",this.boundLoadHandler))}destroy(){this.boundLoadHandler&&"undefined"!=typeof window&&window.removeEventListener("load",this.boundLoadHandler);for(const e of this.observers)e.disconnect();this.observers=[],this.boundClsVisibilityHandler&&"undefined"!=typeof window&&window.removeEventListener("visibilitychange",this.boundClsVisibilityHandler),super.destroy()}trackPerformance(){if("undefined"==typeof performance)return;const e=performance.getEntriesByType("navigation");if(e.length>0){const t=e[0],n=Math.round(t.loadEventEnd-t.startTime),i=Math.round(t.domContentLoadedEventEnd-t.startTime),s=Math.round(t.responseStart-t.requestStart),o=Math.round(t.domInteractive-t.startTime);this.track("performance","Page Performance",{loadTime:n,domReady:i,ttfb:s,domInteractive:o,dns:Math.round(t.domainLookupEnd-t.domainLookupStart),connection:Math.round(t.connectEnd-t.connectStart),transferSize:t.transferSize})}else{const e=performance.timing;if(!e)return;const t=e.loadEventEnd-e.navigationStart,n=e.domContentLoadedEventEnd-e.navigationStart,i=e.responseStart-e.navigationStart,s=e.domInteractive-e.navigationStart;this.track("performance","Page Performance",{loadTime:t,domReady:n,ttfb:i,domInteractive:s})}this.trackWebVitals()}trackWebVitals(){if("PerformanceObserver"in window){try{const e=new PerformanceObserver(e=>{const t=e.getEntries(),n=t[t.length-1];n&&this.track("performance","Web Vital - LCP",{metric:"LCP",value:Math.round(n.startTime)})});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}try{const e=new PerformanceObserver(e=>{const t=e.getEntries()[0];t&&this.track("performance","Web Vital - FID",{metric:"FID",value:Math.round(t.processingStart-t.startTime)})});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}try{let e=0;const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{t.hadRecentInput||(e+=t.value||0)})});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t),this.boundClsVisibilityHandler=()=>{"hidden"===document.visibilityState&&e>0&&this.track("performance","Web Vital - CLS",{metric:"CLS",value:Math.round(1e3*e)/1e3})},window.addEventListener("visibilitychange",this.boundClsVisibilityHandler,{once:!0})}catch{}}}}class $ extends S{constructor(){super(...arguments),this.name="popupForms",this.forms=[],this.shownForms=new Set,this.scrollHandler=null,this.exitHandler=null,this.delayTimers=[],this.clickTriggerListeners=[]}async init(e){super.init(e),"undefined"!=typeof window&&(this.loadShownForms(),await this.fetchForms(),this.setupTriggers())}destroy(){this.removeTriggers();for(const e of this.delayTimers)clearTimeout(e);this.delayTimers=[];for(const{element:e,handler:t}of this.clickTriggerListeners)e.removeEventListener("click",t);this.clickTriggerListeners=[],super.destroy()}loadShownForms(){try{const e=localStorage.getItem("clianta_shown_forms");if(e){const t=JSON.parse(e);this.shownForms=new Set(t.forms||[])}}catch(e){}}saveShownForms(){try{localStorage.setItem("clianta_shown_forms",JSON.stringify({forms:Array.from(this.shownForms),timestamp:Date.now()}))}catch(e){}}async fetchForms(){if(!this.tracker)return;const e=this.tracker.getConfig(),t=this.tracker.getWorkspaceId(),n=e.apiEndpoint||"http://localhost:5000";try{const e=encodeURIComponent(window.location.href),i=await fetch(`${n}/api/public/lead-forms/${t}?url=${e}`);if(!i.ok)return;const s=await i.json();s.success&&Array.isArray(s.data)&&(this.forms=s.data.filter(e=>this.shouldShowForm(e)))}catch(e){console.error("[Clianta] Failed to fetch forms:",e)}}shouldShowForm(e){if("once_per_visitor"===e.showFrequency){if(this.shownForms.has(e._id))return!1}else if("once_per_session"===e.showFrequency){const t=`clianta_form_${e._id}_shown`;if(sessionStorage.getItem(t))return!1}return!0}setupTriggers(){this.forms.forEach(e=>{switch(e.trigger.type){case"delay":this.delayTimers.push(setTimeout(()=>this.showForm(e),1e3*(e.trigger.value||5)));break;case"scroll":this.setupScrollTrigger(e);break;case"exit_intent":this.setupExitIntentTrigger(e);break;case"click":this.setupClickTrigger(e)}})}setupScrollTrigger(e){const t=e.trigger.value||50;this.scrollHandler=()=>{window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100>=t&&(this.showForm(e),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler))},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}setupExitIntentTrigger(e){this.exitHandler=t=>{t.clientY<=0&&(this.showForm(e),this.exitHandler&&document.removeEventListener("mouseout",this.exitHandler))},document.addEventListener("mouseout",this.exitHandler)}setupClickTrigger(e){if(!e.trigger.selector)return;document.querySelectorAll(e.trigger.selector).forEach(t=>{const n=()=>this.showForm(e);t.addEventListener("click",n),this.clickTriggerListeners.push({element:t,handler:n})})}removeTriggers(){this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.exitHandler&&document.removeEventListener("mouseout",this.exitHandler)}async showForm(e){this.shouldShowForm(e)&&(this.shownForms.add(e._id),this.saveShownForms(),sessionStorage.setItem(`clianta_form_${e._id}_shown`,"true"),await this.trackFormView(e._id),this.renderForm(e))}async trackFormView(e){if(!this.tracker)return;const t=this.tracker.getConfig().apiEndpoint||"http://localhost:5000";try{await fetch(`${t}/api/public/lead-forms/${e}/view`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch(e){}}renderForm(e){const t=document.createElement("div");t.id=`clianta-form-overlay-${e._id}`,t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 999998;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n ";const n=document.createElement("div");n.id=`clianta-form-${e._id}`;const i=e.style||{};n.style.cssText=`\n background: ${i.backgroundColor||"#FFFFFF"};\n border-radius: ${i.borderRadius||12}px;\n padding: 24px;\n max-width: 400px;\n width: 90%;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);\n transform: translateY(20px);\n opacity: 0;\n transition: all 0.3s ease;\n `,this.buildFormDOM(e,n),t.appendChild(n),document.body.appendChild(t),requestAnimationFrame(()=>{t.style.opacity="1",n.style.transform="translateY(0)",n.style.opacity="1"}),this.setupFormEvents(e,t,n)}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}buildFormDOM(e,t){const n=e.style||{},i=n.primaryColor||"#10B981",s=n.textColor||"#18181B",o=document.createElement("button");o.id="clianta-form-close",o.style.cssText="\n position: absolute;\n top: 12px;\n right: 12px;\n background: none;\n border: none;\n font-size: 20px;\n cursor: pointer;\n color: #71717A;\n padding: 4px;\n ",o.textContent="×",t.appendChild(o);const r=document.createElement("h2");r.style.cssText=`font-size: 20px; font-weight: 700; margin-bottom: 8px; color: ${this.escapeHTML(s)};`,r.textContent=e.headline||"Stay in touch",t.appendChild(r);const a=document.createElement("p");a.style.cssText="font-size: 14px; color: #71717A; margin-bottom: 16px;",a.textContent=e.subheadline||"Get the latest updates",t.appendChild(a);const d=document.createElement("form");d.id="clianta-form-element",e.fields.forEach(e=>{const t=document.createElement("div");if(t.style.marginBottom="12px","checkbox"===e.type){const n=document.createElement("label");n.style.cssText=`display: flex; align-items: center; gap: 8px; font-size: 14px; color: ${this.escapeHTML(s)}; cursor: pointer;`;const i=document.createElement("input");i.type="checkbox",i.name=e.name,e.required&&(i.required=!0),i.style.cssText="width: 16px; height: 16px;",n.appendChild(i);const o=document.createTextNode(e.label+" ");if(n.appendChild(o),e.required){const e=document.createElement("span");e.style.color="#EF4444",e.textContent="*",n.appendChild(e)}t.appendChild(n)}else{const n=document.createElement("label");if(n.style.cssText=`display: block; font-size: 14px; font-weight: 500; margin-bottom: 4px; color: ${this.escapeHTML(s)};`,n.textContent=e.label+" ",e.required){const e=document.createElement("span");e.style.color="#EF4444",e.textContent="*",n.appendChild(e)}if(t.appendChild(n),"textarea"===e.type){const n=document.createElement("textarea");n.name=e.name,e.placeholder&&(n.placeholder=e.placeholder),e.required&&(n.required=!0),n.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; resize: vertical; min-height: 80px; box-sizing: border-box;",t.appendChild(n)}else if("select"===e.type){const n=document.createElement("select");if(n.name=e.name,e.required&&(n.required=!0),n.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box; background: white; cursor: pointer;",e.placeholder){const t=document.createElement("option");t.value="",t.textContent=e.placeholder,t.disabled=!0,t.selected=!0,n.appendChild(t)}e.options&&Array.isArray(e.options)&&e.options.forEach(e=>{const t=document.createElement("option");"string"==typeof e?(t.value=e,t.textContent=e):(t.value=e.value,t.textContent=e.label),n.appendChild(t)}),t.appendChild(n)}else{const n=document.createElement("input");n.type=e.type,n.name=e.name,e.placeholder&&(n.placeholder=e.placeholder),e.required&&(n.required=!0),n.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box;",t.appendChild(n)}}d.appendChild(t)});const c=document.createElement("button");c.type="submit",c.style.cssText=`\n width: 100%;\n padding: 10px 16px;\n background: ${this.escapeHTML(i)};\n color: white;\n border: none;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n margin-top: 8px;\n `,c.textContent=e.submitButtonText||"Subscribe",d.appendChild(c),t.appendChild(d)}setupFormEvents(e,t,n){const i=n.querySelector("#clianta-form-close");i&&i.addEventListener("click",()=>this.closeForm(e._id,t,n)),t.addEventListener("click",i=>{i.target===t&&this.closeForm(e._id,t,n)});const s=n.querySelector("#clianta-form-element");s&&s.addEventListener("submit",async t=>{t.preventDefault(),await this.handleSubmit(e,s,n)})}closeForm(e,t,n){n.style.transform="translateY(20px)",n.style.opacity="0",t.style.opacity="0",setTimeout(()=>{t.remove()},300)}async handleSubmit(e,t,n){if(!this.tracker)return;const i=this.tracker.getConfig().apiEndpoint||"http://localhost:5000",s=this.tracker.getVisitorId(),o=new FormData(t),r={};o.forEach((e,t)=>{r[t]=e});const a=t.querySelector('button[type="submit"]');a&&(a.disabled=!0,a.textContent="Submitting...");try{const t=await fetch(`${i}/api/public/lead-forms/${e._id}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:s,data:r,url:window.location.href})});if((await t.json()).success){n.innerHTML="";const t=document.createElement("div");t.style.cssText="text-align: center; padding: 20px;";const i=document.createElement("div");i.style.cssText="width: 48px; height: 48px; background: #10B981; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center;";const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("width","24"),s.setAttribute("height","24"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","white"),s.setAttribute("stroke-width","2");const o=document.createElementNS("http://www.w3.org/2000/svg","polyline");o.setAttribute("points","20 6 9 17 4 12"),s.appendChild(o),i.appendChild(s);const a=document.createElement("p");if(a.style.cssText="font-size: 16px; font-weight: 500; color: #18181B;",a.textContent=e.successMessage||"Thank you!",t.appendChild(i),t.appendChild(a),n.appendChild(t),r.email&&this.tracker?.identify(r.email,r),e.redirectUrl)try{const t=new URL(e.redirectUrl,window.location.origin),n=t.origin===window.location.origin,i="https:"===t.protocol||"http:"===t.protocol;n||i?setTimeout(()=>{window.location.href=t.href},1500):console.warn("[Clianta] Blocked unsafe redirect URL:",e.redirectUrl)}catch{console.warn("[Clianta] Invalid redirect URL:",e.redirectUrl)}setTimeout(()=>{const t=document.getElementById(`clianta-form-overlay-${e._id}`);t&&this.closeForm(e._id,t,n)},2e3)}}catch(t){console.error("[Clianta] Form submit error:",t),a&&(a.disabled=!1,a.textContent=e.submitButtonText||"Subscribe")}}}function N(e){switch(e){case"pageView":return new C;case"scroll":return new H;case"forms":return new L;case"clicks":return new F;case"engagement":return new P;case"downloads":return new _;case"exitIntent":return new M;case"errors":return new A;case"performance":return new q;case"popupForms":return new $;default:throw new Error(`Unknown plugin: ${e}`)}}function D(e){try{if("undefined"==typeof localStorage)return!1;const t={state:e,timestamp:Date.now(),version:1};return localStorage.setItem(r,JSON.stringify(t)),!0}catch{return!1}}function R(){try{if("undefined"==typeof localStorage)return null;const e=localStorage.getItem(r);if(!e)return null;const t=JSON.parse(e);return 1!==t.version?(O(),null):t}catch{return null}}function O(){try{return"undefined"!=typeof localStorage&&(localStorage.removeItem(r),!0)}catch{return!1}}class V{constructor(e={}){this.eventBuffer=[],this.callbacks=[],this.hasExplicitConsent=!1,this.config={defaultConsent:{analytics:!0,marketing:!1,personalization:!1},waitForConsent:!1,storageKey:"mb_consent",...e};const t=R();t?(this.state=t.state,this.hasExplicitConsent=!0,p.debug("Loaded stored consent:",this.state)):(this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,p.debug("Using default consent:",this.state)),e.onConsentChange&&this.callbacks.push(e.onConsentChange)}grant(e){const t={...this.state};this.state={...this.state,...e},this.hasExplicitConsent=!0,D(this.state),p.info("Consent granted:",e),this.notifyChange(t)}revoke(e){const t={...this.state};for(const t of e)this.state[t]=!1;this.hasExplicitConsent=!0,D(this.state),p.info("Consent revoked:",e),this.notifyChange(t)}update(e){const t={...this.state};this.state={...e},this.hasExplicitConsent=!0,D(this.state),p.info("Consent updated:",this.state),this.notifyChange(t)}reset(){const e={...this.state};this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,this.eventBuffer=[],O(),p.info("Consent reset to defaults"),this.notifyChange(e)}getState(){return{...this.state}}hasConsent(e){return!0===this.state[e]}canTrack(){return!(this.config.waitForConsent&&!this.hasExplicitConsent)&&!0===this.state.analytics}hasExplicit(){return this.hasExplicitConsent}hasStored(){return null!==R()}bufferEvent(e){this.eventBuffer.length>=100&&(p.warn("Consent event buffer full, dropping oldest event"),this.eventBuffer.shift()),this.eventBuffer.push(e),p.debug("Event buffered (waiting for consent):",e.eventName)}flushBuffer(){const e=[...this.eventBuffer];return this.eventBuffer=[],e.length>0&&p.debug(`Flushing ${e.length} buffered events`),e}getBufferSize(){return this.eventBuffer.length}onChange(e){return this.callbacks.push(e),()=>{const t=this.callbacks.indexOf(e);t>-1&&this.callbacks.splice(t,1)}}notifyChange(e){for(const t of this.callbacks)try{t(this.state,e)}catch(e){p.error("Consent change callback error:",e)}}}class z{constructor(e,i={}){if(this.plugins=[],this.isInitialized=!1,this.contactId=null,this.groupId=null,this.pendingIdentify=null,this.eventSchemas=new Map,this.middlewares=[],this.readyCallbacks=[],!e)throw new Error("[Clianta] Workspace ID is required");this.workspaceId=e,this.config=function(e={}){return{...n,...e,consent:{...n.consent,...e.consent}}}(i),p.enabled=this.config.debug,p.info(`Initializing SDK v${t}`,{workspaceId:e}),this.consentManager=new V({...this.config.consent,onConsentChange:(e,t)=>{this.onConsentChange(e,t)}}),this.transport=new f({apiEndpoint:this.config.apiEndpoint}),this.queue=new T(this.transport,{batchSize:this.config.batchSize,flushInterval:this.config.flushInterval}),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),p.debug("IDs created",{visitorId:this.visitorId,sessionId:this.sessionId}),!this.config.apiEndpoint.startsWith("http://")||"undefined"==typeof window||window.location.hostname.includes("localhost")||window.location.hostname.includes("127.0.0.1")||p.warn("apiEndpoint uses HTTP — events will be sent unencrypted. Use HTTPS in production."),this.initPlugins(),this.isInitialized=!0,p.info("SDK initialized successfully");for(const e of this.readyCallbacks)try{e()}catch(e){p.error("onReady callback error:",e)}this.readyCallbacks=[]}createVisitorId(){if(this.config.consent.anonymousMode&&!this.consentManager.hasExplicit()){const e=i+"_anon";let t=g(e);return t||(t="anon_"+m(),w(e,t)),t}if(this.config.cookielessMode){let e=g(i);return e||(e=m(),w(i,e)),e}return v(this.config.useCookies)}createSessionId(){return function(e){const t=s,n=o;let i=g(t);const r=parseInt(g(n)||"0",10),a=Date.now();return(!i||a-r>e)&&(i=m(),w(t,i)),w(n,a.toString()),i}(this.config.sessionTimeout)}onConsentChange(e,t){if(p.debug("Consent changed:",{from:t,to:e}),e.analytics&&!t.analytics){this.config.consent.anonymousMode&&(this.visitorId=v(this.config.useCookies),p.info("Upgraded from anonymous to persistent visitor ID"));const e=this.consentManager.flushBuffer();for(const t of e)t.visitorId=this.visitorId,this.queue.push(t)}}initPlugins(){const e=this.config.plugins,t=this.config.autoPageView?e:e.filter(e=>"pageView"!==e);for(const e of t)try{const t=N(e),n=t.init(this);n instanceof Promise&&n.catch(t=>{p.error(`Async plugin init failed: ${e}`,t)}),this.plugins.push(t),p.debug(`Plugin loaded: ${e}`)}catch(t){p.error(`Failed to load plugin: ${e}`,t)}}track(e,n,i={}){if(!this.isInitialized)return void p.warn("SDK not initialized, event dropped");const s={workspaceId:this.workspaceId,visitorId:this.visitorId,sessionId:this.sessionId,eventType:e,eventName:n,url:"undefined"!=typeof window?window.location.href:"",referrer:"undefined"!=typeof document&&document.referrer||void 0,properties:{...i,eventId:m(),websiteDomain:"undefined"!=typeof window?window.location.hostname:void 0},device:"undefined"==typeof window||"undefined"==typeof navigator?{userAgent:"unknown",screen:"unknown",language:"unknown",timezone:"unknown"}:{userAgent:navigator.userAgent,screen:`${screen.width}x${screen.height}`,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"unknown"},...E(),timestamp:(new Date).toISOString(),sdkVersion:t};if(this.contactId&&(s.contactId=this.contactId),this.groupId&&(s.groupId=this.groupId),this.validateEventSchema(e,i),!this.consentManager.canTrack())return this.config.consent.waitForConsent?void this.consentManager.bufferEvent(s):void p.debug("Event dropped (no consent):",n);this.runMiddleware(s,()=>{this.queue.push(s),p.debug("Event tracked:",n,i)})}page(e,t={}){const n=e||("undefined"!=typeof document?document.title:"Page View");this.track("page_view",n,{...t,path:"undefined"!=typeof window?window.location.pathname:""})}async identify(e,t={}){if(!e)return p.warn("Email is required for identification"),null;if(!function(e){return!("string"!=typeof e||!e)&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}(e))return p.warn("Invalid email format, identification skipped:",e),null;p.info("Identifying visitor:",e);const n=await this.transport.sendIdentify({workspaceId:this.workspaceId,visitorId:this.visitorId,email:e,properties:t});return n.success?(p.info("Visitor identified successfully, contactId:",n.contactId),this.contactId=n.contactId??null,this.pendingIdentify=null,this.contactId):(p.error("Failed to identify visitor:",n.error),this.pendingIdentify={email:e,traits:t},null)}async retryPendingIdentify(){if(!this.pendingIdentify)return;const{email:e,traits:t}=this.pendingIdentify;this.pendingIdentify=null,await this.identify(e,t)}consent(e){this.consentManager.update(e)}getConsentState(){return this.consentManager.getState()}debug(e){p.enabled=e,p.info("Debug mode "+(e?"enabled":"disabled"))}group(e,t={}){e?(this.groupId=e,p.info("Visitor grouped:",e),this.track("group","Group Identified",{groupId:e,...t})):p.warn("groupId is required for group()")}async alias(e,t){if(!e)return p.warn("newId is required for alias()"),!1;const n=t||this.visitorId;p.info("Aliasing visitor:",{from:n,to:e});try{const t=`${this.config.apiEndpoint}/api/public/track/alias`,i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:this.workspaceId,previousId:n,newId:e})});return i.ok?(p.info("Alias successful"),!0):(p.error("Alias failed:",i.status),!1)}catch(e){return p.error("Alias request failed:",e),!1}}screen(e,t={}){this.track("screen_view",e,{...t,screenName:e})}use(e){this.middlewares.push(e),p.debug("Middleware registered")}runMiddleware(e,t){if(0===this.middlewares.length)return void t();let n=0;const i=this.middlewares,s=()=>{if(n++,n<i.length)try{i[n](e,s)}catch(e){p.error("Middleware error:",e),t()}else t()};try{i[0](e,s)}catch(e){p.error("Middleware error:",e),t()}}onReady(e){if(this.isInitialized)try{e()}catch(e){p.error("onReady callback error:",e)}else this.readyCallbacks.push(e)}isReady(){return this.isInitialized}registerEventSchema(e,t){this.eventSchemas.set(e,t),p.debug("Event schema registered:",e)}validateEventSchema(e,t){if(!this.config.debug)return;const n=this.eventSchemas.get(e);if(n)for(const[i,s]of Object.entries(n)){const n=t[i];if(void 0===n){p.warn(`[Schema] Missing property "${i}" for event type "${e}"`);continue}let o=!1;switch(s){case"string":o="string"==typeof n;break;case"number":o="number"==typeof n;break;case"boolean":o="boolean"==typeof n;break;case"object":o="object"==typeof n&&!Array.isArray(n);break;case"array":o=Array.isArray(n)}o||p.warn(`[Schema] Property "${i}" for event "${e}" expected ${s}, got ${typeof n}`)}}getVisitorId(){return this.visitorId}getSessionId(){return this.sessionId}getWorkspaceId(){return this.workspaceId}getConfig(){return{...this.config}}async flush(){await this.retryPendingIdentify(),await this.queue.flush()}reset(){p.info("Resetting visitor data"),b(this.config.useCookies),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),this.contactId=null,this.pendingIdentify=null,this.queue.clear()}deleteData(){if(p.info("Deleting all user data (GDPR request)"),this.queue.clear(),this.consentManager.reset(),b(this.config.useCookies),"undefined"!=typeof sessionStorage)try{sessionStorage.removeItem(i),sessionStorage.removeItem(i+"_anon"),sessionStorage.removeItem(s),sessionStorage.removeItem(o)}catch{}if("undefined"!=typeof localStorage)try{localStorage.removeItem(i),localStorage.removeItem(r),localStorage.removeItem(a)}catch{}this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),p.info("All user data deleted")}async createContact(e){return this.publicCrmRequest("/api/public/crm/contacts","POST",{workspaceId:this.workspaceId,...e})}async updateContact(e,t){return this.publicCrmRequest(`/api/public/crm/contacts/${e}`,"PUT",{workspaceId:this.workspaceId,...t})}async submitForm(e,t){const n={...t,metadata:{...t.metadata,visitorId:this.visitorId,sessionId:this.sessionId,pageUrl:"undefined"!=typeof window?window.location.href:void 0,referrer:"undefined"!=typeof document&&document.referrer||void 0}};return this.publicCrmRequest(`/api/public/crm/forms/${e}/submit`,"POST",n)}async logActivity(e){return this.publicCrmRequest("/api/public/crm/activities","POST",{workspaceId:this.workspaceId,...e})}async createOpportunity(e){return this.publicCrmRequest("/api/public/crm/opportunities","POST",{workspaceId:this.workspaceId,...e})}async publicCrmRequest(e,t,n){const i=`${this.config.apiEndpoint}${e}`;try{const s=await fetch(i,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),o=await s.json().catch(()=>({}));return s.ok?(p.debug(`Public CRM ${t} ${e} succeeded`),{success:!0,data:o.data??o,status:s.status}):(p.error(`Public CRM ${t} ${e} failed (${s.status}):`,o.message),{success:!1,error:o.message,status:s.status})}catch(n){return p.error(`Public CRM ${t} ${e} error:`,n),{success:!1,error:n.message}}}async destroy(){p.info("Destroying tracker"),await this.queue.flush();for(const e of this.plugins)e.destroy&&e.destroy();this.plugins=[],this.queue.destroy(),this.isInitialized=!1}}let B=null;function j(e,t){return B&&B.getWorkspaceId()===e||(B&&B.destroy(),B=new z(e,t)),B}if("undefined"!=typeof window){window.clianta=j,window.Clianta={clianta:j,Tracker:z,ConsentManager:V};const e=()=>{const e=document.querySelectorAll("script[data-project-id]"),t=e[e.length-1];if(!t)return;const n=t.getAttribute("data-project-id");if(!n)return;const i=j(n,{debug:t.hasAttribute("data-debug")});window.__clianta=i};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.ConsentManager=V,e.SDK_VERSION=t,e.Tracker=z,e.clianta=j,e.default=j,Object.defineProperty(e,"__esModule",{value:!0})});
7
7
  //# sourceMappingURL=clianta.umd.min.js.map