@clianta/sdk 1.7.1 → 1.7.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,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -11,7 +11,7 @@ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentS
11
11
  * @see SDK_VERSION in core/config.ts
12
12
  */
13
13
  /** SDK Version */
14
- const SDK_VERSION = '1.7.0';
14
+ const SDK_VERSION = '1.7.2';
15
15
  /** Default API endpoint — reads from env or falls back to localhost */
16
16
  const getDefaultApiEndpoint = () => {
17
17
  // Next.js (process.env)
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -8,7 +8,7 @@
8
8
  * @see SDK_VERSION in core/config.ts
9
9
  */
10
10
  /** SDK Version */
11
- const SDK_VERSION = '1.7.0';
11
+ const SDK_VERSION = '1.7.2';
12
12
  /** Default API endpoint — reads from env or falls back to localhost */
13
13
  const getDefaultApiEndpoint = () => {
14
14
  // Next.js (process.env)
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -13,7 +13,7 @@ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentS
13
13
  * @see SDK_VERSION in core/config.ts
14
14
  */
15
15
  /** SDK Version */
16
- const SDK_VERSION = '1.7.0';
16
+ const SDK_VERSION = '1.7.2';
17
17
  /** Default API endpoint — reads from env or falls back to localhost */
18
18
  const getDefaultApiEndpoint = () => {
19
19
  // Next.js (process.env)
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -8,7 +8,7 @@
8
8
  * @see SDK_VERSION in core/config.ts
9
9
  */
10
10
  /** SDK Version */
11
- const SDK_VERSION = '1.7.0';
11
+ const SDK_VERSION = '1.7.2';
12
12
  /** Default API endpoint — reads from env or falls back to localhost */
13
13
  const getDefaultApiEndpoint = () => {
14
14
  // Next.js (process.env)
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -15,7 +15,7 @@
15
15
  * @see SDK_VERSION in core/config.ts
16
16
  */
17
17
  /** SDK Version */
18
- const SDK_VERSION = '1.7.0';
18
+ const SDK_VERSION = '1.7.2';
19
19
  /** Default API endpoint — reads from env or falls back to localhost */
20
20
  const getDefaultApiEndpoint = () => {
21
21
  // Next.js (process.env)
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.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";var t="undefined"!=typeof document?document.currentScript:null;const n="1.7.0",i={projectId:"",apiEndpoint:(()=>{if("undefined"!=typeof process&&process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT)return process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT;try{"undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("clianta.umd.min.js",document.baseURI).href,0}catch{}if("undefined"!=typeof process&&process.env?.REACT_APP_CLIANTA_API_ENDPOINT)return process.env.REACT_APP_CLIANTA_API_ENDPOINT;if("undefined"!=typeof process&&process.env?.CLIANTA_API_ENDPOINT)return process.env.CLIANTA_API_ENDPOINT;return"undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)||"undefined"==typeof console||console.warn("[Clianta] No API endpoint configured. Set NEXT_PUBLIC_CLIANTA_API_ENDPOINT (Next.js), VITE_CLIANTA_API_ENDPOINT (Vite), or pass apiEndpoint directly to clianta(). Falling back to localhost — tracking will not work in production."),"http://localhost:5000"})(),debug:!1,autoPageView:!0,plugins:["pageView","forms","scroll","clicks","engagement","downloads","exitIntent","errors","performance","autoIdentify"],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"},s="mb_vid",o="mb_sid",r="mb_st",a="mb_consent",d="mb_queue",l=[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 u="[Clianta]",h={debug:"color: #6b7280; font-weight: normal;",info:"color: #3b82f6; font-weight: normal;",warn:"color: #f59e0b; font-weight: bold;",error:"color: #ef4444; font-weight: bold;"},f={debug:0,info:1,warn:2,error:3};const m=function(e=!1){let t="debug",n=e;const i=e=>!!n&&f[e]>=f[t],s=(e,t)=>"undefined"!=typeof console&&"undefined"!=typeof window?[`%c${u}`,h[e],...t]:[`${u} [${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 p{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});if(n.length>6e4){return this.sendBeacon(e)?{success:!0}:this.send(t,n,1,!1)}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?(m.debug("Identify successful, contactId:",i.contactId),{success:!0,status:n.status,contactId:i.contactId??void 0}):(n.status>=500?m.warn(`Identify server error (${n.status})`):m.error(`Identify failed with status ${n.status}:`,i.message),{success:!1,status:n.status})}catch(e){return m.error("Identify request failed:",e),{success:!1,error:e}}}sendBeacon(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return m.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?m.debug(`Beacon sent ${e.length} events`):m.warn("sendBeacon returned false"),n}catch(e){return m.error("sendBeacon error:",e),!1}}async sendPost(e,t){const n=`${this.config.apiEndpoint}${e}`,i=JSON.stringify(t);return this.send(n,i)}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 m.debug("Fetch successful:",e),{success:!0,data:n.data??n,status:t.status}}return m.error(`Fetch failed with status ${t.status}`),{success:!1,status:t.status}}catch(e){return m.error("Fetch request failed:",e),{success:!1,error:e}}}async send(e,t,n=1,i=!0){if("undefined"!=typeof navigator&&!navigator.onLine)return m.warn("Device offline, skipping send"),{success:!1,error:new Error("offline")};try{const s=await this.fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:i});if(s.ok)return m.debug("Request successful:",e),{success:!0,status:s.status};if(s.status>=500&&n<this.config.maxRetries){const o=this.config.retryDelay*Math.pow(2,n-1);return m.warn(`Server error (${s.status}), retrying in ${o}ms...`),await this.delay(o),this.send(e,t,n+1,i)}return m.error(`Request failed with status ${s.status}`),{success:!1,status:s.status}}catch(s){if(("undefined"==typeof navigator||navigator.onLine)&&n<this.config.maxRetries){const s=this.config.retryDelay*Math.pow(2,n-1);return m.warn(`Network error, retrying in ${s}ms (${n}/${this.config.maxRetries})...`),await this.delay(s),this.send(e,t,n+1,i)}return m.error("Request failed after retries:",s),{success:!1,error:s}}}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 g(){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 y(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 v(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 b(e=!1){const t=s;let n=null;return n=e?v(t):function(e){try{if("undefined"!=typeof localStorage)return localStorage.getItem(e)}catch{}return null}(t),n||(n=g(),e?v(t,n,365):function(e,t){try{if("undefined"!=typeof localStorage)return localStorage.setItem(e,t),!0}catch{}}(t,n)),n}function k(e=!1){const t=s;if(e)v(t,"",-1);else try{localStorage.removeItem(t)}catch{}try{sessionStorage.removeItem(o),sessionStorage.removeItem(r)}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 S(e){try{return e.split("/").pop()?.split("?")[0]||"unknown"}catch{return"unknown"}}function T(e){const t=S(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)}function x(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("data-track-click")||e.classList.contains("track-click")}class C{constructor(e,t={}){this.queue=[],this.flushTimer=null,this.isFlushing=!1,this.isOnline=!0,this.eventTimestamps=[],this.boundBeforeUnload=null,this.boundVisibilityChange=null,this.boundPageHide=null,this.boundOnline=null,this.boundOffline=null,this.unloadFlushed=!1,this.transport=e,this.config={batchSize:t.batchSize??10,flushInterval:t.flushInterval??5e3,maxQueueSize:t.maxQueueSize??1e3,storageKey:t.storageKey??d},this.persistMode=t.persistMode||"session",this.isOnline="undefined"==typeof navigator||navigator.onLine,this.restoreQueue(),this.startFlushTimer(),this.setupUnloadHandlers()}push(e){this.checkRateLimit()?(this.queue.length>=this.config.maxQueueSize&&(m.warn("Queue full, dropping oldest event"),this.queue.shift()),this.queue.push(e),m.debug("Event queued:",e.eventName,`(${this.queue.length} in queue)`),this.queue.length>=this.config.batchSize&&this.flush()):m.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||!this.isOnline)return;this.isFlushing=!0;const e=this.queue.length,t=this.queue.splice(0,e);try{m.debug(`Flushing ${t.length} events`),this.persistQueue([]);(await this.transport.sendEvents(t)).success?m.debug("Flush successful"):(m.warn("Flush failed, re-queuing events"),this.queue.unshift(...t),this.persistQueue(this.queue))}catch(e){m.error("Flush error:",e)}finally{this.isFlushing=!1}}flushSync(){if(this.unloadFlushed||0===this.queue.length)return;this.unloadFlushed=!0;const e=this.queue.splice(0,this.queue.length);m.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),this.boundOnline&&window.removeEventListener("online",this.boundOnline),this.boundOffline&&window.removeEventListener("offline",this.boundOffline))}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():this.unloadFlushed=!1},window.addEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide=()=>this.flushSync(),window.addEventListener("pagehide",this.boundPageHide),this.boundOnline=()=>{m.info("Connection restored — flushing queued events"),this.isOnline=!0,this.flush()},this.boundOffline=()=>{m.warn("Connection lost — pausing event queue"),this.isOnline=!1},window.addEventListener("online",this.boundOnline),window.addEventListener("offline",this.boundOffline))}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=y(this.config.storageKey)),e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.queue=t,m.debug(`Restored ${t.length} events from storage`))}}catch{}}}class _{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)}}const H="__clianta_pv_wrapped__";class L extends _{constructor(){super(...arguments),this.name="pageView",this.originalPushState=null,this.originalReplaceState=null,this.navHandler=null,this.popstateHandler=null}init(e){if(super.init(e),this.trackPageView(),"undefined"!=typeof window){if(!history.pushState[H]){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this.originalPushState,t=this.originalReplaceState;history.pushState=function(...t){e.apply(history,t),window.dispatchEvent(new Event("clianta:navigation"))},history.pushState[H]=!0,history.replaceState=function(...e){t.apply(history,e),window.dispatchEvent(new Event("clianta:navigation"))},history.replaceState[H]=!0}this.navHandler=()=>this.trackPageView(),window.addEventListener("clianta:navigation",this.navHandler),this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler)}}destroy(){"undefined"!=typeof window&&(this.navHandler&&(window.removeEventListener("clianta:navigation",this.navHandler),this.navHandler=null),this.popstateHandler&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null)),this.originalPushState&&(history.pushState=this.originalPushState,delete history.pushState[H],this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,delete history.replaceState[H],this.originalReplaceState=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 N extends _{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 l)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 F extends _{constructor(){super(...arguments),this.name="forms",this.trackedForms=new WeakSet,this.formInteractions=new Set,this.observer=null,this.observerTimer=null,this.listeners=[]}init(e){super.init(e),"undefined"!=typeof document&&(this.trackAllForms(),"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(()=>{this.observerTimer&&clearTimeout(this.observerTimer),this.observerTimer=setTimeout(()=>this.trackAllForms(),100)}),this.observer.observe(document.body,{childList:!0,subtree:!0})))}destroy(){this.observerTimer&&(clearTimeout(this.observerTimer),this.observerTimer=null),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 P extends _{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){let t=e.target;for(;t&&!x(t);)t=t.parentElement;if(!t)return;const n=I(t,100),i=(s=t,{tag:s.tagName?.toLowerCase()||"unknown",id:s.id||"",className:s.className||"",text:I(s,50)});var s;this.track("button_click","Button Clicked",{buttonText:n,elementType:t.tagName.toLowerCase(),elementId:i.id,elementClass:i.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 A extends _{constructor(){super(...arguments),this.name="engagement",this.pageLoadTime=0,this.engagementStartTime=0,this.isEngaged=!1,this.engagementTimeout=null,this.unloadReported=!1,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(),this.unloadReported=!1)},["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.unloadReported=!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(){if(this.unloadReported)return;this.unloadReported=!0;const e=Math.floor((Date.now()-this.engagementStartTime)/1e3);e>0&&this.track("time_on_page","Time Spent",{seconds:e,engaged:this.isEngaged})}}class O extends _{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:S(n),fileType:T(n),linkText:I(t,100)})))}}class M extends _{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 $ extends _{constructor(){super(...arguments),this.name="errors",this.boundErrorHandler=null,this.boundRejectionHandler=null,this.seenErrors=new Set}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){const t=`${e.message}:${e.filename}:${e.lineno}`;this.dedup(t)&&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){const t=String(e.reason).substring(0,200);this.dedup(t)&&this.track("error","Unhandled Promise Rejection",{reason:t})}dedup(e){return!this.seenErrors.has(e)&&(!(this.seenErrors.size>=20)&&(this.seenErrors.add(e),!0))}}class D extends _{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 q extends _{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 l=document.createElement("button");l.type="submit",l.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 `,l.textContent=e.submitButtonText||"Subscribe",d.appendChild(l),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")}}}const R=5e4,U=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,V=["__session","__clerk_db_jwt","next-auth.session-token","__Secure-next-auth.session-token","sb-access-token","auth0.is.authenticated","KEYCLOAK_SESSION","KEYCLOAK_IDENTITY","KC_RESTART","token","jwt","access_token","session_token","auth_token","id_token"],j=["sb-","supabase.auth.","firebase:authUser:","auth0spajs","@@auth0spajs@@","msal.","msal.account","CognitoIdentityServiceProvider","amplify-signin-with-hostedUI","kc-callback-","persist:","-storage","token","jwt","auth","user","session","credential","account"],z=["email","sub","preferred_username","user_email","mail","emailAddress","e_mail"],B=["name","full_name","display_name","displayName"],W=["given_name","first_name","firstName","fname"],K=["family_name","last_name","lastName","lname"],J=[2e3,5e3,1e4,1e4,3e4,3e4,3e4,6e4,6e4,6e4];class Q extends _{constructor(){super(...arguments),this.name="autoIdentify",this.pollTimeouts=[],this.identifiedEmail=null,this.storageHandler=null,this.sessionProbed=!1}init(e){super.init(e),"undefined"!=typeof window&&(this.schedulePollChecks(),this.listenForStorageChanges())}destroy(){for(const e of this.pollTimeouts)clearTimeout(e);this.pollTimeouts=[],this.storageHandler&&"undefined"!=typeof window&&(window.removeEventListener("storage",this.storageHandler),this.storageHandler=null),super.destroy()}schedulePollChecks(){let e=0;for(let t=0;t<J.length;t++){e+=J[t];const n=setTimeout(()=>{if(!this.identifiedEmail){try{this.checkForAuthUser()}catch{}3!==t||this.sessionProbed||(this.sessionProbed=!0,this.guardedSessionProbe())}},e);this.pollTimeouts.push(n)}}listenForStorageChanges(){this.storageHandler=e=>{if(this.identifiedEmail)return;if(!e.key||!e.newValue)return;const t=e.key.toLowerCase();if(j.some(e=>t.includes(e.toLowerCase())))try{this.checkForAuthUser()}catch{}},window.addEventListener("storage",this.storageHandler)}checkForAuthUser(){if(this.tracker&&!this.identifiedEmail){try{const e=this.checkAuthProviders();if(e)return void this.identifyUser(e)}catch{}try{const e=this.checkCookies();if(e)return void this.identifyUser(e)}catch{}try{if("undefined"!=typeof localStorage){const e=this.checkStorage(localStorage);if(e)return void this.identifyUser(e)}}catch{}try{if("undefined"!=typeof sessionStorage){const e=this.checkStorage(sessionStorage);if(e)return void this.identifyUser(e)}}catch{}}}checkAuthProviders(){const e=window;try{const t=e.Clerk?.user;if(t){const e=t.primaryEmailAddress?.emailAddress||t.emailAddresses?.[0]?.emailAddress;if(e&&this.isValidEmail(e))return{email:e,firstName:t.firstName||void 0,lastName:t.lastName||void 0}}}catch{}try{const t=e.firebase?.auth?.(),n=t?.currentUser;if(n?.email&&this.isValidEmail(n.email)){const e=(n.displayName||"").split(" ");return{email:n.email,firstName:e[0]||void 0,lastName:e.slice(1).join(" ")||void 0}}}catch{}try{const t=e.__SUPABASE_CLIENT__||e.supabase;if(t?.auth){const e=t.auth.session?.()||t.auth.getSession?.(),n=e?.data?.session?.user||e?.user;if(n?.email&&this.isValidEmail(n.email)){const e=n.user_metadata||{};return{email:n.email,firstName:e.first_name||e.full_name?.split(" ")[0]||void 0,lastName:e.last_name||e.full_name?.split(" ").slice(1).join(" ")||void 0}}}}catch{}try{const t=e.__auth0Client||e.auth0Client;if(t?.isAuthenticated?.()){const e=t.getUser?.();if(e?.email&&this.isValidEmail(e.email))return{email:e.email,firstName:e.given_name||e.name?.split(" ")[0]||void 0,lastName:e.family_name||e.name?.split(" ").slice(1).join(" ")||void 0}}}catch{}try{const t=e.__google_credential_response?.credential;if(t&&"string"==typeof t){const e=this.extractUserFromToken(t);if(e)return e}const n=e.gapi?.auth2?.getAuthInstance?.()?.currentUser?.get?.(),i=n?.getBasicProfile?.();if(i){const e=i.getEmail?.();if(e&&this.isValidEmail(e))return{email:e,firstName:i.getGivenName?.()||void 0,lastName:i.getFamilyName?.()||void 0}}}catch{}try{const t=e.msalInstance||e.__msalInstance;if(t){const e=(t.getAllAccounts?.()||[])[0];if(e?.username&&this.isValidEmail(e.username)){const t=(e.name||"").split(" ");return{email:e.username,firstName:t[0]||void 0,lastName:t.slice(1).join(" ")||void 0}}}}catch{}try{const t=e.aws_amplify_currentUser||e.__amplify_user;if(t?.signInDetails?.loginId&&this.isValidEmail(t.signInDetails.loginId))return{email:t.signInDetails.loginId,firstName:t.attributes?.given_name||void 0,lastName:t.attributes?.family_name||void 0};if("undefined"!=typeof localStorage){const e=this.checkCognitoStorage();if(e)return e}}catch{}try{const t=e.keycloak||e.Keycloak;if(t?.authenticated&&t.tokenParsed){const e=t.tokenParsed,n=e.email||e.preferred_username;if(n&&this.isValidEmail(n))return{email:n,firstName:e.given_name||void 0,lastName:e.family_name||void 0}}}catch{}try{const t=e.__clianta_user;if(t?.email&&"string"==typeof t.email&&this.isValidEmail(t.email))return{email:t.email,firstName:t.firstName||void 0,lastName:t.lastName||void 0}}catch{}return null}identifyUser(e){if(this.tracker&&this.identifiedEmail!==e.email){this.identifiedEmail=e.email,this.tracker.identify(e.email,{firstName:e.firstName,lastName:e.lastName});for(const e of this.pollTimeouts)clearTimeout(e);this.pollTimeouts=[]}}checkCookies(){if("undefined"==typeof document)return null;try{const e=document.cookie.split(";").map(e=>e.trim());for(const t of e){const[e,...n]=t.split("="),i=n.join("="),s=e.trim().toLowerCase();if(V.some(e=>s.includes(e.toLowerCase()))&&i){const e=this.extractUserFromToken(decodeURIComponent(i));if(e)return e}}}catch{}return null}checkStorage(e){try{for(let t=0;t<e.length;t++){const n=e.key(t);if(!n)continue;const i=n.toLowerCase();if(j.some(e=>i.includes(e.toLowerCase()))){const t=e.getItem(n);if(!t)continue;if(t.length>R)continue;const i=this.extractUserFromToken(t);if(i)return i;try{const e=JSON.parse(t),n=this.deepScanForUser(e,0);if(n)return n}catch{}}}}catch{}return null}deepScanForUser(e,t){if(t>4||!e||"object"!=typeof e||Array.isArray(e))return null;const n=e,i=Object.keys(n),s=this.extractUserFromClaims(n);if(s)return s;const o=i.slice(0,20);for(const e of o){const t=n[e];if("string"==typeof t&&t.length>30&&t.length<4e3){if(2===(t.match(/\./g)||[]).length){const e=this.extractUserFromToken(t);if(e)return e}}}for(const e of o){const i=n[e];if(i&&"object"==typeof i&&!Array.isArray(i)){const e=this.deepScanForUser(i,t+1);if(e)return e}}return null}extractUserFromToken(e){const t=e.split(".");if(3!==t.length)return null;try{const e=JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")));return this.extractUserFromClaims(e)}catch{return null}}extractUserFromClaims(e){if(!e||"object"!=typeof e)return null;let t,n,i=null;for(const t of z){const n=e[t];if(n&&"string"==typeof n&&this.isValidEmail(n)){i=n;break}}if(!i){const t=e.primaryEmailAddress?.emailAddress||e.emailAddresses?.[0]?.emailAddress;t&&"string"==typeof t&&this.isValidEmail(t)&&(i=t)}if(!i)return null;for(const n of W)if(e[n]&&"string"==typeof e[n]){t=e[n];break}for(const t of K)if(e[t]&&"string"==typeof e[t]){n=e[t];break}if(!t)for(const i of B)if(e[i]&&"string"==typeof e[i]){const s=e[i].split(" ");t=s[0],n=n||s.slice(1).join(" ")||void 0;break}return{email:i,firstName:t,lastName:n}}async guardedSessionProbe(){if(this.identifiedEmail)return;const e="undefined"!=typeof document&&(document.cookie.includes("next-auth.session-token")||document.cookie.includes("__Secure-next-auth.session-token")),t="undefined"!=typeof window&&(null!=window.__NEXTAUTH||null!=window.__NEXT_DATA__);if(e||t)try{const e=await fetch("/api/auth/session",{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(e.ok){const t=await e.json();if(t&&"object"==typeof t&&Object.keys(t).length>0){const e=this.deepScanForUser(t,0);e&&this.identifyUser(e)}}}catch{}}checkCognitoStorage(){try{for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);if(t){if(t.startsWith("CognitoIdentityServiceProvider.")&&t.endsWith(".idToken")){const e=localStorage.getItem(t);if(e&&e.length<R){const t=this.extractUserFromToken(e);if(t)return t}}if(t.startsWith("CognitoIdentityServiceProvider.")&&t.endsWith(".userData")){const e=localStorage.getItem(t);if(e&&e.length<R)try{const t=JSON.parse(e),n=t.UserAttributes||t.attributes||[],i=n.find?.(e=>"email"===e.Name||"email"===e.name);if(i?.Value&&this.isValidEmail(i.Value)){const e=n.find?.(e=>"name"===e.Name||"name"===e.name),t=n.find?.(e=>"given_name"===e.Name||"given_name"===e.name),s=n.find?.(e=>"family_name"===e.Name||"family_name"===e.name);let o=t?.Value,r=s?.Value;if(!o&&e?.Value){const t=e.Value.split(" ");o=t[0],r=r||t.slice(1).join(" ")||void 0}return{email:i.Value,firstName:o||void 0,lastName:r||void 0}}}catch{}}}}}catch{}return null}isValidEmail(e){return U.test(e)}}function Y(e){switch(e){case"pageView":return new L;case"scroll":return new N;case"forms":return new F;case"clicks":return new P;case"engagement":return new A;case"downloads":return new O;case"exitIntent":return new M;case"errors":return new $;case"performance":return new D;case"popupForms":return new q;case"autoIdentify":return new Q;default:throw new Error(`Unknown plugin: ${e}`)}}function G(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 X(){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?(Z(),null):t}catch{return null}}function Z(){try{return"undefined"!=typeof localStorage&&(localStorage.removeItem(a),!0)}catch{return!1}}class ee{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=X();t?(this.state=t.state,this.hasExplicitConsent=!0,m.debug("Loaded stored consent:",this.state)):(this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,m.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,G(this.state),m.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,G(this.state),m.info("Consent revoked:",e),this.notifyChange(t)}update(e){const t={...this.state};this.state={...e},this.hasExplicitConsent=!0,G(this.state),m.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=[],Z(),m.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!==X()}bufferEvent(e){this.eventBuffer.length>=100&&(m.warn("Consent event buffer full, dropping oldest event"),this.eventBuffer.shift()),this.eventBuffer.push(e),m.debug("Event buffered (waiting for consent):",e.eventName)}flushBuffer(){const e=[...this.eventBuffer];return this.eventBuffer=[],e.length>0&&m.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){m.error("Consent change callback error:",e)}}}class te{constructor(e,t={}){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}}}(t),m.enabled=this.config.debug,m.info(`Initializing SDK v${n}`,{workspaceId:e}),this.consentManager=new ee({...this.config.consent,onConsentChange:(e,t)=>{this.onConsentChange(e,t)}}),this.transport=new p({apiEndpoint:this.config.apiEndpoint}),this.queue=new C(this.transport,{batchSize:this.config.batchSize,flushInterval:this.config.flushInterval}),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),m.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")||m.warn("apiEndpoint uses HTTP — events will be sent unencrypted. Use HTTPS in production."),this.initPlugins(),this.isInitialized=!0,m.info("SDK initialized successfully");for(const e of this.readyCallbacks)try{e()}catch(e){m.error("onReady callback error:",e)}this.readyCallbacks=[]}createVisitorId(){if(this.config.consent.anonymousMode&&!this.consentManager.hasExplicit()){const e=s+"_anon";let t=y(e);return t||(t="anon_"+g(),w(e,t)),t}if(this.config.cookielessMode){let e=y(s);return e||(e=g(),w(s,e)),e}return b(this.config.useCookies)}createSessionId(){return function(e){const t=o,n=r;let i=y(t);const s=parseInt(y(n)||"0",10),a=Date.now();return(!i||a-s>e)&&(i=g(),w(t,i)),w(n,a.toString()),i}(this.config.sessionTimeout)}onConsentChange(e,t){if(m.debug("Consent changed:",{from:t,to:e}),e.analytics&&!t.analytics){this.config.consent.anonymousMode&&(this.visitorId=b(this.config.useCookies),m.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=Y(e),n=t.init(this);n instanceof Promise&&n.catch(t=>{m.error(`Async plugin init failed: ${e}`,t)}),this.plugins.push(t),m.debug(`Plugin loaded: ${e}`)}catch(t){m.error(`Failed to load plugin: ${e}`,t)}}track(e,t,i={}){if(!this.isInitialized)return void m.warn("SDK not initialized, event dropped");const s={workspaceId:this.workspaceId,visitorId:this.visitorId,sessionId:this.sessionId,eventType:e,eventName:t,url:"undefined"!=typeof window?window.location.href:"",referrer:"undefined"!=typeof document&&document.referrer||void 0,properties:{...i,eventId:g(),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:n};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 m.debug("Event dropped (no consent):",t);this.runMiddleware(s,()=>{this.queue.push(s),m.debug("Event tracked:",t,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 m.warn("Email is required for identification"),null;if(!function(e){return!("string"!=typeof e||!e)&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}(e))return m.warn("Invalid email format, identification skipped:",e),null;m.info("Identifying visitor:",e);const n=await this.transport.sendIdentify({workspaceId:this.workspaceId,visitorId:this.visitorId,email:e,properties:t});return n.success?(m.info("Visitor identified successfully, contactId:",n.contactId),this.contactId=n.contactId??null,this.pendingIdentify=null,this.contactId):(m.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){m.enabled=e,m.info("Debug mode "+(e?"enabled":"disabled"))}group(e,t={}){e?(this.groupId=e,m.info("Visitor grouped:",e),this.track("group","Group Identified",{groupId:e,...t})):m.warn("groupId is required for group()")}async alias(e,t){if(!e)return m.warn("newId is required for alias()"),!1;const n=t||this.visitorId;m.info("Aliasing visitor:",{from:n,to:e});const i=await this.transport.sendPost("/api/public/track/alias",{workspaceId:this.workspaceId,previousId:n,newId:e});return i.success?(m.info("Alias successful"),!0):(m.error("Alias failed:",i.error??i.status),!1)}screen(e,t={}){this.track("screen_view",e,{...t,screenName:e})}use(e){this.middlewares.push(e),m.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){m.error("Middleware error:",e),t()}else t()};try{i[0](e,s)}catch(e){m.error("Middleware error:",e),t()}}onReady(e){if(this.isInitialized)try{e()}catch(e){m.error("onReady callback error:",e)}else this.readyCallbacks.push(e)}isReady(){return this.isInitialized}registerEventSchema(e,t){this.eventSchemas.set(e,t),m.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){m.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||m.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(){m.info("Resetting visitor data"),k(this.config.useCookies),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),this.contactId=null,this.pendingIdentify=null,this.queue.clear()}deleteData(){if(m.info("Deleting all user data (GDPR request)"),this.queue.clear(),this.consentManager.reset(),k(this.config.useCookies),"undefined"!=typeof sessionStorage)try{sessionStorage.removeItem(s),sessionStorage.removeItem(s+"_anon"),sessionStorage.removeItem(o),sessionStorage.removeItem(r)}catch{}if("undefined"!=typeof localStorage)try{localStorage.removeItem(s),localStorage.removeItem(a),localStorage.removeItem(d)}catch{}this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),m.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?(m.debug(`Public CRM ${t} ${e} succeeded`),{success:!0,data:o.data??o,status:s.status}):(m.error(`Public CRM ${t} ${e} failed (${s.status}):`,o.message),{success:!1,error:o.message,status:s.status})}catch(n){return m.error(`Public CRM ${t} ${e} error:`,n),{success:!1,error:n.message}}}async destroy(){m.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 ne=null;function ie(e,t){return ne&&ne.getWorkspaceId()===e?(t&&Object.keys(t).length>0&&"undefined"!=typeof console&&console.warn('[Clianta] clianta() called with config on an already-initialized instance for workspace "'+e+'". The new config was ignored. Call tracker.destroy() first if you need to reconfigure.'),ne):(ne&&ne.destroy(),ne=new te(e,t),ne)}if("undefined"!=typeof window){window.clianta=ie,window.Clianta={clianta:ie,Tracker:te,ConsentManager:ee};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={debug:t.hasAttribute("data-debug")},s=t.getAttribute("data-api-endpoint");s&&(i.apiEndpoint=s),t.hasAttribute("data-cookieless")&&(i.cookielessMode=!0),t.hasAttribute("data-use-cookies")&&(i.useCookies=!0);const o=ie(n,i);window.__clianta=o};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.ConsentManager=ee,e.SDK_VERSION=n,e.Tracker=te,e.clianta=ie,e.default=ie,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";var t="undefined"!=typeof document?document.currentScript:null;const n="1.7.2",i={projectId:"",apiEndpoint:(()=>{if("undefined"!=typeof process&&process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT)return process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT;try{"undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("clianta.umd.min.js",document.baseURI).href,0}catch{}if("undefined"!=typeof process&&process.env?.REACT_APP_CLIANTA_API_ENDPOINT)return process.env.REACT_APP_CLIANTA_API_ENDPOINT;if("undefined"!=typeof process&&process.env?.CLIANTA_API_ENDPOINT)return process.env.CLIANTA_API_ENDPOINT;return"undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)||"undefined"==typeof console||console.warn("[Clianta] No API endpoint configured. Set NEXT_PUBLIC_CLIANTA_API_ENDPOINT (Next.js), VITE_CLIANTA_API_ENDPOINT (Vite), or pass apiEndpoint directly to clianta(). Falling back to localhost — tracking will not work in production."),"http://localhost:5000"})(),debug:!1,autoPageView:!0,plugins:["pageView","forms","scroll","clicks","engagement","downloads","exitIntent","errors","performance","autoIdentify"],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"},s="mb_vid",o="mb_sid",r="mb_st",a="mb_consent",d="mb_queue",l=[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 u="[Clianta]",h={debug:"color: #6b7280; font-weight: normal;",info:"color: #3b82f6; font-weight: normal;",warn:"color: #f59e0b; font-weight: bold;",error:"color: #ef4444; font-weight: bold;"},f={debug:0,info:1,warn:2,error:3};const m=function(e=!1){let t="debug",n=e;const i=e=>!!n&&f[e]>=f[t],s=(e,t)=>"undefined"!=typeof console&&"undefined"!=typeof window?[`%c${u}`,h[e],...t]:[`${u} [${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 p{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});if(n.length>6e4){return this.sendBeacon(e)?{success:!0}:this.send(t,n,1,!1)}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?(m.debug("Identify successful, contactId:",i.contactId),{success:!0,status:n.status,contactId:i.contactId??void 0}):(n.status>=500?m.warn(`Identify server error (${n.status})`):m.error(`Identify failed with status ${n.status}:`,i.message),{success:!1,status:n.status})}catch(e){return m.error("Identify request failed:",e),{success:!1,error:e}}}sendBeacon(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return m.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?m.debug(`Beacon sent ${e.length} events`):m.warn("sendBeacon returned false"),n}catch(e){return m.error("sendBeacon error:",e),!1}}async sendPost(e,t){const n=`${this.config.apiEndpoint}${e}`,i=JSON.stringify(t);return this.send(n,i)}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 m.debug("Fetch successful:",e),{success:!0,data:n.data??n,status:t.status}}return m.error(`Fetch failed with status ${t.status}`),{success:!1,status:t.status}}catch(e){return m.error("Fetch request failed:",e),{success:!1,error:e}}}async send(e,t,n=1,i=!0){if("undefined"!=typeof navigator&&!navigator.onLine)return m.warn("Device offline, skipping send"),{success:!1,error:new Error("offline")};try{const s=await this.fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:i});if(s.ok)return m.debug("Request successful:",e),{success:!0,status:s.status};if(s.status>=500&&n<this.config.maxRetries){const o=this.config.retryDelay*Math.pow(2,n-1);return m.warn(`Server error (${s.status}), retrying in ${o}ms...`),await this.delay(o),this.send(e,t,n+1,i)}return m.error(`Request failed with status ${s.status}`),{success:!1,status:s.status}}catch(s){if(("undefined"==typeof navigator||navigator.onLine)&&n<this.config.maxRetries){const s=this.config.retryDelay*Math.pow(2,n-1);return m.warn(`Network error, retrying in ${s}ms (${n}/${this.config.maxRetries})...`),await this.delay(s),this.send(e,t,n+1,i)}return m.error("Request failed after retries:",s),{success:!1,error:s}}}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 g(){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 y(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 v(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 b(e=!1){const t=s;let n=null;return n=e?v(t):function(e){try{if("undefined"!=typeof localStorage)return localStorage.getItem(e)}catch{}return null}(t),n||(n=g(),e?v(t,n,365):function(e,t){try{if("undefined"!=typeof localStorage)return localStorage.setItem(e,t),!0}catch{}}(t,n)),n}function k(e=!1){const t=s;if(e)v(t,"",-1);else try{localStorage.removeItem(t)}catch{}try{sessionStorage.removeItem(o),sessionStorage.removeItem(r)}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 S(e){try{return e.split("/").pop()?.split("?")[0]||"unknown"}catch{return"unknown"}}function T(e){const t=S(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)}function x(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("data-track-click")||e.classList.contains("track-click")}class C{constructor(e,t={}){this.queue=[],this.flushTimer=null,this.isFlushing=!1,this.isOnline=!0,this.eventTimestamps=[],this.boundBeforeUnload=null,this.boundVisibilityChange=null,this.boundPageHide=null,this.boundOnline=null,this.boundOffline=null,this.unloadFlushed=!1,this.transport=e,this.config={batchSize:t.batchSize??10,flushInterval:t.flushInterval??5e3,maxQueueSize:t.maxQueueSize??1e3,storageKey:t.storageKey??d},this.persistMode=t.persistMode||"session",this.isOnline="undefined"==typeof navigator||navigator.onLine,this.restoreQueue(),this.startFlushTimer(),this.setupUnloadHandlers()}push(e){this.checkRateLimit()?(this.queue.length>=this.config.maxQueueSize&&(m.warn("Queue full, dropping oldest event"),this.queue.shift()),this.queue.push(e),m.debug("Event queued:",e.eventName,`(${this.queue.length} in queue)`),this.queue.length>=this.config.batchSize&&this.flush()):m.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||!this.isOnline)return;this.isFlushing=!0;const e=this.queue.length,t=this.queue.splice(0,e);try{m.debug(`Flushing ${t.length} events`),this.persistQueue([]);(await this.transport.sendEvents(t)).success?m.debug("Flush successful"):(m.warn("Flush failed, re-queuing events"),this.queue.unshift(...t),this.persistQueue(this.queue))}catch(e){m.error("Flush error:",e)}finally{this.isFlushing=!1}}flushSync(){if(this.unloadFlushed||0===this.queue.length)return;this.unloadFlushed=!0;const e=this.queue.splice(0,this.queue.length);m.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),this.boundOnline&&window.removeEventListener("online",this.boundOnline),this.boundOffline&&window.removeEventListener("offline",this.boundOffline))}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():this.unloadFlushed=!1},window.addEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide=()=>this.flushSync(),window.addEventListener("pagehide",this.boundPageHide),this.boundOnline=()=>{m.info("Connection restored — flushing queued events"),this.isOnline=!0,this.flush()},this.boundOffline=()=>{m.warn("Connection lost — pausing event queue"),this.isOnline=!1},window.addEventListener("online",this.boundOnline),window.addEventListener("offline",this.boundOffline))}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=y(this.config.storageKey)),e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.queue=t,m.debug(`Restored ${t.length} events from storage`))}}catch{}}}class _{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)}}const H="__clianta_pv_wrapped__";class L extends _{constructor(){super(...arguments),this.name="pageView",this.originalPushState=null,this.originalReplaceState=null,this.navHandler=null,this.popstateHandler=null}init(e){if(super.init(e),this.trackPageView(),"undefined"!=typeof window){if(!history.pushState[H]){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this.originalPushState,t=this.originalReplaceState;history.pushState=function(...t){e.apply(history,t),window.dispatchEvent(new Event("clianta:navigation"))},history.pushState[H]=!0,history.replaceState=function(...e){t.apply(history,e),window.dispatchEvent(new Event("clianta:navigation"))},history.replaceState[H]=!0}this.navHandler=()=>this.trackPageView(),window.addEventListener("clianta:navigation",this.navHandler),this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler)}}destroy(){"undefined"!=typeof window&&(this.navHandler&&(window.removeEventListener("clianta:navigation",this.navHandler),this.navHandler=null),this.popstateHandler&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null)),this.originalPushState&&(history.pushState=this.originalPushState,delete history.pushState[H],this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,delete history.replaceState[H],this.originalReplaceState=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 N extends _{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 l)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 F extends _{constructor(){super(...arguments),this.name="forms",this.trackedForms=new WeakSet,this.formInteractions=new Set,this.observer=null,this.observerTimer=null,this.listeners=[]}init(e){super.init(e),"undefined"!=typeof document&&(this.trackAllForms(),"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(()=>{this.observerTimer&&clearTimeout(this.observerTimer),this.observerTimer=setTimeout(()=>this.trackAllForms(),100)}),this.observer.observe(document.body,{childList:!0,subtree:!0})))}destroy(){this.observerTimer&&(clearTimeout(this.observerTimer),this.observerTimer=null),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 P extends _{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){let t=e.target;for(;t&&!x(t);)t=t.parentElement;if(!t)return;const n=I(t,100),i=(s=t,{tag:s.tagName?.toLowerCase()||"unknown",id:s.id||"",className:s.className||"",text:I(s,50)});var s;this.track("button_click","Button Clicked",{buttonText:n,elementType:t.tagName.toLowerCase(),elementId:i.id,elementClass:i.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 A extends _{constructor(){super(...arguments),this.name="engagement",this.pageLoadTime=0,this.engagementStartTime=0,this.isEngaged=!1,this.engagementTimeout=null,this.unloadReported=!1,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(),this.unloadReported=!1)},["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.unloadReported=!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(){if(this.unloadReported)return;this.unloadReported=!0;const e=Math.floor((Date.now()-this.engagementStartTime)/1e3);e>0&&this.track("time_on_page","Time Spent",{seconds:e,engaged:this.isEngaged})}}class O extends _{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:S(n),fileType:T(n),linkText:I(t,100)})))}}class M extends _{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 $ extends _{constructor(){super(...arguments),this.name="errors",this.boundErrorHandler=null,this.boundRejectionHandler=null,this.seenErrors=new Set}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){const t=`${e.message}:${e.filename}:${e.lineno}`;this.dedup(t)&&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){const t=String(e.reason).substring(0,200);this.dedup(t)&&this.track("error","Unhandled Promise Rejection",{reason:t})}dedup(e){return!this.seenErrors.has(e)&&(!(this.seenErrors.size>=20)&&(this.seenErrors.add(e),!0))}}class D extends _{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 q extends _{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 l=document.createElement("button");l.type="submit",l.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 `,l.textContent=e.submitButtonText||"Subscribe",d.appendChild(l),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")}}}const R=5e4,U=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,V=["__session","__clerk_db_jwt","next-auth.session-token","__Secure-next-auth.session-token","sb-access-token","auth0.is.authenticated","KEYCLOAK_SESSION","KEYCLOAK_IDENTITY","KC_RESTART","token","jwt","access_token","session_token","auth_token","id_token"],j=["sb-","supabase.auth.","firebase:authUser:","auth0spajs","@@auth0spajs@@","msal.","msal.account","CognitoIdentityServiceProvider","amplify-signin-with-hostedUI","kc-callback-","persist:","-storage","token","jwt","auth","user","session","credential","account"],z=["email","sub","preferred_username","user_email","mail","emailAddress","e_mail"],B=["name","full_name","display_name","displayName"],W=["given_name","first_name","firstName","fname"],K=["family_name","last_name","lastName","lname"],J=[2e3,5e3,1e4,1e4,3e4,3e4,3e4,6e4,6e4,6e4];class Q extends _{constructor(){super(...arguments),this.name="autoIdentify",this.pollTimeouts=[],this.identifiedEmail=null,this.storageHandler=null,this.sessionProbed=!1}init(e){super.init(e),"undefined"!=typeof window&&(this.schedulePollChecks(),this.listenForStorageChanges())}destroy(){for(const e of this.pollTimeouts)clearTimeout(e);this.pollTimeouts=[],this.storageHandler&&"undefined"!=typeof window&&(window.removeEventListener("storage",this.storageHandler),this.storageHandler=null),super.destroy()}schedulePollChecks(){let e=0;for(let t=0;t<J.length;t++){e+=J[t];const n=setTimeout(()=>{if(!this.identifiedEmail){try{this.checkForAuthUser()}catch{}3!==t||this.sessionProbed||(this.sessionProbed=!0,this.guardedSessionProbe())}},e);this.pollTimeouts.push(n)}}listenForStorageChanges(){this.storageHandler=e=>{if(this.identifiedEmail)return;if(!e.key||!e.newValue)return;const t=e.key.toLowerCase();if(j.some(e=>t.includes(e.toLowerCase())))try{this.checkForAuthUser()}catch{}},window.addEventListener("storage",this.storageHandler)}checkForAuthUser(){if(this.tracker&&!this.identifiedEmail){try{const e=this.checkAuthProviders();if(e)return void this.identifyUser(e)}catch{}try{const e=this.checkCookies();if(e)return void this.identifyUser(e)}catch{}try{if("undefined"!=typeof localStorage){const e=this.checkStorage(localStorage);if(e)return void this.identifyUser(e)}}catch{}try{if("undefined"!=typeof sessionStorage){const e=this.checkStorage(sessionStorage);if(e)return void this.identifyUser(e)}}catch{}}}checkAuthProviders(){const e=window;try{const t=e.Clerk?.user;if(t){const e=t.primaryEmailAddress?.emailAddress||t.emailAddresses?.[0]?.emailAddress;if(e&&this.isValidEmail(e))return{email:e,firstName:t.firstName||void 0,lastName:t.lastName||void 0}}}catch{}try{const t=e.firebase?.auth?.(),n=t?.currentUser;if(n?.email&&this.isValidEmail(n.email)){const e=(n.displayName||"").split(" ");return{email:n.email,firstName:e[0]||void 0,lastName:e.slice(1).join(" ")||void 0}}}catch{}try{const t=e.__SUPABASE_CLIENT__||e.supabase;if(t?.auth){const e=t.auth.session?.()||t.auth.getSession?.(),n=e?.data?.session?.user||e?.user;if(n?.email&&this.isValidEmail(n.email)){const e=n.user_metadata||{};return{email:n.email,firstName:e.first_name||e.full_name?.split(" ")[0]||void 0,lastName:e.last_name||e.full_name?.split(" ").slice(1).join(" ")||void 0}}}}catch{}try{const t=e.__auth0Client||e.auth0Client;if(t?.isAuthenticated?.()){const e=t.getUser?.();if(e?.email&&this.isValidEmail(e.email))return{email:e.email,firstName:e.given_name||e.name?.split(" ")[0]||void 0,lastName:e.family_name||e.name?.split(" ").slice(1).join(" ")||void 0}}}catch{}try{const t=e.__google_credential_response?.credential;if(t&&"string"==typeof t){const e=this.extractUserFromToken(t);if(e)return e}const n=e.gapi?.auth2?.getAuthInstance?.()?.currentUser?.get?.(),i=n?.getBasicProfile?.();if(i){const e=i.getEmail?.();if(e&&this.isValidEmail(e))return{email:e,firstName:i.getGivenName?.()||void 0,lastName:i.getFamilyName?.()||void 0}}}catch{}try{const t=e.msalInstance||e.__msalInstance;if(t){const e=(t.getAllAccounts?.()||[])[0];if(e?.username&&this.isValidEmail(e.username)){const t=(e.name||"").split(" ");return{email:e.username,firstName:t[0]||void 0,lastName:t.slice(1).join(" ")||void 0}}}}catch{}try{const t=e.aws_amplify_currentUser||e.__amplify_user;if(t?.signInDetails?.loginId&&this.isValidEmail(t.signInDetails.loginId))return{email:t.signInDetails.loginId,firstName:t.attributes?.given_name||void 0,lastName:t.attributes?.family_name||void 0};if("undefined"!=typeof localStorage){const e=this.checkCognitoStorage();if(e)return e}}catch{}try{const t=e.keycloak||e.Keycloak;if(t?.authenticated&&t.tokenParsed){const e=t.tokenParsed,n=e.email||e.preferred_username;if(n&&this.isValidEmail(n))return{email:n,firstName:e.given_name||void 0,lastName:e.family_name||void 0}}}catch{}try{const t=e.__clianta_user;if(t?.email&&"string"==typeof t.email&&this.isValidEmail(t.email))return{email:t.email,firstName:t.firstName||void 0,lastName:t.lastName||void 0}}catch{}return null}identifyUser(e){if(this.tracker&&this.identifiedEmail!==e.email){this.identifiedEmail=e.email,this.tracker.identify(e.email,{firstName:e.firstName,lastName:e.lastName});for(const e of this.pollTimeouts)clearTimeout(e);this.pollTimeouts=[]}}checkCookies(){if("undefined"==typeof document)return null;try{const e=document.cookie.split(";").map(e=>e.trim());for(const t of e){const[e,...n]=t.split("="),i=n.join("="),s=e.trim().toLowerCase();if(V.some(e=>s.includes(e.toLowerCase()))&&i){const e=this.extractUserFromToken(decodeURIComponent(i));if(e)return e}}}catch{}return null}checkStorage(e){try{for(let t=0;t<e.length;t++){const n=e.key(t);if(!n)continue;const i=n.toLowerCase();if(j.some(e=>i.includes(e.toLowerCase()))){const t=e.getItem(n);if(!t)continue;if(t.length>R)continue;const i=this.extractUserFromToken(t);if(i)return i;try{const e=JSON.parse(t),n=this.deepScanForUser(e,0);if(n)return n}catch{}}}}catch{}return null}deepScanForUser(e,t){if(t>4||!e||"object"!=typeof e||Array.isArray(e))return null;const n=e,i=Object.keys(n),s=this.extractUserFromClaims(n);if(s)return s;const o=i.slice(0,20);for(const e of o){const t=n[e];if("string"==typeof t&&t.length>30&&t.length<4e3){if(2===(t.match(/\./g)||[]).length){const e=this.extractUserFromToken(t);if(e)return e}}}for(const e of o){const i=n[e];if(i&&"object"==typeof i&&!Array.isArray(i)){const e=this.deepScanForUser(i,t+1);if(e)return e}}return null}extractUserFromToken(e){const t=e.split(".");if(3!==t.length)return null;try{const e=JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")));return this.extractUserFromClaims(e)}catch{return null}}extractUserFromClaims(e){if(!e||"object"!=typeof e)return null;let t,n,i=null;for(const t of z){const n=e[t];if(n&&"string"==typeof n&&this.isValidEmail(n)){i=n;break}}if(!i){const t=e.primaryEmailAddress?.emailAddress||e.emailAddresses?.[0]?.emailAddress;t&&"string"==typeof t&&this.isValidEmail(t)&&(i=t)}if(!i)return null;for(const n of W)if(e[n]&&"string"==typeof e[n]){t=e[n];break}for(const t of K)if(e[t]&&"string"==typeof e[t]){n=e[t];break}if(!t)for(const i of B)if(e[i]&&"string"==typeof e[i]){const s=e[i].split(" ");t=s[0],n=n||s.slice(1).join(" ")||void 0;break}return{email:i,firstName:t,lastName:n}}async guardedSessionProbe(){if(this.identifiedEmail)return;const e="undefined"!=typeof document&&(document.cookie.includes("next-auth.session-token")||document.cookie.includes("__Secure-next-auth.session-token")),t="undefined"!=typeof window&&(null!=window.__NEXTAUTH||null!=window.__NEXT_DATA__);if(e||t)try{const e=await fetch("/api/auth/session",{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(e.ok){const t=await e.json();if(t&&"object"==typeof t&&Object.keys(t).length>0){const e=this.deepScanForUser(t,0);e&&this.identifyUser(e)}}}catch{}}checkCognitoStorage(){try{for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);if(t){if(t.startsWith("CognitoIdentityServiceProvider.")&&t.endsWith(".idToken")){const e=localStorage.getItem(t);if(e&&e.length<R){const t=this.extractUserFromToken(e);if(t)return t}}if(t.startsWith("CognitoIdentityServiceProvider.")&&t.endsWith(".userData")){const e=localStorage.getItem(t);if(e&&e.length<R)try{const t=JSON.parse(e),n=t.UserAttributes||t.attributes||[],i=n.find?.(e=>"email"===e.Name||"email"===e.name);if(i?.Value&&this.isValidEmail(i.Value)){const e=n.find?.(e=>"name"===e.Name||"name"===e.name),t=n.find?.(e=>"given_name"===e.Name||"given_name"===e.name),s=n.find?.(e=>"family_name"===e.Name||"family_name"===e.name);let o=t?.Value,r=s?.Value;if(!o&&e?.Value){const t=e.Value.split(" ");o=t[0],r=r||t.slice(1).join(" ")||void 0}return{email:i.Value,firstName:o||void 0,lastName:r||void 0}}}catch{}}}}}catch{}return null}isValidEmail(e){return U.test(e)}}function Y(e){switch(e){case"pageView":return new L;case"scroll":return new N;case"forms":return new F;case"clicks":return new P;case"engagement":return new A;case"downloads":return new O;case"exitIntent":return new M;case"errors":return new $;case"performance":return new D;case"popupForms":return new q;case"autoIdentify":return new Q;default:throw new Error(`Unknown plugin: ${e}`)}}function G(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 X(){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?(Z(),null):t}catch{return null}}function Z(){try{return"undefined"!=typeof localStorage&&(localStorage.removeItem(a),!0)}catch{return!1}}class ee{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=X();t?(this.state=t.state,this.hasExplicitConsent=!0,m.debug("Loaded stored consent:",this.state)):(this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,m.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,G(this.state),m.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,G(this.state),m.info("Consent revoked:",e),this.notifyChange(t)}update(e){const t={...this.state};this.state={...e},this.hasExplicitConsent=!0,G(this.state),m.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=[],Z(),m.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!==X()}bufferEvent(e){this.eventBuffer.length>=100&&(m.warn("Consent event buffer full, dropping oldest event"),this.eventBuffer.shift()),this.eventBuffer.push(e),m.debug("Event buffered (waiting for consent):",e.eventName)}flushBuffer(){const e=[...this.eventBuffer];return this.eventBuffer=[],e.length>0&&m.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){m.error("Consent change callback error:",e)}}}class te{constructor(e,t={}){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}}}(t),m.enabled=this.config.debug,m.info(`Initializing SDK v${n}`,{workspaceId:e}),this.consentManager=new ee({...this.config.consent,onConsentChange:(e,t)=>{this.onConsentChange(e,t)}}),this.transport=new p({apiEndpoint:this.config.apiEndpoint}),this.queue=new C(this.transport,{batchSize:this.config.batchSize,flushInterval:this.config.flushInterval}),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),m.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")||m.warn("apiEndpoint uses HTTP — events will be sent unencrypted. Use HTTPS in production."),this.initPlugins(),this.isInitialized=!0,m.info("SDK initialized successfully");for(const e of this.readyCallbacks)try{e()}catch(e){m.error("onReady callback error:",e)}this.readyCallbacks=[]}createVisitorId(){if(this.config.consent.anonymousMode&&!this.consentManager.hasExplicit()){const e=s+"_anon";let t=y(e);return t||(t="anon_"+g(),w(e,t)),t}if(this.config.cookielessMode){let e=y(s);return e||(e=g(),w(s,e)),e}return b(this.config.useCookies)}createSessionId(){return function(e){const t=o,n=r;let i=y(t);const s=parseInt(y(n)||"0",10),a=Date.now();return(!i||a-s>e)&&(i=g(),w(t,i)),w(n,a.toString()),i}(this.config.sessionTimeout)}onConsentChange(e,t){if(m.debug("Consent changed:",{from:t,to:e}),e.analytics&&!t.analytics){this.config.consent.anonymousMode&&(this.visitorId=b(this.config.useCookies),m.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=Y(e),n=t.init(this);n instanceof Promise&&n.catch(t=>{m.error(`Async plugin init failed: ${e}`,t)}),this.plugins.push(t),m.debug(`Plugin loaded: ${e}`)}catch(t){m.error(`Failed to load plugin: ${e}`,t)}}track(e,t,i={}){if(!this.isInitialized)return void m.warn("SDK not initialized, event dropped");const s={workspaceId:this.workspaceId,visitorId:this.visitorId,sessionId:this.sessionId,eventType:e,eventName:t,url:"undefined"!=typeof window?window.location.href:"",referrer:"undefined"!=typeof document&&document.referrer||void 0,properties:{...i,eventId:g(),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:n};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 m.debug("Event dropped (no consent):",t);this.runMiddleware(s,()=>{this.queue.push(s),m.debug("Event tracked:",t,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 m.warn("Email is required for identification"),null;if(!function(e){return!("string"!=typeof e||!e)&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}(e))return m.warn("Invalid email format, identification skipped:",e),null;m.info("Identifying visitor:",e);const n=await this.transport.sendIdentify({workspaceId:this.workspaceId,visitorId:this.visitorId,email:e,properties:t});return n.success?(m.info("Visitor identified successfully, contactId:",n.contactId),this.contactId=n.contactId??null,this.pendingIdentify=null,this.contactId):(m.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){m.enabled=e,m.info("Debug mode "+(e?"enabled":"disabled"))}group(e,t={}){e?(this.groupId=e,m.info("Visitor grouped:",e),this.track("group","Group Identified",{groupId:e,...t})):m.warn("groupId is required for group()")}async alias(e,t){if(!e)return m.warn("newId is required for alias()"),!1;const n=t||this.visitorId;m.info("Aliasing visitor:",{from:n,to:e});const i=await this.transport.sendPost("/api/public/track/alias",{workspaceId:this.workspaceId,previousId:n,newId:e});return i.success?(m.info("Alias successful"),!0):(m.error("Alias failed:",i.error??i.status),!1)}screen(e,t={}){this.track("screen_view",e,{...t,screenName:e})}use(e){this.middlewares.push(e),m.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){m.error("Middleware error:",e),t()}else t()};try{i[0](e,s)}catch(e){m.error("Middleware error:",e),t()}}onReady(e){if(this.isInitialized)try{e()}catch(e){m.error("onReady callback error:",e)}else this.readyCallbacks.push(e)}isReady(){return this.isInitialized}registerEventSchema(e,t){this.eventSchemas.set(e,t),m.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){m.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||m.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(){m.info("Resetting visitor data"),k(this.config.useCookies),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),this.contactId=null,this.pendingIdentify=null,this.queue.clear()}deleteData(){if(m.info("Deleting all user data (GDPR request)"),this.queue.clear(),this.consentManager.reset(),k(this.config.useCookies),"undefined"!=typeof sessionStorage)try{sessionStorage.removeItem(s),sessionStorage.removeItem(s+"_anon"),sessionStorage.removeItem(o),sessionStorage.removeItem(r)}catch{}if("undefined"!=typeof localStorage)try{localStorage.removeItem(s),localStorage.removeItem(a),localStorage.removeItem(d)}catch{}this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),m.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?(m.debug(`Public CRM ${t} ${e} succeeded`),{success:!0,data:o.data??o,status:s.status}):(m.error(`Public CRM ${t} ${e} failed (${s.status}):`,o.message),{success:!1,error:o.message,status:s.status})}catch(n){return m.error(`Public CRM ${t} ${e} error:`,n),{success:!1,error:n.message}}}async destroy(){m.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 ne=null;function ie(e,t){return ne&&ne.getWorkspaceId()===e?(t&&Object.keys(t).length>0&&"undefined"!=typeof console&&console.warn('[Clianta] clianta() called with config on an already-initialized instance for workspace "'+e+'". The new config was ignored. Call tracker.destroy() first if you need to reconfigure.'),ne):(ne&&ne.destroy(),ne=new te(e,t),ne)}if("undefined"!=typeof window){window.clianta=ie,window.Clianta={clianta:ie,Tracker:te,ConsentManager:ee};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={debug:t.hasAttribute("data-debug")},s=t.getAttribute("data-api-endpoint");s&&(i.apiEndpoint=s),t.hasAttribute("data-cookieless")&&(i.cookielessMode=!0),t.hasAttribute("data-use-cookies")&&(i.useCookies=!0);const o=ie(n,i);window.__clianta=o};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.ConsentManager=ee,e.SDK_VERSION=n,e.Tracker=te,e.clianta=ie,e.default=ie,Object.defineProperty(e,"__esModule",{value:!0})});
7
7
  //# sourceMappingURL=clianta.umd.min.js.map
package/dist/index.d.ts CHANGED
@@ -524,7 +524,7 @@ interface StoredConsent {
524
524
  */
525
525
 
526
526
  /** SDK Version */
527
- declare const SDK_VERSION = "1.7.0";
527
+ declare const SDK_VERSION = "1.7.2";
528
528
 
529
529
  /**
530
530
  * Clianta SDK
package/dist/react.cjs.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -14,7 +14,7 @@ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentS
14
14
  * @see SDK_VERSION in core/config.ts
15
15
  */
16
16
  /** SDK Version */
17
- const SDK_VERSION = '1.7.0';
17
+ const SDK_VERSION = '1.7.2';
18
18
  /** Default API endpoint — reads from env or falls back to localhost */
19
19
  const getDefaultApiEndpoint = () => {
20
20
  // Next.js (process.env)
package/dist/react.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -11,7 +11,7 @@ import { createContext, useState, useRef, useEffect, useContext, useCallback, Co
11
11
  * @see SDK_VERSION in core/config.ts
12
12
  */
13
13
  /** SDK Version */
14
- const SDK_VERSION = '1.7.0';
14
+ const SDK_VERSION = '1.7.2';
15
15
  /** Default API endpoint — reads from env or falls back to localhost */
16
16
  const getDefaultApiEndpoint = () => {
17
17
  // Next.js (process.env)
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -11,7 +11,7 @@ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentS
11
11
  * @see SDK_VERSION in core/config.ts
12
12
  */
13
13
  /** SDK Version */
14
- const SDK_VERSION = '1.7.0';
14
+ const SDK_VERSION = '1.7.2';
15
15
  /** Default API endpoint — reads from env or falls back to localhost */
16
16
  const getDefaultApiEndpoint = () => {
17
17
  // Next.js (process.env)
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -8,7 +8,7 @@
8
8
  * @see SDK_VERSION in core/config.ts
9
9
  */
10
10
  /** SDK Version */
11
- const SDK_VERSION = '1.7.0';
11
+ const SDK_VERSION = '1.7.2';
12
12
  /** Default API endpoint — reads from env or falls back to localhost */
13
13
  const getDefaultApiEndpoint = () => {
14
14
  // Next.js (process.env)
package/dist/vue.cjs.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -13,7 +13,7 @@ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentS
13
13
  * @see SDK_VERSION in core/config.ts
14
14
  */
15
15
  /** SDK Version */
16
- const SDK_VERSION = '1.7.0';
16
+ const SDK_VERSION = '1.7.2';
17
17
  /** Default API endpoint — reads from env or falls back to localhost */
18
18
  const getDefaultApiEndpoint = () => {
19
19
  // Next.js (process.env)
package/dist/vue.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.7.1
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -10,7 +10,7 @@ import { ref, inject } from 'vue';
10
10
  * @see SDK_VERSION in core/config.ts
11
11
  */
12
12
  /** SDK Version */
13
- const SDK_VERSION = '1.7.0';
13
+ const SDK_VERSION = '1.7.2';
14
14
  /** Default API endpoint — reads from env or falls back to localhost */
15
15
  const getDefaultApiEndpoint = () => {
16
16
  // Next.js (process.env)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clianta/sdk",
3
- "version": "1.7.1",
3
+ "version": "1.7.2",
4
4
  "type": "module",
5
5
  "description": "Professional CRM SDK for Clianta - Track visitors, manage contacts, opportunities, and analyze behavior",
6
6
  "main": "dist/clianta.cjs.js",