@maxaiagent/widget-sdk 1.2.3 → 1.2.4

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
  /* @maxaiagent/widget-sdk v1.1.0 | MIT License | maxaiagent.app */
2
- "use strict";var MaxAISDK=(()=>{var L=Object.defineProperty,Qe=Object.defineProperties,Ze=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyDescriptors,tt=Object.getOwnPropertyNames,ce=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var he=(n,e,t)=>e in n?L(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,f=(n,e)=>{for(var t in e||(e={}))pe.call(e,t)&&he(n,t,e[t]);if(ce)for(var t of ce(e))nt.call(e,t)&&he(n,t,e[t]);return n},O=(n,e)=>Qe(n,et(e));var it=(n,e)=>{for(var t in e)L(n,t,{get:e[t],enumerable:!0})},st=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tt(e))!pe.call(n,s)&&s!==t&&L(n,s,{get:()=>e[s],enumerable:!(i=Ze(e,s))||i.enumerable});return n};var rt=n=>st(L({},"__esModule",{value:!0}),n);var yt={};it(yt,{MaxAI:()=>ie});var M=class{constructor(e){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=e}attach(e){this.iframe=e,this.boundListener=t=>this.onMessage(t),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let e of this.queue)this.sendRaw(e);this.queue=[]}send(e,t){let i=f({type:e},t);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(e,t){this.handlers.set(e,t)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(e){var t,i;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(i=(t=this.iframe)==null?void 0:t.contentWindow)==null||i.postMessage(e,this.baseUrl)}catch(s){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(e){return this.baseUrl}}onMessage(e){if(!e.data||!e.data.type||this.iframe&&e.source!==this.iframe.contentWindow||e.origin!==this.expectedOrigin())return;let t=this.handlers.get(e.data.type);t&&t(e.data)}};var A=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}emit(e,...t){var i;(i=this.listeners.get(e))==null||i.forEach(s=>{try{s(...t)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",ue="max-widget:register-tools",ge="max-widget:unregister-tool",G="max-widget:tool-result",me="max-widget:point-ask-result",H="max-widget:point-ask-cancel",w="max-widget:host-styles",fe="max-widget:debug-snapshot",P="max-widget:config-features";var ve="max-widget:expand",be="max-widget:hide",ye="max-widget:close",U="max-widget:request-page-context",xe="max-widget:start-point-ask",Se="max-widget:stop-point-ask",we="max-widget:execute-tool",Te="max-widget:request-debug-snapshot",D="max-widget:request-host-styles",Ee="max-widget:gdpr-consent",Me="max-widget:navigate",ke="max-widget:message",_e="max-widget:error";var N="max-widget:session-update",K="max-widget:session-request",_="max-widget:session-restore",B="max-widget:session-clear",Ie="max-widget:draft-save",Ce="max-widget:draft-request",Le="max-widget:draft-restore",Oe="max-widget:identity-set",Ae="max-widget:browser-metadata";var W=class{constructor(e){this.tools=new Map;this.transport=e}register(e){return!e.slug||!/^[a-z0-9_]+$/.test(e.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",e.slug),()=>{}):(this.tools.set(e.slug,{slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,handler:e.handler,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}),this.sendList(),()=>this.unregister(e.slug))}unregister(e){this.tools.has(e)&&(this.tools.delete(e),this.transport.send(ge,{slug:e}),this.sendList())}async execute(e,t,i){let s=this.tools.get(t);if(!(s!=null&&s.handler)){let o=`Tool "${t}" not found or has no handler`;return this.transport.send(G,{toolCallId:e,ok:!1,error:o}),{ok:!1,error:o}}try{let o=await s.handler(i);return this.transport.send(G,{toolCallId:e,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:t,args:i}})),{ok:!0}}catch(o){let r=o instanceof Error?o.message:"Tool execution failed";return this.transport.send(G,{toolCallId:e,ok:!1,error:r}),{ok:!1,error:r}}}sendList(){let e=Array.from(this.tools.values()).map(t=>({slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,requiresConfirmation:t.requiresConfirmation,category:t.category}));this.transport.send(ue,{tools:e})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Ge(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}var ot=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function at(n){let e=JSON.stringify(n);for(let t of ot)e=e.replace(t,"[REDACTED]");try{return JSON.parse(e)}catch(t){return n}}var $=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...t)=>{this.origConsole[e](...t);try{let i=t.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:e,message:Ge(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=e=>{this.errors.push({message:e.message||"",source:e.filename||"",line:e.lineno||0,col:e.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{this.errors.push({message:"Unhandled rejection: "+(e.reason?String(e.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(e=>{var t;for(let i of e.getEntries()){let s=i,o=(t=s.responseStatus)!=null?t:0;this.networkLog.push(f({method:"GET",url:Ge(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(e){}}}getSnapshot(){return at({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var e;if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];(e=this.perfObserver)==null||e.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function ne(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function lt(n){let e=[],t=n;for(;t&&t.nodeType===1;){let i=1,s=t.previousSibling;for(;s;)s.nodeType===1&&s.tagName===t.tagName&&i++,s=s.previousSibling;e.unshift(t.tagName.toLowerCase()+"["+i+"]"),t=t.parentElement}return"/"+e.join("/")}function dt(n){let e=n.tagName.toLowerCase();return!!(e==="input"||e==="textarea"||e==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var X=class{constructor(e){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=e}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=e=>this.onMouseMove(e),this.boundClick=e=>this.onClick(e),this.boundKey=e=>this.onKeyDown(e),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(H),this.cleanup())}onMouseMove(e){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);this.overlay.style.pointerEvents="auto",this.highlight(t)}onClick(e){if(e.preventDefault(),e.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);if(this.overlay.style.pointerEvents="auto",!t||dt(t)){this.transport.send(H),this.cleanup();return}let i={};for(let r of["class","id","href","src","alt","title","data-id","data-name"]){let a=t.getAttribute(r);a&&(i[r]=ne(a,200))}let s=t.parentElement?ne(t.parentElement.innerText,300):"",o={elementText:ne(t.innerText,500),elementTag:t.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:lt(t)};this.transport.send(me,o),this.cleanup()}onKeyDown(e){e.key==="Escape"&&(this.transport.send(H),this.cleanup())}highlight(e){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),e&&e!==document.body&&e!==document.documentElement?(e._prevOutline=e.style.outline,e._prevOffset=e.style.outlineOffset,e.style.outline="2px solid #6366f1",e.style.outlineOffset="2px",this.lastHighlighted=e):this.lastHighlighted=null}cleanup(){var e,t;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(t=(e=this.overlay)==null?void 0:e.parentNode)==null||t.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function ct(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function He(n){let e={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},t=document.querySelector('meta[name="description"]');t&&(e.description=t.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(e.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(e.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{e.jsonLd.push(JSON.parse(l.textContent||""))}catch(h){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(e.mainContent=ct(o.innerText,2e3));let r=document.querySelector(`script[data-key="${n}"]`);return r&&Array.from(r.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");e.customContext[l]=a.value}}),e}function Pe(n,e){if(!e)return n;let t=f({},n);return e.pageType&&(t.pageType=e.pageType),e.visibleData&&(t.visibleData=e.visibleData),e.customContext&&(t.customContext=f(f({},t.customContext),e.customContext)),t}var q=class{constructor(e){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=e,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let e=this.origPush,t=this.origReplace,i=()=>this.checkChange();history.pushState=function(...o){e.apply(this,o),i()},history.replaceState=function(...o){t.apply(this,o),i()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let s=document.querySelector("title");s&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(s,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var e;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(e=this.observer)==null||e.disconnect()}checkChange(){let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,setTimeout(this.onChange,200))}};function z(){return{userAgent:(navigator.userAgent||"").slice(0,256),language:navigator.language||"",platform:navigator.platform||"",screenWidth:screen.width||0,screenHeight:screen.height||0,devicePixelRatio:window.devicePixelRatio||1,timezone:ht(),touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,referrer:(document.referrer||"").slice(0,512)}}function ht(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch(n){return""}}function Ue(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return!0;let[t,i,s]=[+e[1],+e[2],+e[3]],o=Math.max(t,i,s),r=Math.min(t,i,s);return(o===0?0:(o-r)/o)<.15}function x(){let n=getComputedStyle(document.documentElement),e=getComputedStyle(document.body),t=e.backgroundColor||"",o={bgColor:!t||t==="rgba(0, 0, 0, 0)"||t==="transparent"?n.backgroundColor||"":t,fontFamily:e.fontFamily||"",textColor:e.color||"",primaryColor:"",accentColors:[]};try{let r=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],a={};for(let h of r){let g=document.querySelectorAll(h);for(let p=0;p<Math.min(g.length,10);p++){let y=getComputedStyle(g[p]),m=y.color;m&&m!==o.textColor&&m!=="rgb(0, 0, 0)"&&m!=="rgba(0, 0, 0, 0)"&&!Ue(m)&&(a[m]=(a[m]||0)+1);let b=y.backgroundColor;b&&b!=="rgba(0, 0, 0, 0)"&&b!=="transparent"&&b!==o.bgColor&&!Ue(b)&&(a[b]=(a[b]||0)+1)}}let l=Object.keys(a).sort((h,g)=>a[g]-a[h]);o.primaryColor=l[0]||"",o.accentColors=l.slice(0,5)}catch(r){}return o}var pt=`
2
+ "use strict";var MaxAISDK=(()=>{var L=Object.defineProperty,Qe=Object.defineProperties,Ze=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyDescriptors,tt=Object.getOwnPropertyNames,he=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var pe=(n,e,t)=>e in n?L(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,v=(n,e)=>{for(var t in e||(e={}))ue.call(e,t)&&pe(n,t,e[t]);if(he)for(var t of he(e))nt.call(e,t)&&pe(n,t,e[t]);return n},O=(n,e)=>Qe(n,et(e));var it=(n,e)=>{for(var t in e)L(n,t,{get:e[t],enumerable:!0})},st=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tt(e))!ue.call(n,s)&&s!==t&&L(n,s,{get:()=>e[s],enumerable:!(i=Ze(e,s))||i.enumerable});return n};var rt=n=>st(L({},"__esModule",{value:!0}),n);var yt={};it(yt,{MaxAI:()=>se});var M=class{constructor(e){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=e}attach(e){this.iframe=e,this.boundListener=t=>this.onMessage(t),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let e of this.queue)this.sendRaw(e);this.queue=[]}send(e,t){let i=v({type:e},t);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(e,t){this.handlers.set(e,t)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(e){var t,i;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(i=(t=this.iframe)==null?void 0:t.contentWindow)==null||i.postMessage(e,this.baseUrl)}catch(s){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(e){return this.baseUrl}}onMessage(e){if(!e.data||!e.data.type||this.iframe&&e.source!==this.iframe.contentWindow||e.origin!==this.expectedOrigin())return;let t=this.handlers.get(e.data.type);t&&t(e.data)}};var A=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}emit(e,...t){var i;(i=this.listeners.get(e))==null||i.forEach(s=>{try{s(...t)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",ge="max-widget:register-tools",me="max-widget:unregister-tool",G="max-widget:tool-result",fe="max-widget:point-ask-result",H="max-widget:point-ask-cancel",w="max-widget:host-styles",ve="max-widget:debug-snapshot",P="max-widget:config-features";var be="max-widget:expand",ye="max-widget:hide",xe="max-widget:close",U="max-widget:request-page-context",Se="max-widget:start-point-ask",we="max-widget:stop-point-ask",D="max-widget:execute-tool",Te="max-widget:request-debug-snapshot",N="max-widget:request-host-styles",Ee="max-widget:gdpr-consent",Me="max-widget:navigate",ke="max-widget:message",_e="max-widget:error";var K="max-widget:session-update",B="max-widget:session-request",_="max-widget:session-restore",W="max-widget:session-clear",Ie="max-widget:draft-save",Ce="max-widget:draft-request",Le="max-widget:draft-restore",Oe="max-widget:identity-set",Ae="max-widget:browser-metadata";var $=class{constructor(e){this.tools=new Map;this.transport=e}register(e){return!e.slug||!/^[a-z0-9_]+$/.test(e.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",e.slug),()=>{}):(this.tools.set(e.slug,{slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,handler:e.handler,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}),this.sendList(),()=>this.unregister(e.slug))}unregister(e){this.tools.has(e)&&(this.tools.delete(e),this.transport.send(me,{slug:e}),this.sendList())}async execute(e,t,i){let s=this.tools.get(t);if(!(s!=null&&s.handler)){let o=`Tool "${t}" not found or has no handler`;return this.transport.send(G,{toolCallId:e,ok:!1,error:o}),{ok:!1,error:o}}try{let o=await s.handler(i);return this.transport.send(G,{toolCallId:e,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:t,args:i}})),{ok:!0}}catch(o){let r=o instanceof Error?o.message:"Tool execution failed";return this.transport.send(G,{toolCallId:e,ok:!1,error:r}),{ok:!1,error:r}}}sendList(){this.sendListVia(this.transport)}sendListVia(e){let t=Array.from(this.tools.values()).map(i=>({slug:i.slug,name:i.name,description:i.description,schema:i.schema,context:i.context,requiresConfirmation:i.requiresConfirmation,category:i.category}));e.send(ge,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Ge(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}var ot=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function at(n){let e=JSON.stringify(n);for(let t of ot)e=e.replace(t,"[REDACTED]");try{return JSON.parse(e)}catch(t){return n}}var X=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...t)=>{this.origConsole[e](...t);try{let i=t.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:e,message:Ge(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=e=>{this.errors.push({message:e.message||"",source:e.filename||"",line:e.lineno||0,col:e.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{this.errors.push({message:"Unhandled rejection: "+(e.reason?String(e.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(e=>{var t;for(let i of e.getEntries()){let s=i,o=(t=s.responseStatus)!=null?t:0;this.networkLog.push(v({method:"GET",url:Ge(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(e){}}}getSnapshot(){return at({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var e;if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];(e=this.perfObserver)==null||e.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function ie(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function lt(n){let e=[],t=n;for(;t&&t.nodeType===1;){let i=1,s=t.previousSibling;for(;s;)s.nodeType===1&&s.tagName===t.tagName&&i++,s=s.previousSibling;e.unshift(t.tagName.toLowerCase()+"["+i+"]"),t=t.parentElement}return"/"+e.join("/")}function dt(n){let e=n.tagName.toLowerCase();return!!(e==="input"||e==="textarea"||e==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var q=class{constructor(e){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=e}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=e=>this.onMouseMove(e),this.boundClick=e=>this.onClick(e),this.boundKey=e=>this.onKeyDown(e),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(H),this.cleanup())}onMouseMove(e){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);this.overlay.style.pointerEvents="auto",this.highlight(t)}onClick(e){if(e.preventDefault(),e.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);if(this.overlay.style.pointerEvents="auto",!t||dt(t)){this.transport.send(H),this.cleanup();return}let i={};for(let r of["class","id","href","src","alt","title","data-id","data-name"]){let a=t.getAttribute(r);a&&(i[r]=ie(a,200))}let s=t.parentElement?ie(t.parentElement.innerText,300):"",o={elementText:ie(t.innerText,500),elementTag:t.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:lt(t)};this.transport.send(fe,o),this.cleanup()}onKeyDown(e){e.key==="Escape"&&(this.transport.send(H),this.cleanup())}highlight(e){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),e&&e!==document.body&&e!==document.documentElement?(e._prevOutline=e.style.outline,e._prevOffset=e.style.outlineOffset,e.style.outline="2px solid #6366f1",e.style.outlineOffset="2px",this.lastHighlighted=e):this.lastHighlighted=null}cleanup(){var e,t;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(t=(e=this.overlay)==null?void 0:e.parentNode)==null||t.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function ct(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function He(n){let e={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},t=document.querySelector('meta[name="description"]');t&&(e.description=t.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(e.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(e.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{e.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(e.mainContent=ct(o.innerText,2e3));let r=document.querySelector(`script[data-key="${n}"]`);return r&&Array.from(r.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");e.customContext[l]=a.value}}),e}function Pe(n,e){if(!e)return n;let t=v({},n);return e.pageType&&(t.pageType=e.pageType),e.visibleData&&(t.visibleData=e.visibleData),e.customContext&&(t.customContext=v(v({},t.customContext),e.customContext)),t}var z=class{constructor(e){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=e,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let e=this.origPush,t=this.origReplace,i=()=>this.checkChange();history.pushState=function(...o){e.apply(this,o),i()},history.replaceState=function(...o){t.apply(this,o),i()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let s=document.querySelector("title");s&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(s,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var e;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(e=this.observer)==null||e.disconnect()}checkChange(){let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,setTimeout(this.onChange,200))}};function F(){return{userAgent:(navigator.userAgent||"").slice(0,256),language:navigator.language||"",platform:navigator.platform||"",screenWidth:screen.width||0,screenHeight:screen.height||0,devicePixelRatio:window.devicePixelRatio||1,timezone:ht(),touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,referrer:(document.referrer||"").slice(0,512)}}function ht(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch(n){return""}}function Ue(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return!0;let[t,i,s]=[+e[1],+e[2],+e[3]],o=Math.max(t,i,s),r=Math.min(t,i,s);return(o===0?0:(o-r)/o)<.15}function x(){let n=getComputedStyle(document.documentElement),e=getComputedStyle(document.body),t=e.backgroundColor||"",o={bgColor:!t||t==="rgba(0, 0, 0, 0)"||t==="transparent"?n.backgroundColor||"":t,fontFamily:e.fontFamily||"",textColor:e.color||"",primaryColor:"",accentColors:[]};try{let r=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],a={};for(let c of r){let g=document.querySelectorAll(c);for(let p=0;p<Math.min(g.length,10);p++){let f=getComputedStyle(g[p]),m=f.color;m&&m!==o.textColor&&m!=="rgb(0, 0, 0)"&&m!=="rgba(0, 0, 0, 0)"&&!Ue(m)&&(a[m]=(a[m]||0)+1);let y=f.backgroundColor;y&&y!=="rgba(0, 0, 0, 0)"&&y!=="transparent"&&y!==o.bgColor&&!Ue(y)&&(a[y]=(a[y]||0)+1)}}let l=Object.keys(a).sort((c,g)=>a[g]-a[c]);o.primaryColor=l[0]||"",o.accentColors=l.slice(0,5)}catch(r){}return o}var pt=`
3
3
  .max-widget-container{position:fixed;bottom:20px;z-index:999999;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
4
4
  .max-widget-container.right{right:20px}
5
5
  .max-widget-container.left{left:20px}
@@ -39,6 +39,6 @@
39
39
  .max-widget-drag-handle:hover::after{background:rgba(255,255,255,0.35)}
40
40
  .max-widget-drag-handle.dragging{cursor:grabbing!important}
41
41
  .max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
42
- `,ut='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var gt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',mt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Ne(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function De(n,e){let t=Ne(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function T(n,e){let t=Ne(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ft(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ke(n,e,t,i){let s=vt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=De(s,.08),l=De(s,-.06);r.style.background=`linear-gradient(180deg, ${T(a,.96)}, ${T(l,.92)})`,r.style.border=`1px solid ${T(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${T(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${T(s,.55)}, ${T(s,.4)})`,r.style.border=`1px solid ${T(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function vt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ft(n):"":""}function Be(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=pt,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let h=document.createElement("div");h.className="max-widget-drag-handle",l.appendChild(h);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=ut,a.appendChild(p);let y=!1,m=!1,b=!1,se=0,re=0,J=0,V=0;function k(d,u){let v=window.innerWidth-a.offsetWidth,te=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(v,d))+"px",a.style.top=Math.max(0,Math.min(te,u))+"px",a.style.bottom="auto",a.style.right="auto"}function oe(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}Q()}function Q(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),v=u.top,te=window.innerHeight-u.bottom;v<d+8&&te>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function Je(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:v}=JSON.parse(d);typeof u=="number"&&typeof v=="number"&&k(u,v)}catch(d){}}Je(),Q(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,se=d.clientX,re=d.clientY;let u=a.getBoundingClientRect();J=u.left,V=u.top,k(J,V),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-se,v=d.clientY-re;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&k(J+u,V+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,oe(),m=!1))});let C=!1,E=!1,ae=0,le=0,Z=0,ee=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,E=!1,ae=d.clientX,le=d.clientY;let u=a.getBoundingClientRect();Z=u.left,ee=u.top,k(Z,ee),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-ae,v=d.clientY-le;!E&&(Math.abs(u)>4||Math.abs(v)>4)&&(E=!0,h.classList.add("dragging")),E&&k(Z+u,ee+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),E&&(oe(),E=!1))});let S=document.createElement("button");S.className="max-widget-tab "+(t?"right":"left"),S.style.backgroundColor=i,S.innerHTML=t?gt:mt,document.body.appendChild(S);let de=!1;function Ve(){de=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),S.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(de){Ve();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(Q(),l.classList.add("open"),o.onOpen())}),S.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),S.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:S,style:r}}function We(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function $e(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Xe(n){n.container.remove(),n.tab.remove(),n.style.remove()}function qe(n){n.shell.classList.add("open")}function ze(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var F=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=z(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:f({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(O(f({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var j=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(O(f({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Fe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function bt(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let h=(o=a[l].innerText)==null?void 0:o.trim();h&&(r+=h+`
42
+ `,ut='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var gt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',mt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Ne(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function De(n,e){let t=Ne(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function T(n,e){let t=Ne(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ft(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ke(n,e,t,i){let s=vt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=De(s,.08),l=De(s,-.06);r.style.background=`linear-gradient(180deg, ${T(a,.96)}, ${T(l,.92)})`,r.style.border=`1px solid ${T(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${T(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${T(s,.55)}, ${T(s,.4)})`,r.style.border=`1px solid ${T(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function vt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ft(n):"":""}function Be(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=pt,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let c=document.createElement("div");c.className="max-widget-drag-handle",l.appendChild(c);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=ut,a.appendChild(p);let f=!1,m=!1,y=!1,re=0,oe=0,J=0,Q=0;function k(d,u){let b=window.innerWidth-a.offsetWidth,ne=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(b,d))+"px",a.style.top=Math.max(0,Math.min(ne,u))+"px",a.style.bottom="auto",a.style.right="auto"}function ae(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}Z()}function Z(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),b=u.top,ne=window.innerHeight-u.bottom;b<d+8&&ne>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function Ve(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:b}=JSON.parse(d);typeof u=="number"&&typeof b=="number"&&k(u,b)}catch(d){}}Ve(),Z(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;f=!0,m=!1,re=d.clientX,oe=d.clientY;let u=a.getBoundingClientRect();J=u.left,Q=u.top,k(J,Q),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!f)return;let u=d.clientX-re,b=d.clientY-oe;!m&&(Math.abs(u)>4||Math.abs(b)>4)&&(m=!0,p.classList.add("dragging")),m&&k(J+u,Q+b)}),p.addEventListener("pointerup",()=>{f&&(f=!1,p.classList.remove("dragging"),m&&(y=!0,ae(),m=!1))});let C=!1,E=!1,le=0,de=0,ee=0,te=0;c.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,E=!1,le=d.clientX,de=d.clientY;let u=a.getBoundingClientRect();ee=u.left,te=u.top,k(ee,te),c.setPointerCapture(d.pointerId),d.preventDefault()}),c.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-le,b=d.clientY-de;!E&&(Math.abs(u)>4||Math.abs(b)>4)&&(E=!0,c.classList.add("dragging")),E&&k(ee+u,te+b)}),c.addEventListener("pointerup",()=>{C&&(C=!1,c.classList.remove("dragging"),E&&(ae(),E=!1))});let S=document.createElement("button");S.className="max-widget-tab "+(t?"right":"left"),S.style.backgroundColor=i,S.innerHTML=t?gt:mt,document.body.appendChild(S);let ce=!1;function Je(){ce=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),S.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(y){y=!1;return}if(ce){Je();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(Z(),l.classList.add("open"),o.onOpen())}),S.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),S.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:S,style:r}}function We(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function $e(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Xe(n){n.container.remove(),n.tab.remove(),n.style.remove()}function qe(n){n.shell.classList.add("open")}function ze(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var j=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=F(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:v({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(O(v({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var Y=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(O(v({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Fe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function bt(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let c=(o=a[l].innerText)==null?void 0:o.trim();c&&(r+=c+`
43
43
  `)}if(r.length>e.join(" ").length)return Fe(r.trim(),3e3)}return Fe(e.join(`
44
- `),3e3)}function I(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new M(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{var a;if(s.markReady(),e.config&&s.send(P,{features:e.config}),o(),(a=e.config)!=null&&a.autoTheme){let l=x();s.send(w,{styles:l})}}),s.listen(K,()=>{s.send(_,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(N,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(B,()=>{}),s.listen(U,()=>{o()}),s.listen(D,()=>{let a=x();s.send(w,{styles:a})}),n.appendChild(i);function o(){let a=bt(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(R,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function je(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=I(i,n);s&&t.push(s)}),t}function Ye(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),I(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>I(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var Y=class{constructor(e){this.emitter=new A;this.debug=new $;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new M(this.baseUrl),this.tools=new W(this.transport),this.pointAndAsk=new X(this.transport),this.spaDetector=new q(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=Be(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?x().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(P,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=je(t),this.inlineObserver=Ye(t)}setupMessageHandlers(){this.transport.listen(ve,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(be,()=>{this.ui&&$e(this.ui)}),this.transport.listen(ye,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(xe,()=>{this.pointAndAsk.start()}),this.transport.listen(Se,()=>{this.pointAndAsk.stop()}),this.transport.listen(we,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(Te,()=>{this.transport.send(fe,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(D,()=>{let e=x();this.applyTheme(e.primaryColor),this.transport.send(w,{styles:e})}),this.transport.listen(Ee,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=x();this.applyTheme(s.primaryColor),this.transport.send(w,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(Me,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(ke,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(_e,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(K,()=>{this.transport.send(_,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(N,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(B,()=>{this.clearSessionToken()}),this.transport.listen(Ie,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(Ce,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Le,{text:e})})}startIntelligence(e){this.presence||(this.presence=new F({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new j({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ke(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=He(this.key),t=Pe(e,this.explicitContext);this.transport.send(R,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=z();this.transport.send(Ae,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(_,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=I(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Oe,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(qe(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&(ze(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Xe(this.ui),this.ui=null}};var c=null,ie={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new Y(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&ie.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=ie);return rt(yt);})();
44
+ `),3e3)}function I(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new M(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{var l;if(s.markReady(),e.config&&s.send(P,{features:e.config}),r(),(l=e.config)!=null&&l.autoTheme){let c=x();s.send(w,{styles:c})}e.tools.hasTools()&&o()}),s.listen(B,()=>{s.send(_,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(K,l=>{l.sessionToken&&e.onSessionUpdate(l.sessionToken)}),s.listen(W,()=>{}),s.listen(U,()=>{r()}),s.listen(N,()=>{let l=x();s.send(w,{styles:l})}),s.listen("max-widget:request-tools",()=>{o()}),s.listen(D,l=>{let c=l.toolCallId,g=l.slug||l.name,p=l.args;e.tools.execute(c,g,p).then(f=>{s.send("max-widget:tool-result",{toolCallId:c,ok:f.ok,error:f.error})})}),n.appendChild(i);function o(){e.tools.sendListVia(s)}function r(){let l=bt(n),c={url:window.location.href,title:document.title||"",mainContent:l,customContext:{inline_mode:"true",content_above:l},lang:document.documentElement.lang||""},g=n.attributes;for(let p=0;p<g.length;p++){let f=g[p].name;if(f.startsWith("data-context-")){let m=f.replace("data-context-","").replace(/-/g,"_");c.customContext||(c.customContext={}),c.customContext[m]=g[p].value}}s.send(R,{context:c})}function a(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:a}}function je(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=I(i,n);s&&t.push(s)}),t}function Ye(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),I(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>I(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var V=class{constructor(e){this.emitter=new A;this.debug=new X;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new M(this.baseUrl),this.tools=new $(this.transport),this.pointAndAsk=new q(this.transport),this.spaDetector=new z(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=Be(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?x().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(P,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=je(t),this.inlineObserver=Ye(t)}setupMessageHandlers(){this.transport.listen(be,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ye,()=>{this.ui&&$e(this.ui)}),this.transport.listen(xe,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(Se,()=>{this.pointAndAsk.start()}),this.transport.listen(we,()=>{this.pointAndAsk.stop()}),this.transport.listen(D,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(Te,()=>{this.transport.send(ve,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(N,()=>{let e=x();this.applyTheme(e.primaryColor),this.transport.send(w,{styles:e})}),this.transport.listen(Ee,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=x();this.applyTheme(s.primaryColor),this.transport.send(w,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(Me,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(ke,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(_e,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(B,()=>{this.transport.send(_,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(K,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(W,()=>{this.clearSessionToken()}),this.transport.listen(Ie,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(Ce,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Le,{text:e})})}startIntelligence(e){this.presence||(this.presence=new j({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new Y({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ke(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=He(this.key),t=Pe(e,this.explicitContext);this.transport.send(R,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=F();this.transport.send(Ae,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,tools:this.tools,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(_,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=I(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Oe,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(qe(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&(ze(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Xe(this.ui),this.ui=null}};var h=null,se={init(n){return h?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),h):(h=new V(n),h)},setPageContext(n){if(!h){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}h.setPageContext(n)},setIdentity(n){if(!h){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}h.setIdentity(n)},registerTool(n){return h?h.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){h&&h.unregisterTool(n)},on(n,e){return h?h.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return h?h.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){h==null||h.open()},close(){h==null||h.close()},destroy(){h==null||h.destroy(),h=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&se.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=se);return rt(yt);})();
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /* @maxaiagent/widget-sdk v1.1.0 | MIT License | maxaiagent.app */
2
- "use strict";var L=Object.defineProperty,Qe=Object.defineProperties,Ze=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyDescriptors,tt=Object.getOwnPropertyNames,ce=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var he=(n,e,t)=>e in n?L(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,f=(n,e)=>{for(var t in e||(e={}))pe.call(e,t)&&he(n,t,e[t]);if(ce)for(var t of ce(e))nt.call(e,t)&&he(n,t,e[t]);return n},O=(n,e)=>Qe(n,et(e));var it=(n,e)=>{for(var t in e)L(n,t,{get:e[t],enumerable:!0})},st=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tt(e))!pe.call(n,s)&&s!==t&&L(n,s,{get:()=>e[s],enumerable:!(i=Ze(e,s))||i.enumerable});return n};var rt=n=>st(L({},"__esModule",{value:!0}),n);var yt={};it(yt,{MaxAI:()=>ie});module.exports=rt(yt);var M=class{constructor(e){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=e}attach(e){this.iframe=e,this.boundListener=t=>this.onMessage(t),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let e of this.queue)this.sendRaw(e);this.queue=[]}send(e,t){let i=f({type:e},t);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(e,t){this.handlers.set(e,t)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(e){var t,i;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(i=(t=this.iframe)==null?void 0:t.contentWindow)==null||i.postMessage(e,this.baseUrl)}catch(s){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(e){return this.baseUrl}}onMessage(e){if(!e.data||!e.data.type||this.iframe&&e.source!==this.iframe.contentWindow||e.origin!==this.expectedOrigin())return;let t=this.handlers.get(e.data.type);t&&t(e.data)}};var A=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}emit(e,...t){var i;(i=this.listeners.get(e))==null||i.forEach(s=>{try{s(...t)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",ue="max-widget:register-tools",ge="max-widget:unregister-tool",G="max-widget:tool-result",me="max-widget:point-ask-result",H="max-widget:point-ask-cancel",w="max-widget:host-styles",fe="max-widget:debug-snapshot",P="max-widget:config-features";var ve="max-widget:expand",be="max-widget:hide",ye="max-widget:close",U="max-widget:request-page-context",xe="max-widget:start-point-ask",Se="max-widget:stop-point-ask",we="max-widget:execute-tool",Te="max-widget:request-debug-snapshot",D="max-widget:request-host-styles",Ee="max-widget:gdpr-consent",Me="max-widget:navigate",ke="max-widget:message",_e="max-widget:error";var N="max-widget:session-update",K="max-widget:session-request",_="max-widget:session-restore",B="max-widget:session-clear",Ie="max-widget:draft-save",Ce="max-widget:draft-request",Le="max-widget:draft-restore",Oe="max-widget:identity-set",Ae="max-widget:browser-metadata";var W=class{constructor(e){this.tools=new Map;this.transport=e}register(e){return!e.slug||!/^[a-z0-9_]+$/.test(e.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",e.slug),()=>{}):(this.tools.set(e.slug,{slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,handler:e.handler,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}),this.sendList(),()=>this.unregister(e.slug))}unregister(e){this.tools.has(e)&&(this.tools.delete(e),this.transport.send(ge,{slug:e}),this.sendList())}async execute(e,t,i){let s=this.tools.get(t);if(!(s!=null&&s.handler)){let o=`Tool "${t}" not found or has no handler`;return this.transport.send(G,{toolCallId:e,ok:!1,error:o}),{ok:!1,error:o}}try{let o=await s.handler(i);return this.transport.send(G,{toolCallId:e,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:t,args:i}})),{ok:!0}}catch(o){let r=o instanceof Error?o.message:"Tool execution failed";return this.transport.send(G,{toolCallId:e,ok:!1,error:r}),{ok:!1,error:r}}}sendList(){let e=Array.from(this.tools.values()).map(t=>({slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,requiresConfirmation:t.requiresConfirmation,category:t.category}));this.transport.send(ue,{tools:e})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Ge(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}var ot=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function at(n){let e=JSON.stringify(n);for(let t of ot)e=e.replace(t,"[REDACTED]");try{return JSON.parse(e)}catch(t){return n}}var $=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...t)=>{this.origConsole[e](...t);try{let i=t.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:e,message:Ge(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=e=>{this.errors.push({message:e.message||"",source:e.filename||"",line:e.lineno||0,col:e.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{this.errors.push({message:"Unhandled rejection: "+(e.reason?String(e.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(e=>{var t;for(let i of e.getEntries()){let s=i,o=(t=s.responseStatus)!=null?t:0;this.networkLog.push(f({method:"GET",url:Ge(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(e){}}}getSnapshot(){return at({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var e;if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];(e=this.perfObserver)==null||e.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function ne(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function lt(n){let e=[],t=n;for(;t&&t.nodeType===1;){let i=1,s=t.previousSibling;for(;s;)s.nodeType===1&&s.tagName===t.tagName&&i++,s=s.previousSibling;e.unshift(t.tagName.toLowerCase()+"["+i+"]"),t=t.parentElement}return"/"+e.join("/")}function dt(n){let e=n.tagName.toLowerCase();return!!(e==="input"||e==="textarea"||e==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var X=class{constructor(e){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=e}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=e=>this.onMouseMove(e),this.boundClick=e=>this.onClick(e),this.boundKey=e=>this.onKeyDown(e),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(H),this.cleanup())}onMouseMove(e){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);this.overlay.style.pointerEvents="auto",this.highlight(t)}onClick(e){if(e.preventDefault(),e.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);if(this.overlay.style.pointerEvents="auto",!t||dt(t)){this.transport.send(H),this.cleanup();return}let i={};for(let r of["class","id","href","src","alt","title","data-id","data-name"]){let a=t.getAttribute(r);a&&(i[r]=ne(a,200))}let s=t.parentElement?ne(t.parentElement.innerText,300):"",o={elementText:ne(t.innerText,500),elementTag:t.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:lt(t)};this.transport.send(me,o),this.cleanup()}onKeyDown(e){e.key==="Escape"&&(this.transport.send(H),this.cleanup())}highlight(e){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),e&&e!==document.body&&e!==document.documentElement?(e._prevOutline=e.style.outline,e._prevOffset=e.style.outlineOffset,e.style.outline="2px solid #6366f1",e.style.outlineOffset="2px",this.lastHighlighted=e):this.lastHighlighted=null}cleanup(){var e,t;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(t=(e=this.overlay)==null?void 0:e.parentNode)==null||t.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function ct(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function He(n){let e={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},t=document.querySelector('meta[name="description"]');t&&(e.description=t.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(e.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(e.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{e.jsonLd.push(JSON.parse(l.textContent||""))}catch(h){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(e.mainContent=ct(o.innerText,2e3));let r=document.querySelector(`script[data-key="${n}"]`);return r&&Array.from(r.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");e.customContext[l]=a.value}}),e}function Pe(n,e){if(!e)return n;let t=f({},n);return e.pageType&&(t.pageType=e.pageType),e.visibleData&&(t.visibleData=e.visibleData),e.customContext&&(t.customContext=f(f({},t.customContext),e.customContext)),t}var q=class{constructor(e){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=e,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let e=this.origPush,t=this.origReplace,i=()=>this.checkChange();history.pushState=function(...o){e.apply(this,o),i()},history.replaceState=function(...o){t.apply(this,o),i()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let s=document.querySelector("title");s&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(s,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var e;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(e=this.observer)==null||e.disconnect()}checkChange(){let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,setTimeout(this.onChange,200))}};function z(){return{userAgent:(navigator.userAgent||"").slice(0,256),language:navigator.language||"",platform:navigator.platform||"",screenWidth:screen.width||0,screenHeight:screen.height||0,devicePixelRatio:window.devicePixelRatio||1,timezone:ht(),touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,referrer:(document.referrer||"").slice(0,512)}}function ht(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch(n){return""}}function Ue(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return!0;let[t,i,s]=[+e[1],+e[2],+e[3]],o=Math.max(t,i,s),r=Math.min(t,i,s);return(o===0?0:(o-r)/o)<.15}function x(){let n=getComputedStyle(document.documentElement),e=getComputedStyle(document.body),t=e.backgroundColor||"",o={bgColor:!t||t==="rgba(0, 0, 0, 0)"||t==="transparent"?n.backgroundColor||"":t,fontFamily:e.fontFamily||"",textColor:e.color||"",primaryColor:"",accentColors:[]};try{let r=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],a={};for(let h of r){let g=document.querySelectorAll(h);for(let p=0;p<Math.min(g.length,10);p++){let y=getComputedStyle(g[p]),m=y.color;m&&m!==o.textColor&&m!=="rgb(0, 0, 0)"&&m!=="rgba(0, 0, 0, 0)"&&!Ue(m)&&(a[m]=(a[m]||0)+1);let b=y.backgroundColor;b&&b!=="rgba(0, 0, 0, 0)"&&b!=="transparent"&&b!==o.bgColor&&!Ue(b)&&(a[b]=(a[b]||0)+1)}}let l=Object.keys(a).sort((h,g)=>a[g]-a[h]);o.primaryColor=l[0]||"",o.accentColors=l.slice(0,5)}catch(r){}return o}var pt=`
2
+ "use strict";var L=Object.defineProperty,Qe=Object.defineProperties,Ze=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyDescriptors,tt=Object.getOwnPropertyNames,he=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var pe=(n,e,t)=>e in n?L(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,v=(n,e)=>{for(var t in e||(e={}))ue.call(e,t)&&pe(n,t,e[t]);if(he)for(var t of he(e))nt.call(e,t)&&pe(n,t,e[t]);return n},O=(n,e)=>Qe(n,et(e));var it=(n,e)=>{for(var t in e)L(n,t,{get:e[t],enumerable:!0})},st=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tt(e))!ue.call(n,s)&&s!==t&&L(n,s,{get:()=>e[s],enumerable:!(i=Ze(e,s))||i.enumerable});return n};var rt=n=>st(L({},"__esModule",{value:!0}),n);var yt={};it(yt,{MaxAI:()=>se});module.exports=rt(yt);var M=class{constructor(e){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=e}attach(e){this.iframe=e,this.boundListener=t=>this.onMessage(t),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let e of this.queue)this.sendRaw(e);this.queue=[]}send(e,t){let i=v({type:e},t);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(e,t){this.handlers.set(e,t)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(e){var t,i;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(i=(t=this.iframe)==null?void 0:t.contentWindow)==null||i.postMessage(e,this.baseUrl)}catch(s){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(e){return this.baseUrl}}onMessage(e){if(!e.data||!e.data.type||this.iframe&&e.source!==this.iframe.contentWindow||e.origin!==this.expectedOrigin())return;let t=this.handlers.get(e.data.type);t&&t(e.data)}};var A=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}emit(e,...t){var i;(i=this.listeners.get(e))==null||i.forEach(s=>{try{s(...t)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",ge="max-widget:register-tools",me="max-widget:unregister-tool",G="max-widget:tool-result",fe="max-widget:point-ask-result",H="max-widget:point-ask-cancel",w="max-widget:host-styles",ve="max-widget:debug-snapshot",P="max-widget:config-features";var be="max-widget:expand",ye="max-widget:hide",xe="max-widget:close",U="max-widget:request-page-context",Se="max-widget:start-point-ask",we="max-widget:stop-point-ask",D="max-widget:execute-tool",Te="max-widget:request-debug-snapshot",N="max-widget:request-host-styles",Ee="max-widget:gdpr-consent",Me="max-widget:navigate",ke="max-widget:message",_e="max-widget:error";var K="max-widget:session-update",B="max-widget:session-request",_="max-widget:session-restore",W="max-widget:session-clear",Ie="max-widget:draft-save",Ce="max-widget:draft-request",Le="max-widget:draft-restore",Oe="max-widget:identity-set",Ae="max-widget:browser-metadata";var $=class{constructor(e){this.tools=new Map;this.transport=e}register(e){return!e.slug||!/^[a-z0-9_]+$/.test(e.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",e.slug),()=>{}):(this.tools.set(e.slug,{slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,handler:e.handler,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}),this.sendList(),()=>this.unregister(e.slug))}unregister(e){this.tools.has(e)&&(this.tools.delete(e),this.transport.send(me,{slug:e}),this.sendList())}async execute(e,t,i){let s=this.tools.get(t);if(!(s!=null&&s.handler)){let o=`Tool "${t}" not found or has no handler`;return this.transport.send(G,{toolCallId:e,ok:!1,error:o}),{ok:!1,error:o}}try{let o=await s.handler(i);return this.transport.send(G,{toolCallId:e,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:t,args:i}})),{ok:!0}}catch(o){let r=o instanceof Error?o.message:"Tool execution failed";return this.transport.send(G,{toolCallId:e,ok:!1,error:r}),{ok:!1,error:r}}}sendList(){this.sendListVia(this.transport)}sendListVia(e){let t=Array.from(this.tools.values()).map(i=>({slug:i.slug,name:i.name,description:i.description,schema:i.schema,context:i.context,requiresConfirmation:i.requiresConfirmation,category:i.category}));e.send(ge,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Ge(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}var ot=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function at(n){let e=JSON.stringify(n);for(let t of ot)e=e.replace(t,"[REDACTED]");try{return JSON.parse(e)}catch(t){return n}}var X=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...t)=>{this.origConsole[e](...t);try{let i=t.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:e,message:Ge(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=e=>{this.errors.push({message:e.message||"",source:e.filename||"",line:e.lineno||0,col:e.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{this.errors.push({message:"Unhandled rejection: "+(e.reason?String(e.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(e=>{var t;for(let i of e.getEntries()){let s=i,o=(t=s.responseStatus)!=null?t:0;this.networkLog.push(v({method:"GET",url:Ge(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(e){}}}getSnapshot(){return at({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var e;if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];(e=this.perfObserver)==null||e.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function ie(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function lt(n){let e=[],t=n;for(;t&&t.nodeType===1;){let i=1,s=t.previousSibling;for(;s;)s.nodeType===1&&s.tagName===t.tagName&&i++,s=s.previousSibling;e.unshift(t.tagName.toLowerCase()+"["+i+"]"),t=t.parentElement}return"/"+e.join("/")}function dt(n){let e=n.tagName.toLowerCase();return!!(e==="input"||e==="textarea"||e==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var q=class{constructor(e){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=e}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=e=>this.onMouseMove(e),this.boundClick=e=>this.onClick(e),this.boundKey=e=>this.onKeyDown(e),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(H),this.cleanup())}onMouseMove(e){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);this.overlay.style.pointerEvents="auto",this.highlight(t)}onClick(e){if(e.preventDefault(),e.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);if(this.overlay.style.pointerEvents="auto",!t||dt(t)){this.transport.send(H),this.cleanup();return}let i={};for(let r of["class","id","href","src","alt","title","data-id","data-name"]){let a=t.getAttribute(r);a&&(i[r]=ie(a,200))}let s=t.parentElement?ie(t.parentElement.innerText,300):"",o={elementText:ie(t.innerText,500),elementTag:t.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:lt(t)};this.transport.send(fe,o),this.cleanup()}onKeyDown(e){e.key==="Escape"&&(this.transport.send(H),this.cleanup())}highlight(e){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),e&&e!==document.body&&e!==document.documentElement?(e._prevOutline=e.style.outline,e._prevOffset=e.style.outlineOffset,e.style.outline="2px solid #6366f1",e.style.outlineOffset="2px",this.lastHighlighted=e):this.lastHighlighted=null}cleanup(){var e,t;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(t=(e=this.overlay)==null?void 0:e.parentNode)==null||t.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function ct(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function He(n){let e={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},t=document.querySelector('meta[name="description"]');t&&(e.description=t.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(e.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(e.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{e.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(e.mainContent=ct(o.innerText,2e3));let r=document.querySelector(`script[data-key="${n}"]`);return r&&Array.from(r.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");e.customContext[l]=a.value}}),e}function Pe(n,e){if(!e)return n;let t=v({},n);return e.pageType&&(t.pageType=e.pageType),e.visibleData&&(t.visibleData=e.visibleData),e.customContext&&(t.customContext=v(v({},t.customContext),e.customContext)),t}var z=class{constructor(e){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=e,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let e=this.origPush,t=this.origReplace,i=()=>this.checkChange();history.pushState=function(...o){e.apply(this,o),i()},history.replaceState=function(...o){t.apply(this,o),i()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let s=document.querySelector("title");s&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(s,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var e;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(e=this.observer)==null||e.disconnect()}checkChange(){let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,setTimeout(this.onChange,200))}};function F(){return{userAgent:(navigator.userAgent||"").slice(0,256),language:navigator.language||"",platform:navigator.platform||"",screenWidth:screen.width||0,screenHeight:screen.height||0,devicePixelRatio:window.devicePixelRatio||1,timezone:ht(),touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,referrer:(document.referrer||"").slice(0,512)}}function ht(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch(n){return""}}function Ue(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return!0;let[t,i,s]=[+e[1],+e[2],+e[3]],o=Math.max(t,i,s),r=Math.min(t,i,s);return(o===0?0:(o-r)/o)<.15}function x(){let n=getComputedStyle(document.documentElement),e=getComputedStyle(document.body),t=e.backgroundColor||"",o={bgColor:!t||t==="rgba(0, 0, 0, 0)"||t==="transparent"?n.backgroundColor||"":t,fontFamily:e.fontFamily||"",textColor:e.color||"",primaryColor:"",accentColors:[]};try{let r=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],a={};for(let c of r){let g=document.querySelectorAll(c);for(let p=0;p<Math.min(g.length,10);p++){let f=getComputedStyle(g[p]),m=f.color;m&&m!==o.textColor&&m!=="rgb(0, 0, 0)"&&m!=="rgba(0, 0, 0, 0)"&&!Ue(m)&&(a[m]=(a[m]||0)+1);let y=f.backgroundColor;y&&y!=="rgba(0, 0, 0, 0)"&&y!=="transparent"&&y!==o.bgColor&&!Ue(y)&&(a[y]=(a[y]||0)+1)}}let l=Object.keys(a).sort((c,g)=>a[g]-a[c]);o.primaryColor=l[0]||"",o.accentColors=l.slice(0,5)}catch(r){}return o}var pt=`
3
3
  .max-widget-container{position:fixed;bottom:20px;z-index:999999;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
4
4
  .max-widget-container.right{right:20px}
5
5
  .max-widget-container.left{left:20px}
@@ -39,6 +39,6 @@
39
39
  .max-widget-drag-handle:hover::after{background:rgba(255,255,255,0.35)}
40
40
  .max-widget-drag-handle.dragging{cursor:grabbing!important}
41
41
  .max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
42
- `,ut='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var gt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',mt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Ne(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function De(n,e){let t=Ne(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function T(n,e){let t=Ne(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ft(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ke(n,e,t,i){let s=vt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=De(s,.08),l=De(s,-.06);r.style.background=`linear-gradient(180deg, ${T(a,.96)}, ${T(l,.92)})`,r.style.border=`1px solid ${T(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${T(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${T(s,.55)}, ${T(s,.4)})`,r.style.border=`1px solid ${T(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function vt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ft(n):"":""}function Be(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=pt,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let h=document.createElement("div");h.className="max-widget-drag-handle",l.appendChild(h);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=ut,a.appendChild(p);let y=!1,m=!1,b=!1,se=0,re=0,J=0,V=0;function k(d,u){let v=window.innerWidth-a.offsetWidth,te=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(v,d))+"px",a.style.top=Math.max(0,Math.min(te,u))+"px",a.style.bottom="auto",a.style.right="auto"}function oe(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}Q()}function Q(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),v=u.top,te=window.innerHeight-u.bottom;v<d+8&&te>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function Je(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:v}=JSON.parse(d);typeof u=="number"&&typeof v=="number"&&k(u,v)}catch(d){}}Je(),Q(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,se=d.clientX,re=d.clientY;let u=a.getBoundingClientRect();J=u.left,V=u.top,k(J,V),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-se,v=d.clientY-re;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&k(J+u,V+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,oe(),m=!1))});let C=!1,E=!1,ae=0,le=0,Z=0,ee=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,E=!1,ae=d.clientX,le=d.clientY;let u=a.getBoundingClientRect();Z=u.left,ee=u.top,k(Z,ee),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-ae,v=d.clientY-le;!E&&(Math.abs(u)>4||Math.abs(v)>4)&&(E=!0,h.classList.add("dragging")),E&&k(Z+u,ee+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),E&&(oe(),E=!1))});let S=document.createElement("button");S.className="max-widget-tab "+(t?"right":"left"),S.style.backgroundColor=i,S.innerHTML=t?gt:mt,document.body.appendChild(S);let de=!1;function Ve(){de=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),S.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(de){Ve();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(Q(),l.classList.add("open"),o.onOpen())}),S.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),S.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:S,style:r}}function We(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function $e(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Xe(n){n.container.remove(),n.tab.remove(),n.style.remove()}function qe(n){n.shell.classList.add("open")}function ze(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var F=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=z(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:f({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(O(f({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var j=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(O(f({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Fe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function bt(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let h=(o=a[l].innerText)==null?void 0:o.trim();h&&(r+=h+`
42
+ `,ut='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var gt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',mt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Ne(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function De(n,e){let t=Ne(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function T(n,e){let t=Ne(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ft(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ke(n,e,t,i){let s=vt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=De(s,.08),l=De(s,-.06);r.style.background=`linear-gradient(180deg, ${T(a,.96)}, ${T(l,.92)})`,r.style.border=`1px solid ${T(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${T(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${T(s,.55)}, ${T(s,.4)})`,r.style.border=`1px solid ${T(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function vt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ft(n):"":""}function Be(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=pt,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let c=document.createElement("div");c.className="max-widget-drag-handle",l.appendChild(c);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=ut,a.appendChild(p);let f=!1,m=!1,y=!1,re=0,oe=0,J=0,Q=0;function k(d,u){let b=window.innerWidth-a.offsetWidth,ne=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(b,d))+"px",a.style.top=Math.max(0,Math.min(ne,u))+"px",a.style.bottom="auto",a.style.right="auto"}function ae(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}Z()}function Z(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),b=u.top,ne=window.innerHeight-u.bottom;b<d+8&&ne>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function Ve(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:b}=JSON.parse(d);typeof u=="number"&&typeof b=="number"&&k(u,b)}catch(d){}}Ve(),Z(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;f=!0,m=!1,re=d.clientX,oe=d.clientY;let u=a.getBoundingClientRect();J=u.left,Q=u.top,k(J,Q),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!f)return;let u=d.clientX-re,b=d.clientY-oe;!m&&(Math.abs(u)>4||Math.abs(b)>4)&&(m=!0,p.classList.add("dragging")),m&&k(J+u,Q+b)}),p.addEventListener("pointerup",()=>{f&&(f=!1,p.classList.remove("dragging"),m&&(y=!0,ae(),m=!1))});let C=!1,E=!1,le=0,de=0,ee=0,te=0;c.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,E=!1,le=d.clientX,de=d.clientY;let u=a.getBoundingClientRect();ee=u.left,te=u.top,k(ee,te),c.setPointerCapture(d.pointerId),d.preventDefault()}),c.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-le,b=d.clientY-de;!E&&(Math.abs(u)>4||Math.abs(b)>4)&&(E=!0,c.classList.add("dragging")),E&&k(ee+u,te+b)}),c.addEventListener("pointerup",()=>{C&&(C=!1,c.classList.remove("dragging"),E&&(ae(),E=!1))});let S=document.createElement("button");S.className="max-widget-tab "+(t?"right":"left"),S.style.backgroundColor=i,S.innerHTML=t?gt:mt,document.body.appendChild(S);let ce=!1;function Je(){ce=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),S.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(y){y=!1;return}if(ce){Je();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(Z(),l.classList.add("open"),o.onOpen())}),S.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),S.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:S,style:r}}function We(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function $e(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Xe(n){n.container.remove(),n.tab.remove(),n.style.remove()}function qe(n){n.shell.classList.add("open")}function ze(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var j=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=F(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:v({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(O(v({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var Y=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(O(v({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Fe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function bt(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let c=(o=a[l].innerText)==null?void 0:o.trim();c&&(r+=c+`
43
43
  `)}if(r.length>e.join(" ").length)return Fe(r.trim(),3e3)}return Fe(e.join(`
44
- `),3e3)}function I(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new M(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{var a;if(s.markReady(),e.config&&s.send(P,{features:e.config}),o(),(a=e.config)!=null&&a.autoTheme){let l=x();s.send(w,{styles:l})}}),s.listen(K,()=>{s.send(_,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(N,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(B,()=>{}),s.listen(U,()=>{o()}),s.listen(D,()=>{let a=x();s.send(w,{styles:a})}),n.appendChild(i);function o(){let a=bt(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(R,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function je(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=I(i,n);s&&t.push(s)}),t}function Ye(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),I(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>I(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var Y=class{constructor(e){this.emitter=new A;this.debug=new $;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new M(this.baseUrl),this.tools=new W(this.transport),this.pointAndAsk=new X(this.transport),this.spaDetector=new q(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=Be(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?x().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(P,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=je(t),this.inlineObserver=Ye(t)}setupMessageHandlers(){this.transport.listen(ve,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(be,()=>{this.ui&&$e(this.ui)}),this.transport.listen(ye,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(xe,()=>{this.pointAndAsk.start()}),this.transport.listen(Se,()=>{this.pointAndAsk.stop()}),this.transport.listen(we,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(Te,()=>{this.transport.send(fe,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(D,()=>{let e=x();this.applyTheme(e.primaryColor),this.transport.send(w,{styles:e})}),this.transport.listen(Ee,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=x();this.applyTheme(s.primaryColor),this.transport.send(w,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(Me,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(ke,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(_e,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(K,()=>{this.transport.send(_,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(N,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(B,()=>{this.clearSessionToken()}),this.transport.listen(Ie,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(Ce,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Le,{text:e})})}startIntelligence(e){this.presence||(this.presence=new F({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new j({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ke(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=He(this.key),t=Pe(e,this.explicitContext);this.transport.send(R,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=z();this.transport.send(Ae,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(_,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=I(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Oe,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(qe(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&(ze(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Xe(this.ui),this.ui=null}};var c=null,ie={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new Y(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&ie.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=ie);
44
+ `),3e3)}function I(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new M(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{var l;if(s.markReady(),e.config&&s.send(P,{features:e.config}),r(),(l=e.config)!=null&&l.autoTheme){let c=x();s.send(w,{styles:c})}e.tools.hasTools()&&o()}),s.listen(B,()=>{s.send(_,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(K,l=>{l.sessionToken&&e.onSessionUpdate(l.sessionToken)}),s.listen(W,()=>{}),s.listen(U,()=>{r()}),s.listen(N,()=>{let l=x();s.send(w,{styles:l})}),s.listen("max-widget:request-tools",()=>{o()}),s.listen(D,l=>{let c=l.toolCallId,g=l.slug||l.name,p=l.args;e.tools.execute(c,g,p).then(f=>{s.send("max-widget:tool-result",{toolCallId:c,ok:f.ok,error:f.error})})}),n.appendChild(i);function o(){e.tools.sendListVia(s)}function r(){let l=bt(n),c={url:window.location.href,title:document.title||"",mainContent:l,customContext:{inline_mode:"true",content_above:l},lang:document.documentElement.lang||""},g=n.attributes;for(let p=0;p<g.length;p++){let f=g[p].name;if(f.startsWith("data-context-")){let m=f.replace("data-context-","").replace(/-/g,"_");c.customContext||(c.customContext={}),c.customContext[m]=g[p].value}}s.send(R,{context:c})}function a(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:a}}function je(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=I(i,n);s&&t.push(s)}),t}function Ye(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),I(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>I(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var V=class{constructor(e){this.emitter=new A;this.debug=new X;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new M(this.baseUrl),this.tools=new $(this.transport),this.pointAndAsk=new q(this.transport),this.spaDetector=new z(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=Be(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?x().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(P,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=je(t),this.inlineObserver=Ye(t)}setupMessageHandlers(){this.transport.listen(be,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ye,()=>{this.ui&&$e(this.ui)}),this.transport.listen(xe,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(Se,()=>{this.pointAndAsk.start()}),this.transport.listen(we,()=>{this.pointAndAsk.stop()}),this.transport.listen(D,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(Te,()=>{this.transport.send(ve,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(N,()=>{let e=x();this.applyTheme(e.primaryColor),this.transport.send(w,{styles:e})}),this.transport.listen(Ee,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=x();this.applyTheme(s.primaryColor),this.transport.send(w,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(Me,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(ke,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(_e,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(B,()=>{this.transport.send(_,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(K,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(W,()=>{this.clearSessionToken()}),this.transport.listen(Ie,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(Ce,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Le,{text:e})})}startIntelligence(e){this.presence||(this.presence=new j({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new Y({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ke(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=He(this.key),t=Pe(e,this.explicitContext);this.transport.send(R,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=F();this.transport.send(Ae,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,tools:this.tools,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(_,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=I(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Oe,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(qe(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&(ze(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Xe(this.ui),this.ui=null}};var h=null,se={init(n){return h?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),h):(h=new V(n),h)},setPageContext(n){if(!h){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}h.setPageContext(n)},setIdentity(n){if(!h){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}h.setIdentity(n)},registerTool(n){return h?h.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){h&&h.unregisterTool(n)},on(n,e){return h?h.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return h?h.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){h==null||h.open()},close(){h==null||h.close()},destroy(){h==null||h.destroy(),h=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&se.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=se);
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /* @maxaiagent/widget-sdk v1.1.0 | MIT License | maxaiagent.app */
2
- var Je=Object.defineProperty,Ve=Object.defineProperties;var Qe=Object.getOwnPropertyDescriptors;var le=Object.getOwnPropertySymbols;var Ze=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var de=(n,e,t)=>e in n?Je(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,f=(n,e)=>{for(var t in e||(e={}))Ze.call(e,t)&&de(n,t,e[t]);if(le)for(var t of le(e))et.call(e,t)&&de(n,t,e[t]);return n},L=(n,e)=>Ve(n,Qe(e));var M=class{constructor(e){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=e}attach(e){this.iframe=e,this.boundListener=t=>this.onMessage(t),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let e of this.queue)this.sendRaw(e);this.queue=[]}send(e,t){let i=f({type:e},t);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(e,t){this.handlers.set(e,t)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(e){var t,i;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(i=(t=this.iframe)==null?void 0:t.contentWindow)==null||i.postMessage(e,this.baseUrl)}catch(s){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(e){return this.baseUrl}}onMessage(e){if(!e.data||!e.data.type||this.iframe&&e.source!==this.iframe.contentWindow||e.origin!==this.expectedOrigin())return;let t=this.handlers.get(e.data.type);t&&t(e.data)}};var O=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}emit(e,...t){var i;(i=this.listeners.get(e))==null||i.forEach(s=>{try{s(...t)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var A="max-widget:page-context",ce="max-widget:register-tools",he="max-widget:unregister-tool",R="max-widget:tool-result",pe="max-widget:point-ask-result",G="max-widget:point-ask-cancel",w="max-widget:host-styles",ue="max-widget:debug-snapshot",H="max-widget:config-features";var ge="max-widget:expand",me="max-widget:hide",fe="max-widget:close",P="max-widget:request-page-context",ve="max-widget:start-point-ask",be="max-widget:stop-point-ask",ye="max-widget:execute-tool",xe="max-widget:request-debug-snapshot",U="max-widget:request-host-styles",Se="max-widget:gdpr-consent",we="max-widget:navigate",Te="max-widget:message",Ee="max-widget:error";var D="max-widget:session-update",N="max-widget:session-request",_="max-widget:session-restore",K="max-widget:session-clear",Me="max-widget:draft-save",ke="max-widget:draft-request",_e="max-widget:draft-restore",Ie="max-widget:identity-set",Ce="max-widget:browser-metadata";var B=class{constructor(e){this.tools=new Map;this.transport=e}register(e){return!e.slug||!/^[a-z0-9_]+$/.test(e.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",e.slug),()=>{}):(this.tools.set(e.slug,{slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,handler:e.handler,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}),this.sendList(),()=>this.unregister(e.slug))}unregister(e){this.tools.has(e)&&(this.tools.delete(e),this.transport.send(he,{slug:e}),this.sendList())}async execute(e,t,i){let s=this.tools.get(t);if(!(s!=null&&s.handler)){let o=`Tool "${t}" not found or has no handler`;return this.transport.send(R,{toolCallId:e,ok:!1,error:o}),{ok:!1,error:o}}try{let o=await s.handler(i);return this.transport.send(R,{toolCallId:e,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:t,args:i}})),{ok:!0}}catch(o){let r=o instanceof Error?o.message:"Tool execution failed";return this.transport.send(R,{toolCallId:e,ok:!1,error:r}),{ok:!1,error:r}}}sendList(){let e=Array.from(this.tools.values()).map(t=>({slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,requiresConfirmation:t.requiresConfirmation,category:t.category}));this.transport.send(ce,{tools:e})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Oe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}var tt=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function nt(n){let e=JSON.stringify(n);for(let t of tt)e=e.replace(t,"[REDACTED]");try{return JSON.parse(e)}catch(t){return n}}var W=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...t)=>{this.origConsole[e](...t);try{let i=t.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:e,message:Oe(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=e=>{this.errors.push({message:e.message||"",source:e.filename||"",line:e.lineno||0,col:e.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{this.errors.push({message:"Unhandled rejection: "+(e.reason?String(e.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(e=>{var t;for(let i of e.getEntries()){let s=i,o=(t=s.responseStatus)!=null?t:0;this.networkLog.push(f({method:"GET",url:Oe(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(e){}}}getSnapshot(){return nt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var e;if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];(e=this.perfObserver)==null||e.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function te(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function it(n){let e=[],t=n;for(;t&&t.nodeType===1;){let i=1,s=t.previousSibling;for(;s;)s.nodeType===1&&s.tagName===t.tagName&&i++,s=s.previousSibling;e.unshift(t.tagName.toLowerCase()+"["+i+"]"),t=t.parentElement}return"/"+e.join("/")}function st(n){let e=n.tagName.toLowerCase();return!!(e==="input"||e==="textarea"||e==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var $=class{constructor(e){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=e}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=e=>this.onMouseMove(e),this.boundClick=e=>this.onClick(e),this.boundKey=e=>this.onKeyDown(e),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(G),this.cleanup())}onMouseMove(e){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);this.overlay.style.pointerEvents="auto",this.highlight(t)}onClick(e){if(e.preventDefault(),e.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);if(this.overlay.style.pointerEvents="auto",!t||st(t)){this.transport.send(G),this.cleanup();return}let i={};for(let r of["class","id","href","src","alt","title","data-id","data-name"]){let a=t.getAttribute(r);a&&(i[r]=te(a,200))}let s=t.parentElement?te(t.parentElement.innerText,300):"",o={elementText:te(t.innerText,500),elementTag:t.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:it(t)};this.transport.send(pe,o),this.cleanup()}onKeyDown(e){e.key==="Escape"&&(this.transport.send(G),this.cleanup())}highlight(e){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),e&&e!==document.body&&e!==document.documentElement?(e._prevOutline=e.style.outline,e._prevOffset=e.style.outlineOffset,e.style.outline="2px solid #6366f1",e.style.outlineOffset="2px",this.lastHighlighted=e):this.lastHighlighted=null}cleanup(){var e,t;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(t=(e=this.overlay)==null?void 0:e.parentNode)==null||t.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function rt(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function Ae(n){let e={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},t=document.querySelector('meta[name="description"]');t&&(e.description=t.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(e.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(e.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{e.jsonLd.push(JSON.parse(l.textContent||""))}catch(h){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(e.mainContent=rt(o.innerText,2e3));let r=document.querySelector(`script[data-key="${n}"]`);return r&&Array.from(r.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");e.customContext[l]=a.value}}),e}function Re(n,e){if(!e)return n;let t=f({},n);return e.pageType&&(t.pageType=e.pageType),e.visibleData&&(t.visibleData=e.visibleData),e.customContext&&(t.customContext=f(f({},t.customContext),e.customContext)),t}var X=class{constructor(e){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=e,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let e=this.origPush,t=this.origReplace,i=()=>this.checkChange();history.pushState=function(...o){e.apply(this,o),i()},history.replaceState=function(...o){t.apply(this,o),i()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let s=document.querySelector("title");s&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(s,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var e;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(e=this.observer)==null||e.disconnect()}checkChange(){let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,setTimeout(this.onChange,200))}};function q(){return{userAgent:(navigator.userAgent||"").slice(0,256),language:navigator.language||"",platform:navigator.platform||"",screenWidth:screen.width||0,screenHeight:screen.height||0,devicePixelRatio:window.devicePixelRatio||1,timezone:ot(),touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,referrer:(document.referrer||"").slice(0,512)}}function ot(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch(n){return""}}function Ge(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return!0;let[t,i,s]=[+e[1],+e[2],+e[3]],o=Math.max(t,i,s),r=Math.min(t,i,s);return(o===0?0:(o-r)/o)<.15}function x(){let n=getComputedStyle(document.documentElement),e=getComputedStyle(document.body),t=e.backgroundColor||"",o={bgColor:!t||t==="rgba(0, 0, 0, 0)"||t==="transparent"?n.backgroundColor||"":t,fontFamily:e.fontFamily||"",textColor:e.color||"",primaryColor:"",accentColors:[]};try{let r=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],a={};for(let h of r){let g=document.querySelectorAll(h);for(let p=0;p<Math.min(g.length,10);p++){let y=getComputedStyle(g[p]),m=y.color;m&&m!==o.textColor&&m!=="rgb(0, 0, 0)"&&m!=="rgba(0, 0, 0, 0)"&&!Ge(m)&&(a[m]=(a[m]||0)+1);let b=y.backgroundColor;b&&b!=="rgba(0, 0, 0, 0)"&&b!=="transparent"&&b!==o.bgColor&&!Ge(b)&&(a[b]=(a[b]||0)+1)}}let l=Object.keys(a).sort((h,g)=>a[g]-a[h]);o.primaryColor=l[0]||"",o.accentColors=l.slice(0,5)}catch(r){}return o}var at=`
2
+ var Ve=Object.defineProperty,Je=Object.defineProperties;var Qe=Object.getOwnPropertyDescriptors;var de=Object.getOwnPropertySymbols;var Ze=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var ce=(n,e,t)=>e in n?Ve(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,v=(n,e)=>{for(var t in e||(e={}))Ze.call(e,t)&&ce(n,t,e[t]);if(de)for(var t of de(e))et.call(e,t)&&ce(n,t,e[t]);return n},L=(n,e)=>Je(n,Qe(e));var M=class{constructor(e){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=e}attach(e){this.iframe=e,this.boundListener=t=>this.onMessage(t),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let e of this.queue)this.sendRaw(e);this.queue=[]}send(e,t){let i=v({type:e},t);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}listen(e,t){this.handlers.set(e,t)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(e){var t,i;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(i=(t=this.iframe)==null?void 0:t.contentWindow)==null||i.postMessage(e,this.baseUrl)}catch(s){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(e){return this.baseUrl}}onMessage(e){if(!e.data||!e.data.type||this.iframe&&e.source!==this.iframe.contentWindow||e.origin!==this.expectedOrigin())return;let t=this.handlers.get(e.data.type);t&&t(e.data)}};var O=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}emit(e,...t){var i;(i=this.listeners.get(e))==null||i.forEach(s=>{try{s(...t)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var A="max-widget:page-context",he="max-widget:register-tools",pe="max-widget:unregister-tool",R="max-widget:tool-result",ue="max-widget:point-ask-result",G="max-widget:point-ask-cancel",w="max-widget:host-styles",ge="max-widget:debug-snapshot",H="max-widget:config-features";var me="max-widget:expand",fe="max-widget:hide",ve="max-widget:close",P="max-widget:request-page-context",be="max-widget:start-point-ask",ye="max-widget:stop-point-ask",U="max-widget:execute-tool",xe="max-widget:request-debug-snapshot",D="max-widget:request-host-styles",Se="max-widget:gdpr-consent",we="max-widget:navigate",Te="max-widget:message",Ee="max-widget:error";var N="max-widget:session-update",K="max-widget:session-request",_="max-widget:session-restore",B="max-widget:session-clear",Me="max-widget:draft-save",ke="max-widget:draft-request",_e="max-widget:draft-restore",Ie="max-widget:identity-set",Ce="max-widget:browser-metadata";var W=class{constructor(e){this.tools=new Map;this.transport=e}register(e){return!e.slug||!/^[a-z0-9_]+$/.test(e.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",e.slug),()=>{}):(this.tools.set(e.slug,{slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,handler:e.handler,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}),this.sendList(),()=>this.unregister(e.slug))}unregister(e){this.tools.has(e)&&(this.tools.delete(e),this.transport.send(pe,{slug:e}),this.sendList())}async execute(e,t,i){let s=this.tools.get(t);if(!(s!=null&&s.handler)){let o=`Tool "${t}" not found or has no handler`;return this.transport.send(R,{toolCallId:e,ok:!1,error:o}),{ok:!1,error:o}}try{let o=await s.handler(i);return this.transport.send(R,{toolCallId:e,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:t,args:i}})),{ok:!0}}catch(o){let r=o instanceof Error?o.message:"Tool execution failed";return this.transport.send(R,{toolCallId:e,ok:!1,error:r}),{ok:!1,error:r}}}sendList(){this.sendListVia(this.transport)}sendListVia(e){let t=Array.from(this.tools.values()).map(i=>({slug:i.slug,name:i.name,description:i.description,schema:i.schema,context:i.context,requiresConfirmation:i.requiresConfirmation,category:i.category}));e.send(he,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Oe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}var tt=[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/token=[A-Za-z0-9\-._~+/]+=*/g,/password["'\s:=]+["']?[^\s"',}]*/gi,/api[_-]?key["'\s:=]+["']?[A-Za-z0-9\-._~+/]*/gi,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g];function nt(n){let e=JSON.stringify(n);for(let t of tt)e=e.replace(t,"[REDACTED]");try{return JSON.parse(e)}catch(t){return n}}var $=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.errorHandler=null;this.rejectionHandler=null;this.perfObserver=null;this.initialized=!1}init(){if(!this.initialized){this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...t)=>{this.origConsole[e](...t);try{let i=t.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:e,message:Oe(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};this.errorHandler=e=>{this.errors.push({message:e.message||"",source:e.filename||"",line:e.lineno||0,col:e.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{this.errors.push({message:"Unhandled rejection: "+(e.reason?String(e.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(e=>{var t;for(let i of e.getEntries()){let s=i,o=(t=s.responseStatus)!=null?t:0;this.networkLog.push(v({method:"GET",url:Oe(s.name,200),status:o,duration:Math.round(s.duration),timestamp:Math.round(performance.timeOrigin+s.startTime)},o===0||o>=400?{error:o===0?"Network error or blocked":`HTTP ${o}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(e){}}}getSnapshot(){return nt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var e;if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];(e=this.perfObserver)==null||e.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function ne(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function it(n){let e=[],t=n;for(;t&&t.nodeType===1;){let i=1,s=t.previousSibling;for(;s;)s.nodeType===1&&s.tagName===t.tagName&&i++,s=s.previousSibling;e.unshift(t.tagName.toLowerCase()+"["+i+"]"),t=t.parentElement}return"/"+e.join("/")}function st(n){let e=n.tagName.toLowerCase();return!!(e==="input"||e==="textarea"||e==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var X=class{constructor(e){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=e}start(){this.active||(this.active=!0,this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;inset:0;z-index:999998;cursor:crosshair;background:transparent;",document.body.appendChild(this.overlay),this.boundMove=e=>this.onMouseMove(e),this.boundClick=e=>this.onClick(e),this.boundKey=e=>this.onKeyDown(e),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(G),this.cleanup())}onMouseMove(e){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);this.overlay.style.pointerEvents="auto",this.highlight(t)}onClick(e){if(e.preventDefault(),e.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let t=document.elementFromPoint(e.clientX,e.clientY);if(this.overlay.style.pointerEvents="auto",!t||st(t)){this.transport.send(G),this.cleanup();return}let i={};for(let r of["class","id","href","src","alt","title","data-id","data-name"]){let a=t.getAttribute(r);a&&(i[r]=ne(a,200))}let s=t.parentElement?ne(t.parentElement.innerText,300):"",o={elementText:ne(t.innerText,500),elementTag:t.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:it(t)};this.transport.send(ue,o),this.cleanup()}onKeyDown(e){e.key==="Escape"&&(this.transport.send(G),this.cleanup())}highlight(e){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),e&&e!==document.body&&e!==document.documentElement?(e._prevOutline=e.style.outline,e._prevOffset=e.style.outlineOffset,e.style.outline="2px solid #6366f1",e.style.outlineOffset="2px",this.lastHighlighted=e):this.lastHighlighted=null}cleanup(){var e,t;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(t=(e=this.overlay)==null?void 0:e.parentNode)==null||t.removeChild(this.overlay),this.overlay=null,this.boundMove&&document.removeEventListener("mousemove",this.boundMove,!0),this.boundClick&&document.removeEventListener("click",this.boundClick,!0),this.boundKey&&document.removeEventListener("keydown",this.boundKey,!0)}};function rt(n,e){return n?n.length>e?n.slice(0,e)+"\u2026":n:""}function Ae(n){let e={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},t=document.querySelector('meta[name="description"]');t&&(e.description=t.getAttribute("content")||"");let i=document.querySelector('meta[property="og:title"]');i&&(e.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(e.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{e.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(e.mainContent=rt(o.innerText,2e3));let r=document.querySelector(`script[data-key="${n}"]`);return r&&Array.from(r.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");e.customContext[l]=a.value}}),e}function Re(n,e){if(!e)return n;let t=v({},n);return e.pageType&&(t.pageType=e.pageType),e.visibleData&&(t.visibleData=e.visibleData),e.customContext&&(t.customContext=v(v({},t.customContext),e.customContext)),t}var q=class{constructor(e){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=e,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let e=this.origPush,t=this.origReplace,i=()=>this.checkChange();history.pushState=function(...o){e.apply(this,o),i()},history.replaceState=function(...o){t.apply(this,o),i()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let s=document.querySelector("title");s&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(s,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var e;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(e=this.observer)==null||e.disconnect()}checkChange(){let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,setTimeout(this.onChange,200))}};function z(){return{userAgent:(navigator.userAgent||"").slice(0,256),language:navigator.language||"",platform:navigator.platform||"",screenWidth:screen.width||0,screenHeight:screen.height||0,devicePixelRatio:window.devicePixelRatio||1,timezone:ot(),touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,referrer:(document.referrer||"").slice(0,512)}}function ot(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch(n){return""}}function Ge(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return!0;let[t,i,s]=[+e[1],+e[2],+e[3]],o=Math.max(t,i,s),r=Math.min(t,i,s);return(o===0?0:(o-r)/o)<.15}function x(){let n=getComputedStyle(document.documentElement),e=getComputedStyle(document.body),t=e.backgroundColor||"",o={bgColor:!t||t==="rgba(0, 0, 0, 0)"||t==="transparent"?n.backgroundColor||"":t,fontFamily:e.fontFamily||"",textColor:e.color||"",primaryColor:"",accentColors:[]};try{let r=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],a={};for(let c of r){let g=document.querySelectorAll(c);for(let p=0;p<Math.min(g.length,10);p++){let f=getComputedStyle(g[p]),m=f.color;m&&m!==o.textColor&&m!=="rgb(0, 0, 0)"&&m!=="rgba(0, 0, 0, 0)"&&!Ge(m)&&(a[m]=(a[m]||0)+1);let y=f.backgroundColor;y&&y!=="rgba(0, 0, 0, 0)"&&y!=="transparent"&&y!==o.bgColor&&!Ge(y)&&(a[y]=(a[y]||0)+1)}}let l=Object.keys(a).sort((c,g)=>a[g]-a[c]);o.primaryColor=l[0]||"",o.accentColors=l.slice(0,5)}catch(r){}return o}var at=`
3
3
  .max-widget-container{position:fixed;bottom:20px;z-index:999999;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
4
4
  .max-widget-container.right{right:20px}
5
5
  .max-widget-container.left{left:20px}
@@ -39,6 +39,6 @@ var Je=Object.defineProperty,Ve=Object.defineProperties;var Qe=Object.getOwnProp
39
39
  .max-widget-drag-handle:hover::after{background:rgba(255,255,255,0.35)}
40
40
  .max-widget-drag-handle.dragging{cursor:grabbing!important}
41
41
  .max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
42
- `,lt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var dt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',ct='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Pe(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function He(n,e){let t=Pe(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function T(n,e){let t=Pe(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ht(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ue(n,e,t,i){let s=pt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=He(s,.08),l=He(s,-.06);r.style.background=`linear-gradient(180deg, ${T(a,.96)}, ${T(l,.92)})`,r.style.border=`1px solid ${T(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${T(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${T(s,.55)}, ${T(s,.4)})`,r.style.border=`1px solid ${T(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function pt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ht(n):"":""}function De(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=at,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let h=document.createElement("div");h.className="max-widget-drag-handle",l.appendChild(h);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=lt,a.appendChild(p);let y=!1,m=!1,b=!1,ne=0,ie=0,Y=0,J=0;function k(d,u){let v=window.innerWidth-a.offsetWidth,ee=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(v,d))+"px",a.style.top=Math.max(0,Math.min(ee,u))+"px",a.style.bottom="auto",a.style.right="auto"}function se(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}V()}function V(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),v=u.top,ee=window.innerHeight-u.bottom;v<d+8&&ee>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function je(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:v}=JSON.parse(d);typeof u=="number"&&typeof v=="number"&&k(u,v)}catch(d){}}je(),V(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,ne=d.clientX,ie=d.clientY;let u=a.getBoundingClientRect();Y=u.left,J=u.top,k(Y,J),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-ne,v=d.clientY-ie;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&k(Y+u,J+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,se(),m=!1))});let C=!1,E=!1,re=0,oe=0,Q=0,Z=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,E=!1,re=d.clientX,oe=d.clientY;let u=a.getBoundingClientRect();Q=u.left,Z=u.top,k(Q,Z),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-re,v=d.clientY-oe;!E&&(Math.abs(u)>4||Math.abs(v)>4)&&(E=!0,h.classList.add("dragging")),E&&k(Q+u,Z+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),E&&(se(),E=!1))});let S=document.createElement("button");S.className="max-widget-tab "+(t?"right":"left"),S.style.backgroundColor=i,S.innerHTML=t?dt:ct,document.body.appendChild(S);let ae=!1;function Ye(){ae=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),S.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(ae){Ye();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(V(),l.classList.add("open"),o.onOpen())}),S.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),S.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:S,style:r}}function Ne(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function Ke(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Be(n){n.container.remove(),n.tab.remove(),n.style.remove()}function We(n){n.shell.classList.add("open")}function $e(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var z=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=q(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:f({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(L(f({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var F=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(L(f({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Xe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function ut(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let h=(o=a[l].innerText)==null?void 0:o.trim();h&&(r+=h+`
42
+ `,lt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var dt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',ct='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Pe(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function He(n,e){let t=Pe(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function T(n,e){let t=Pe(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ht(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ue(n,e,t,i){let s=pt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=He(s,.08),l=He(s,-.06);r.style.background=`linear-gradient(180deg, ${T(a,.96)}, ${T(l,.92)})`,r.style.border=`1px solid ${T(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${T(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${T(s,.55)}, ${T(s,.4)})`,r.style.border=`1px solid ${T(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function pt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ht(n):"":""}function De(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=at,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let c=document.createElement("div");c.className="max-widget-drag-handle",l.appendChild(c);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=lt,a.appendChild(p);let f=!1,m=!1,y=!1,ie=0,se=0,V=0,J=0;function k(d,u){let b=window.innerWidth-a.offsetWidth,te=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(b,d))+"px",a.style.top=Math.max(0,Math.min(te,u))+"px",a.style.bottom="auto",a.style.right="auto"}function re(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}Q()}function Q(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),b=u.top,te=window.innerHeight-u.bottom;b<d+8&&te>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function je(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:b}=JSON.parse(d);typeof u=="number"&&typeof b=="number"&&k(u,b)}catch(d){}}je(),Q(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;f=!0,m=!1,ie=d.clientX,se=d.clientY;let u=a.getBoundingClientRect();V=u.left,J=u.top,k(V,J),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!f)return;let u=d.clientX-ie,b=d.clientY-se;!m&&(Math.abs(u)>4||Math.abs(b)>4)&&(m=!0,p.classList.add("dragging")),m&&k(V+u,J+b)}),p.addEventListener("pointerup",()=>{f&&(f=!1,p.classList.remove("dragging"),m&&(y=!0,re(),m=!1))});let C=!1,E=!1,oe=0,ae=0,Z=0,ee=0;c.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,E=!1,oe=d.clientX,ae=d.clientY;let u=a.getBoundingClientRect();Z=u.left,ee=u.top,k(Z,ee),c.setPointerCapture(d.pointerId),d.preventDefault()}),c.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-oe,b=d.clientY-ae;!E&&(Math.abs(u)>4||Math.abs(b)>4)&&(E=!0,c.classList.add("dragging")),E&&k(Z+u,ee+b)}),c.addEventListener("pointerup",()=>{C&&(C=!1,c.classList.remove("dragging"),E&&(re(),E=!1))});let S=document.createElement("button");S.className="max-widget-tab "+(t?"right":"left"),S.style.backgroundColor=i,S.innerHTML=t?dt:ct,document.body.appendChild(S);let le=!1;function Ye(){le=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),S.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(y){y=!1;return}if(le){Ye();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(Q(),l.classList.add("open"),o.onOpen())}),S.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),S.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:S,style:r}}function Ne(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function Ke(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Be(n){n.container.remove(),n.tab.remove(),n.style.remove()}function We(n){n.shell.classList.add("open")}function $e(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var F=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=z(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:v({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(L(v({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var j=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(L(v({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Xe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function ut(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let c=(o=a[l].innerText)==null?void 0:o.trim();c&&(r+=c+`
43
43
  `)}if(r.length>e.join(" ").length)return Xe(r.trim(),3e3)}return Xe(e.join(`
44
- `),3e3)}function I(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new M(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{var a;if(s.markReady(),e.config&&s.send(H,{features:e.config}),o(),(a=e.config)!=null&&a.autoTheme){let l=x();s.send(w,{styles:l})}}),s.listen(N,()=>{s.send(_,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(D,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(K,()=>{}),s.listen(P,()=>{o()}),s.listen(U,()=>{let a=x();s.send(w,{styles:a})}),n.appendChild(i);function o(){let a=ut(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(A,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function qe(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=I(i,n);s&&t.push(s)}),t}function ze(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),I(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>I(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var j=class{constructor(e){this.emitter=new O;this.debug=new W;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new M(this.baseUrl),this.tools=new B(this.transport),this.pointAndAsk=new $(this.transport),this.spaDetector=new X(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=De(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?x().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(H,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=qe(t),this.inlineObserver=ze(t)}setupMessageHandlers(){this.transport.listen(ge,e=>{this.ui&&Ne(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(me,()=>{this.ui&&Ke(this.ui)}),this.transport.listen(fe,()=>{this.close()}),this.transport.listen(P,()=>{this.sendPageContext()}),this.transport.listen(ve,()=>{this.pointAndAsk.start()}),this.transport.listen(be,()=>{this.pointAndAsk.stop()}),this.transport.listen(ye,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(xe,()=>{this.transport.send(ue,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(U,()=>{let e=x();this.applyTheme(e.primaryColor),this.transport.send(w,{styles:e})}),this.transport.listen(Se,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=x();this.applyTheme(s.primaryColor),this.transport.send(w,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(we,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(Te,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(Ee,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(N,()=>{this.transport.send(_,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(D,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(K,()=>{this.clearSessionToken()}),this.transport.listen(Me,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(ke,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(_e,{text:e})})}startIntelligence(e){this.presence||(this.presence=new z({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new F({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ue(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=Ae(this.key),t=Re(e,this.explicitContext);this.transport.send(A,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=q();this.transport.send(Ce,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(_,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=I(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Ie,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(We(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&($e(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Be(this.ui),this.ui=null}};var c=null,Fe={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new j(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&Fe.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=Fe);export{Fe as MaxAI};
44
+ `),3e3)}function I(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new M(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{var l;if(s.markReady(),e.config&&s.send(H,{features:e.config}),r(),(l=e.config)!=null&&l.autoTheme){let c=x();s.send(w,{styles:c})}e.tools.hasTools()&&o()}),s.listen(K,()=>{s.send(_,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(N,l=>{l.sessionToken&&e.onSessionUpdate(l.sessionToken)}),s.listen(B,()=>{}),s.listen(P,()=>{r()}),s.listen(D,()=>{let l=x();s.send(w,{styles:l})}),s.listen("max-widget:request-tools",()=>{o()}),s.listen(U,l=>{let c=l.toolCallId,g=l.slug||l.name,p=l.args;e.tools.execute(c,g,p).then(f=>{s.send("max-widget:tool-result",{toolCallId:c,ok:f.ok,error:f.error})})}),n.appendChild(i);function o(){e.tools.sendListVia(s)}function r(){let l=ut(n),c={url:window.location.href,title:document.title||"",mainContent:l,customContext:{inline_mode:"true",content_above:l},lang:document.documentElement.lang||""},g=n.attributes;for(let p=0;p<g.length;p++){let f=g[p].name;if(f.startsWith("data-context-")){let m=f.replace("data-context-","").replace(/-/g,"_");c.customContext||(c.customContext={}),c.customContext[m]=g[p].value}}s.send(A,{context:c})}function a(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:a}}function qe(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=I(i,n);s&&t.push(s)}),t}function ze(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),I(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>I(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var Y=class{constructor(e){this.emitter=new O;this.debug=new $;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new M(this.baseUrl),this.tools=new W(this.transport),this.pointAndAsk=new X(this.transport),this.spaDetector=new q(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=De(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?x().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(H,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=x();this.applyTheme(r.primaryColor),this.transport.send(w,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=qe(t),this.inlineObserver=ze(t)}setupMessageHandlers(){this.transport.listen(me,e=>{this.ui&&Ne(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(fe,()=>{this.ui&&Ke(this.ui)}),this.transport.listen(ve,()=>{this.close()}),this.transport.listen(P,()=>{this.sendPageContext()}),this.transport.listen(be,()=>{this.pointAndAsk.start()}),this.transport.listen(ye,()=>{this.pointAndAsk.stop()}),this.transport.listen(U,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(xe,()=>{this.transport.send(ge,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(D,()=>{let e=x();this.applyTheme(e.primaryColor),this.transport.send(w,{styles:e})}),this.transport.listen(Se,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=x();this.applyTheme(s.primaryColor),this.transport.send(w,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(we,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(Te,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(Ee,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(K,()=>{this.transport.send(_,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(N,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(B,()=>{this.clearSessionToken()}),this.transport.listen(Me,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(ke,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(_e,{text:e})})}startIntelligence(e){this.presence||(this.presence=new F({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new j({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ue(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=Ae(this.key),t=Re(e,this.explicitContext);this.transport.send(A,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=z();this.transport.send(Ce,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,tools:this.tools,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(_,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=I(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Ie,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(We(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&($e(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Be(this.ui),this.ui=null}};var h=null,Fe={init(n){return h?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),h):(h=new Y(n),h)},setPageContext(n){if(!h){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}h.setPageContext(n)},setIdentity(n){if(!h){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}h.setIdentity(n)},registerTool(n){return h?h.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){h&&h.unregisterTool(n)},on(n,e){return h?h.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return h?h.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){h==null||h.open()},close(){h==null||h.close()},destroy(){h==null||h.destroy(),h=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&Fe.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=Fe);export{Fe as MaxAI};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxaiagent/widget-sdk",
3
- "version": "1.2.3",
3
+ "version": "1.2.4",
4
4
  "description": "MaxAI Widget SDK — embed AI chat with page context, client-side tools, and event system",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",