@maxaiagent/widget-sdk 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -165,6 +165,12 @@ interface IdentityPayload {
165
165
  signature?: string;
166
166
  }
167
167
  interface WidgetInstance {
168
+ /** Mount an inline chat widget inside a container element. Reads sibling content as context. */
169
+ mountInline(el: HTMLElement | string): {
170
+ container: HTMLElement;
171
+ iframe: HTMLIFrameElement;
172
+ destroy: () => void;
173
+ } | null;
168
174
  /** Send explicit page context to the widget */
169
175
  setPageContext(ctx: Partial<PageContext>): void;
170
176
  /**
@@ -230,6 +236,12 @@ declare const MaxAI: {
230
236
  * Subscribe to events.
231
237
  */
232
238
  on(event: WidgetEvent, callback: (...args: unknown[]) => void): () => void;
239
+ /**
240
+ * Mount an inline chat widget inside a container element.
241
+ * Reads sibling content above as conversation context.
242
+ * Also auto-mounts any .maxai-inline divs via MutationObserver.
243
+ */
244
+ mountInline(el: HTMLElement | string): ReturnType<WidgetInstance["mountInline"]>;
233
245
  /**
234
246
  * Open the chat panel.
235
247
  */
package/dist/index.d.ts CHANGED
@@ -165,6 +165,12 @@ interface IdentityPayload {
165
165
  signature?: string;
166
166
  }
167
167
  interface WidgetInstance {
168
+ /** Mount an inline chat widget inside a container element. Reads sibling content as context. */
169
+ mountInline(el: HTMLElement | string): {
170
+ container: HTMLElement;
171
+ iframe: HTMLIFrameElement;
172
+ destroy: () => void;
173
+ } | null;
168
174
  /** Send explicit page context to the widget */
169
175
  setPageContext(ctx: Partial<PageContext>): void;
170
176
  /**
@@ -230,6 +236,12 @@ declare const MaxAI: {
230
236
  * Subscribe to events.
231
237
  */
232
238
  on(event: WidgetEvent, callback: (...args: unknown[]) => void): () => void;
239
+ /**
240
+ * Mount an inline chat widget inside a container element.
241
+ * Reads sibling content above as conversation context.
242
+ * Also auto-mounts any .maxai-inline divs via MutationObserver.
243
+ */
244
+ mountInline(el: HTMLElement | string): ReturnType<WidgetInstance["mountInline"]>;
233
245
  /**
234
246
  * Open the chat panel.
235
247
  */
@@ -1,5 +1,5 @@
1
1
  /* @maxaiagent/widget-sdk v1.1.0 | MIT License | maxaiagent.app */
2
- "use strict";var MaxAISDK=(()=>{var _=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var Z=Object.prototype.hasOwnProperty,Kt=Object.prototype.propertyIsEnumerable;var Q=(n,t,e)=>t in n?_(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,y=(n,t)=>{for(var e in t||(t={}))Z.call(t,e)&&Q(n,e,t[e]);if(V)for(var e of V(t))Kt.call(t,e)&&Q(n,e,t[e]);return n};var Xt=(n,t)=>{for(var e in t)_(n,e,{get:t[e],enumerable:!0})},jt=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Wt(t))!Z.call(n,i)&&i!==e&&_(n,i,{get:()=>t[i],enumerable:!(s=qt(t,i))||s.enumerable});return n};var Ft=n=>jt(_({},"__esModule",{value:!0}),n);var oe={};Xt(oe,{MaxAI:()=>K});var C=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let s=y({type:t},e);this.ready&&this.iframe?this.sendRaw(s):this.queue.push(s)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,s;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(s=(e=this.iframe)==null?void 0:e.contentWindow)==null||s.postMessage(t,this.baseUrl)}catch(i){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(t){return this.baseUrl}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow||t.origin!==this.expectedOrigin())return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var k=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.listeners.get(t))==null||s.delete(e)}emit(t,...e){var s;(s=this.listeners.get(t))==null||s.forEach(i=>{try{i(...e)}catch(r){console.error("[MaxAI SDK]",r)}})}removeAll(){this.listeners.clear()}};var tt="max-widget:page-context",et="max-widget:register-tools",nt="max-widget:unregister-tool",L="max-widget:tool-result",st="max-widget:point-ask-result",I="max-widget:point-ask-cancel",T="max-widget:host-styles",it="max-widget:debug-snapshot",rt="max-widget:config-features";var ot="max-widget:expand",at="max-widget:hide",lt="max-widget:close",dt="max-widget:request-page-context",ct="max-widget:start-point-ask",pt="max-widget:stop-point-ask",ht="max-widget:execute-tool",gt="max-widget:request-debug-snapshot",ut="max-widget:request-host-styles",mt="max-widget:gdpr-consent",ft="max-widget:navigate",xt="max-widget:message",vt="max-widget:error";var yt="max-widget:session-update",St="max-widget:session-request",bt="max-widget:session-restore",wt="max-widget:session-clear",Et="max-widget:draft-save",Tt="max-widget:draft-request",Mt="max-widget:draft-restore",_t="max-widget:identity-set";var O=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.slug||!/^[a-z0-9_]+$/.test(t.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",t.slug),()=>{}):(this.tools.set(t.slug,{slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,handler:t.handler,requiresConfirmation:t.requiresConfirmation||!1,category:t.category||""}),this.sendList(),()=>this.unregister(t.slug))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(nt,{slug:t}),this.sendList())}async execute(t,e,s){let i=this.tools.get(e);if(!(i!=null&&i.handler)){let r=`Tool "${e}" not found or has no handler`;return this.transport.send(L,{toolCallId:t,ok:!1,error:r}),{ok:!1,error:r}}try{let r=await i.handler(s);return this.transport.send(L,{toolCallId:t,ok:!0,data:r}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:e,args:s}})),{ok:!0}}catch(r){let a=r instanceof Error?r.message:"Tool execution failed";return this.transport.send(L,{toolCallId:t,ok:!1,error:a}),{ok:!1,error:a}}}sendList(){let t=Array.from(this.tools.values()).map(e=>({slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,requiresConfirmation:e.requiresConfirmation,category:e.category}));this.transport.send(et,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Ct(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var Yt=[/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 Jt(n){let t=JSON.stringify(n);for(let e of Yt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var A=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 t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let s=e.map(i=>{try{return typeof i=="string"?i:JSON.stringify(i)}catch(r){return String(i)}}).join(" ");this.consoleLogs.push({level:t,message:Ct(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let s of t.getEntries()){let i=s,r=(e=i.responseStatus)!=null?e:0;this.networkLog.push(y({method:"GET",url:Ct(i.name,200),status:r,duration:Math.round(i.duration),timestamp:Math.round(performance.timeOrigin+i.startTime)},r===0||r>=400?{error:r===0?"Network error or blocked":`HTTP ${r}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return Jt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function W(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Vt(n){let t=[],e=n;for(;e&&e.nodeType===1;){let s=1,i=e.previousSibling;for(;i;)i.nodeType===1&&i.tagName===e.tagName&&s++,i=i.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+s+"]"),e=e.parentElement}return"/"+t.join("/")}function Qt(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var G=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}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=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(I),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||Qt(e)){this.transport.send(I),this.cleanup();return}let s={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let o=e.getAttribute(a);o&&(s[a]=W(o,200))}let i=e.parentElement?W(e.parentElement.innerText,300):"",r={elementText:W(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:s,surroundingText:i,xpath:Vt(e)};this.transport.send(st,r),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(I),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.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 Zt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function kt(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let s=document.querySelector('meta[property="og:title"]');s&&(t.ogTitle=s.getAttribute("content")||"");let i=document.querySelector('meta[property="og:description"]');i&&(t.ogDescription=i.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(u){}})}catch(o){}let r=document.querySelector("main, article, [role='main']");r&&(t.mainContent=Zt(r.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(o=>{if(o.name.startsWith("data-context-")){let l=o.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=o.value}}),t}function Lt(n,t){if(!t)return n;let e=y({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=y(y({},e.customContext),t.customContext)),e}var R=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this.origPush,e=this.origReplace,s=()=>this.checkChange();history.pushState=function(...r){t.apply(this,r),s()},history.replaceState=function(...r){e.apply(this,r),s()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let i=document.querySelector("title");i&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(i,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function It(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return!0;let[e,s,i]=[+t[1],+t[2],+t[3]],r=Math.max(e,s,i),a=Math.min(e,s,i);return(r===0?0:(r-a)/r)<.15}function w(){let n=getComputedStyle(document.documentElement),t=getComputedStyle(document.body),e=t.backgroundColor||"",r={bgColor:!e||e==="rgba(0, 0, 0, 0)"||e==="transparent"?n.backgroundColor||"":e,fontFamily:t.fontFamily||"",textColor:t.color||"",primaryColor:"",accentColors:[]};try{let a=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],o={};for(let u of a){let m=document.querySelectorAll(u);for(let h=0;h<Math.min(m.length,10);h++){let S=getComputedStyle(m[h]),g=S.color;g&&g!==r.textColor&&g!=="rgb(0, 0, 0)"&&g!=="rgba(0, 0, 0, 0)"&&!It(g)&&(o[g]=(o[g]||0)+1);let x=S.backgroundColor;x&&x!=="rgba(0, 0, 0, 0)"&&x!=="transparent"&&x!==r.bgColor&&!It(x)&&(o[x]=(o[x]||0)+1)}}let l=Object.keys(o).sort((u,m)=>o[m]-o[u]);r.primaryColor=l[0]||"",r.accentColors=l.slice(0,5)}catch(a){}return r}var te=`
2
+ "use strict";var MaxAISDK=(()=>{var L=Object.defineProperty,Qe=Object.defineProperties,Ze=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyDescriptors,tt=Object.getOwnPropertyNames,de=Object.getOwnPropertySymbols;var he=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var ce=(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={}))he.call(e,t)&&ce(n,t,e[t]);if(de)for(var t of de(e))nt.call(e,t)&&ce(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))!he.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:()=>ne});var T=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",pe="max-widget:register-tools",ue="max-widget:unregister-tool",G="max-widget:tool-result",ge="max-widget:point-ask-result",H="max-widget:point-ask-cancel",k="max-widget:host-styles",me="max-widget:debug-snapshot",P="max-widget:config-features";var fe="max-widget:expand",ve="max-widget:hide",be="max-widget:close",U="max-widget:request-page-context",ye="max-widget:start-point-ask",xe="max-widget:stop-point-ask",Se="max-widget:execute-tool",we="max-widget:request-debug-snapshot",Te="max-widget:request-host-styles",Ee="max-widget:gdpr-consent",Me="max-widget:navigate",ke="max-widget:message",Ie="max-widget:error";var D="max-widget:session-update",N="max-widget:session-request",I="max-widget:session-restore",K="max-widget:session-clear",_e="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 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(ue,{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(pe,{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 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: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 te(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 $=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]=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:lt(t)};this.transport.send(ge,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 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: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 E(){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=`
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,4 +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
- `,ee='<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 ne='<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>',se='<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 At(n){if(!n||n.charAt(0)!=="#")return null;let t=n.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),t.length!==6?null:{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function Ot(n,t){let e=At(n);if(!e)return n;let s=Math.max(0,Math.min(255,Math.round(e.r+255*t))),i=Math.max(0,Math.min(255,Math.round(e.g+255*t))),r=Math.max(0,Math.min(255,Math.round(e.b+255*t))),a=o=>{let l=o.toString(16);return l.length===1?"0"+l:l};return"#"+a(s)+a(i)+a(r)}function P(n,t){let e=At(n);return e?`rgba(${e.r},${e.g},${e.b},${t})`:`rgba(99,102,241,${t})`}function ie(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return"";let e=s=>{let i=s.toString(16);return i.length===1?"0"+i:i};return"#"+e(+t[1])+e(+t[2])+e(+t[3])}function Gt(n,t,e,s){let i=re(e)||s||"#6366f1",r=[n.btn,n.tab];for(let a of r)if(a)if(a.style.background="",a.style.backgroundColor="",a.style.border="none",a.style.backdropFilter="",a.style.webkitBackdropFilter="",a.style.boxShadow="",t==="glassmorphism")a.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",a.style.border="1px solid rgba(255, 255, 255, 0.18)",a.style.backdropFilter="blur(18px) saturate(180%)",a.style.webkitBackdropFilter="blur(18px) saturate(180%)",a.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(t==="auto-adaptive"){let o=Ot(i,.08),l=Ot(i,-.06);a.style.background=`linear-gradient(180deg, ${P(o,.96)}, ${P(l,.92)})`,a.style.border=`1px solid ${P(i,.24)}`,a.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${P(i,.22)}`}else a.style.backgroundColor=s||i,a.style.boxShadow="0 4px 12px rgba(0,0,0,0.3)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),t==="glassmorphism"?n.shell.classList.add("glassmorphism"):t==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function re(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ie(n):"":""}function Rt(n,t,e,s,i,r){if(document.querySelector(".max-widget-container"))return null;let a=document.createElement("style");i&&(a.nonce=i),a.textContent=te,document.head.appendChild(a);let o=document.createElement("div");o.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(o);let l=document.createElement("div");l.className="max-widget-shell "+(e?"right":"left"),o.appendChild(l);let u=document.createElement("div");u.className="max-widget-drag-handle",l.appendChild(u);let m=document.createElement("iframe");m.className="max-widget-frame",m.src=n+"/widget/"+t,m.setAttribute("allow","clipboard-write"),m.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),m.setAttribute("allowtransparency","true"),l.appendChild(m);let h=document.createElement("button");h.className="max-widget-btn",h.style.backgroundColor=s,h.innerHTML=ee,o.appendChild(h);let S=!1,g=!1,x=!1,X=0,j=0,D=0,N=0;function E(d,p){let f=window.innerWidth-o.offsetWidth,q=window.innerHeight-o.offsetHeight;o.style.left=Math.max(0,Math.min(f,d))+"px",o.style.top=Math.max(0,Math.min(q,p))+"px",o.style.bottom="auto",o.style.right="auto"}function F(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(o.style.left),top:parseInt(o.style.top)}))}catch(d){}U()}function U(){let d=l.offsetHeight||600,p=o.getBoundingClientRect(),f=p.top,q=window.innerHeight-p.bottom;f<d+8&&q>=d+8?(l.style.bottom="auto",l.style.top=o.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function zt(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:p,top:f}=JSON.parse(d);typeof p=="number"&&typeof f=="number"&&E(p,f)}catch(d){}}zt(),U(),h.addEventListener("pointerdown",d=>{if(d.button!==0)return;S=!0,g=!1,X=d.clientX,j=d.clientY;let p=o.getBoundingClientRect();D=p.left,N=p.top,E(D,N),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!S)return;let p=d.clientX-X,f=d.clientY-j;!g&&(Math.abs(p)>4||Math.abs(f)>4)&&(g=!0,h.classList.add("dragging")),g&&E(D+p,N+f)}),h.addEventListener("pointerup",()=>{S&&(S=!1,h.classList.remove("dragging"),g&&(x=!0,F(),g=!1))});let M=!1,b=!1,B=0,Y=0,z=0,$=0;u.addEventListener("pointerdown",d=>{if(d.button!==0)return;M=!0,b=!1,B=d.clientX,Y=d.clientY;let p=o.getBoundingClientRect();z=p.left,$=p.top,E(z,$),u.setPointerCapture(d.pointerId),d.preventDefault()}),u.addEventListener("pointermove",d=>{if(!M)return;let p=d.clientX-B,f=d.clientY-Y;!b&&(Math.abs(p)>4||Math.abs(f)>4)&&(b=!0,u.classList.add("dragging")),b&&E(z+p,$+f)}),u.addEventListener("pointerup",()=>{M&&(M=!1,u.classList.remove("dragging"),b&&(F(),b=!1))});let v=document.createElement("button");v.className="max-widget-tab "+(e?"right":"left"),v.style.backgroundColor=s,v.innerHTML=e?ne:se,document.body.appendChild(v);let J=!1;function $t(){J=!1,l.classList.remove("expanded","panel-hidden"),o.classList.remove("panel-expanded","panel-hidden-state"),v.classList.remove("visible"),document.body.style.overflow=""}return h.addEventListener("click",()=>{if(x){x=!1;return}if(J){$t();return}l.classList.contains("open")?(l.classList.remove("open"),r.onClose()):(U(),l.classList.add("open"),r.onOpen())}),v.addEventListener("click",()=>{l.classList.remove("panel-hidden"),o.classList.remove("panel-hidden-state"),v.classList.remove("visible")}),{container:o,shell:l,iframe:m,btn:h,tab:v,style:a}}function Pt(n,t,e){let{container:s,shell:i,tab:r}=n;t?(i.classList.contains("open")||i.classList.add("open"),i.classList.add("expanded"),s.classList.add("panel-expanded"),i.classList.remove("panel-hidden"),s.classList.remove("panel-hidden-state"),r.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(i.classList.remove("expanded","panel-hidden"),s.classList.remove("panel-expanded","panel-hidden-state"),r.classList.remove("visible"),document.body.style.overflow="")}function Ht(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Dt(n){n.container.remove(),n.tab.remove(),n.style.remove()}function Nt(n){n.shell.classList.add("open")}function Ut(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 H=class{constructor(t){this.emitter=new k;this.debug=new A;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.storedSessionToken=null;this.storedIdentity=null;this.key=t.key,this.isRight=t.position!=="bottom-left",this.nonce=t.nonce||null;let e=document.querySelector(`script[data-key="${t.key}"]`);e&&e.src?this.baseUrl=e.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):t.baseUrl?this.baseUrl=t.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new C(this.baseUrl),this.tools=new O(this.transport),this.pointAndAsk=new G(this.transport),this.spaDetector=new R(()=>{var s;if(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.ui){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}}),this.init()}readOrCreateVisitorId(){let t=`maxai_vid_${this.key}`;try{let s=localStorage.getItem(t);if(s)return s}catch(s){}let e=this.getCookie(t);if(e){try{localStorage.setItem(t,e)}catch(s){}return e}return this.generateUUID()}persistVisitorId(t){let e=`maxai_vid_${this.key}`;try{localStorage.setItem(e,t)}catch(s){}this.setCookie(e,t,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(t){}return null}saveSessionToken(t){this.storedSessionToken=t;try{localStorage.setItem(`maxai_st_${this.key}`,t)}catch(e){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(t){}}readStoredIdentity(){try{let t=localStorage.getItem(`maxai_identity_${this.key}`);if(t)return JSON.parse(t)}catch(t){}return null}saveIdentity(t){this.storedIdentity=t;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(t))}catch(e){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}setCookie(t,e,s){try{let i=new Date;i.setTime(i.getTime()+s*864e5),document.cookie=`${t}=${e};expires=${i.toUTCString()};path=/;SameSite=Lax;Secure`}catch(i){}}getCookie(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?e[1]:null}catch(e){return null}}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(e){t={}}this.config={pageContext:t.enable_page_context||!1,pointAndAsk:t.enable_point_and_ask||!1,debugMode:t.enable_debug_mode||!1,bugReport:t.enable_bug_reports||!1,clientTools:t.enable_client_tools||!1,autoTheme:t.theme_mode!=="manual",themeMode:t.theme_mode||"manual",gdprRequired:t.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=t.primary_color||"#6366f1",this.ui=Rt(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.ui&&(this.applyTheme(this.config.autoTheme?w().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var e,s;if(this.transport.markReady(),this.config&&this.transport.send(rt,{features:this.config}),(!((e=this.config)!=null&&e.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme)){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers())}setupMessageHandlers(){this.transport.listen(ot,t=>{this.ui&&Pt(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(at,()=>{this.ui&&Ht(this.ui)}),this.transport.listen(lt,()=>{this.close()}),this.transport.listen(dt,()=>{this.sendPageContext()}),this.transport.listen(ct,()=>{this.pointAndAsk.start()}),this.transport.listen(pt,()=>{this.pointAndAsk.stop()}),this.transport.listen(ht,t=>{let e=t.toolCallId,s=t.slug||t.name,i=t.args;this.emitter.emit("tool:call",{id:e,name:s,args:i}),this.tools.execute(e,s,i).then(r=>{this.emitter.emit("tool:result",{id:e,name:s,ok:r.ok,error:r.error})})}),this.transport.listen(gt,()=>{this.transport.send(it,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(ut,()=>{let t=w();this.applyTheme(t.primaryColor),this.transport.send(T,{styles:t})}),this.transport.listen(mt,()=>{var t,e;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme){let s=w();this.applyTheme(s.primaryColor),this.transport.send(T,{styles:s})}}),this.transport.listen(ft,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(xt,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(vt,t=>{this.emitter.emit("error",{message:t.error})}),this.transport.listen(St,()=>{this.transport.send(bt,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(yt,t=>{t.sessionToken&&this.saveSessionToken(t.sessionToken)}),this.transport.listen(wt,()=>{this.clearSessionToken()}),this.transport.listen(Et,t=>{try{localStorage.setItem(`maxai_draft_${this.key}`,t.text||"")}catch(e){}}),this.transport.listen(Tt,()=>{let t="";try{t=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(e){}this.transport.send(Mt,{text:t})})}applyTheme(t){!this.ui||!this.config||Gt(this.ui,this.config.themeMode,t,this.primaryColor)}sendPageContext(){var s;if(!this.consentGiven&&((s=this.config)!=null&&s.gdprRequired))return;let t=kt(this.key),e=Lt(t,this.explicitContext);this.transport.send(tt,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}setIdentity(t){this.saveIdentity(t),this.transport.send(_t,{identityPayload:t})}registerTool(t){return this.tools.register(t)}unregisterTool(t){this.tools.unregister(t)}on(t,e){return this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}open(){this.ui&&(Nt(this.ui),this.emitter.emit("open"))}close(){this.ui&&(Ut(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&Dt(this.ui),this.ui=null}};var c=null,K={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new H(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,t){return c?c.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},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 t=n.getAttribute("data-key");t&&K.init({key:t,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=K);return Ft(oe);})();
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 S(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, ${S(a,.96)}, ${S(l,.92)})`,r.style.border=`1px solid ${S(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${S(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${S(s,.55)}, ${S(s,.4)})`,r.style.border=`1px solid ${S(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,ie=0,se=0,Y=0,J=0;function M(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 re(){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"&&M(u,v)}catch(d){}}Je(),V(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,ie=d.clientX,se=d.clientY;let u=a.getBoundingClientRect();Y=u.left,J=u.top,M(Y,J),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-ie,v=d.clientY-se;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&M(Y+u,J+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,re(),m=!1))});let C=!1,w=!1,oe=0,ae=0,Q=0,Z=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,w=!1,oe=d.clientX,ae=d.clientY;let u=a.getBoundingClientRect();Q=u.left,Z=u.top,M(Q,Z),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-oe,v=d.clientY-ae;!w&&(Math.abs(u)>4||Math.abs(v)>4)&&(w=!0,h.classList.add("dragging")),w&&M(Q+u,Z+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),w&&(re(),w=!1))});let x=document.createElement("button");x.className="max-widget-tab "+(t?"right":"left"),x.style.backgroundColor=i,x.innerHTML=t?gt:mt,document.body.appendChild(x);let le=!1;function Ve(){le=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),x.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(le){Ve();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(V(),l.classList.add("open"),o.onOpen())}),x.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),x.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:x,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 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(O(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(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+`
43
+ `)}if(r.length>e.join(" ").length)return Fe(r.trim(),3e3)}return Fe(e.join(`
44
+ `),3e3)}function _(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 T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(P,{features:e.config}),o()}),s.listen(N,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(D,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(K,()=>{}),s.listen(U,()=>{o()}),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,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),_(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=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var j=class{constructor(e){this.emitter=new A;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 T(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=E();this.applyTheme(r.primaryColor),this.transport.send(k,{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?E().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=E();this.applyTheme(r.primaryColor),this.transport.send(k,{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(fe,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ve,()=>{this.ui&&$e(this.ui)}),this.transport.listen(be,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(ye,()=>{this.pointAndAsk.start()}),this.transport.listen(xe,()=>{this.pointAndAsk.stop()}),this.transport.listen("max-widget:request-tools",()=>{this.tools.hasTools()&&this.tools.sendList()}),this.transport.listen(Se,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(we,()=>{this.transport.send(me,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(Te,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{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=E();this.applyTheme(s.primaryColor),this.transport.send(k,{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(Ie,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(N,()=>{this.transport.send(I,{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(_e,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 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||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=q();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(I,{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=_(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,ne={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&&ne.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=ne);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 _=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var Z=Object.prototype.hasOwnProperty,Kt=Object.prototype.propertyIsEnumerable;var Q=(n,t,e)=>t in n?_(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,y=(n,t)=>{for(var e in t||(t={}))Z.call(t,e)&&Q(n,e,t[e]);if(V)for(var e of V(t))Kt.call(t,e)&&Q(n,e,t[e]);return n};var Xt=(n,t)=>{for(var e in t)_(n,e,{get:t[e],enumerable:!0})},jt=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Wt(t))!Z.call(n,i)&&i!==e&&_(n,i,{get:()=>t[i],enumerable:!(s=qt(t,i))||s.enumerable});return n};var Ft=n=>jt(_({},"__esModule",{value:!0}),n);var oe={};Xt(oe,{MaxAI:()=>K});module.exports=Ft(oe);var C=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let s=y({type:t},e);this.ready&&this.iframe?this.sendRaw(s):this.queue.push(s)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,s;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(s=(e=this.iframe)==null?void 0:e.contentWindow)==null||s.postMessage(t,this.baseUrl)}catch(i){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(t){return this.baseUrl}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow||t.origin!==this.expectedOrigin())return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var k=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.listeners.get(t))==null||s.delete(e)}emit(t,...e){var s;(s=this.listeners.get(t))==null||s.forEach(i=>{try{i(...e)}catch(r){console.error("[MaxAI SDK]",r)}})}removeAll(){this.listeners.clear()}};var tt="max-widget:page-context",et="max-widget:register-tools",nt="max-widget:unregister-tool",L="max-widget:tool-result",st="max-widget:point-ask-result",I="max-widget:point-ask-cancel",T="max-widget:host-styles",it="max-widget:debug-snapshot",rt="max-widget:config-features";var ot="max-widget:expand",at="max-widget:hide",lt="max-widget:close",dt="max-widget:request-page-context",ct="max-widget:start-point-ask",pt="max-widget:stop-point-ask",ht="max-widget:execute-tool",gt="max-widget:request-debug-snapshot",ut="max-widget:request-host-styles",mt="max-widget:gdpr-consent",ft="max-widget:navigate",xt="max-widget:message",vt="max-widget:error";var yt="max-widget:session-update",St="max-widget:session-request",bt="max-widget:session-restore",wt="max-widget:session-clear",Et="max-widget:draft-save",Tt="max-widget:draft-request",Mt="max-widget:draft-restore",_t="max-widget:identity-set";var O=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.slug||!/^[a-z0-9_]+$/.test(t.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",t.slug),()=>{}):(this.tools.set(t.slug,{slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,handler:t.handler,requiresConfirmation:t.requiresConfirmation||!1,category:t.category||""}),this.sendList(),()=>this.unregister(t.slug))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(nt,{slug:t}),this.sendList())}async execute(t,e,s){let i=this.tools.get(e);if(!(i!=null&&i.handler)){let r=`Tool "${e}" not found or has no handler`;return this.transport.send(L,{toolCallId:t,ok:!1,error:r}),{ok:!1,error:r}}try{let r=await i.handler(s);return this.transport.send(L,{toolCallId:t,ok:!0,data:r}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:e,args:s}})),{ok:!0}}catch(r){let a=r instanceof Error?r.message:"Tool execution failed";return this.transport.send(L,{toolCallId:t,ok:!1,error:a}),{ok:!1,error:a}}}sendList(){let t=Array.from(this.tools.values()).map(e=>({slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,requiresConfirmation:e.requiresConfirmation,category:e.category}));this.transport.send(et,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Ct(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var Yt=[/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 Jt(n){let t=JSON.stringify(n);for(let e of Yt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var A=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 t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let s=e.map(i=>{try{return typeof i=="string"?i:JSON.stringify(i)}catch(r){return String(i)}}).join(" ");this.consoleLogs.push({level:t,message:Ct(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let s of t.getEntries()){let i=s,r=(e=i.responseStatus)!=null?e:0;this.networkLog.push(y({method:"GET",url:Ct(i.name,200),status:r,duration:Math.round(i.duration),timestamp:Math.round(performance.timeOrigin+i.startTime)},r===0||r>=400?{error:r===0?"Network error or blocked":`HTTP ${r}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return Jt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function W(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Vt(n){let t=[],e=n;for(;e&&e.nodeType===1;){let s=1,i=e.previousSibling;for(;i;)i.nodeType===1&&i.tagName===e.tagName&&s++,i=i.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+s+"]"),e=e.parentElement}return"/"+t.join("/")}function Qt(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var G=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}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=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(I),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||Qt(e)){this.transport.send(I),this.cleanup();return}let s={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let o=e.getAttribute(a);o&&(s[a]=W(o,200))}let i=e.parentElement?W(e.parentElement.innerText,300):"",r={elementText:W(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:s,surroundingText:i,xpath:Vt(e)};this.transport.send(st,r),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(I),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.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 Zt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function kt(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let s=document.querySelector('meta[property="og:title"]');s&&(t.ogTitle=s.getAttribute("content")||"");let i=document.querySelector('meta[property="og:description"]');i&&(t.ogDescription=i.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(u){}})}catch(o){}let r=document.querySelector("main, article, [role='main']");r&&(t.mainContent=Zt(r.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(o=>{if(o.name.startsWith("data-context-")){let l=o.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=o.value}}),t}function Lt(n,t){if(!t)return n;let e=y({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=y(y({},e.customContext),t.customContext)),e}var R=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this.origPush,e=this.origReplace,s=()=>this.checkChange();history.pushState=function(...r){t.apply(this,r),s()},history.replaceState=function(...r){e.apply(this,r),s()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let i=document.querySelector("title");i&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(i,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function It(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return!0;let[e,s,i]=[+t[1],+t[2],+t[3]],r=Math.max(e,s,i),a=Math.min(e,s,i);return(r===0?0:(r-a)/r)<.15}function w(){let n=getComputedStyle(document.documentElement),t=getComputedStyle(document.body),e=t.backgroundColor||"",r={bgColor:!e||e==="rgba(0, 0, 0, 0)"||e==="transparent"?n.backgroundColor||"":e,fontFamily:t.fontFamily||"",textColor:t.color||"",primaryColor:"",accentColors:[]};try{let a=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],o={};for(let u of a){let m=document.querySelectorAll(u);for(let h=0;h<Math.min(m.length,10);h++){let S=getComputedStyle(m[h]),g=S.color;g&&g!==r.textColor&&g!=="rgb(0, 0, 0)"&&g!=="rgba(0, 0, 0, 0)"&&!It(g)&&(o[g]=(o[g]||0)+1);let x=S.backgroundColor;x&&x!=="rgba(0, 0, 0, 0)"&&x!=="transparent"&&x!==r.bgColor&&!It(x)&&(o[x]=(o[x]||0)+1)}}let l=Object.keys(o).sort((u,m)=>o[m]-o[u]);r.primaryColor=l[0]||"",r.accentColors=l.slice(0,5)}catch(a){}return r}var te=`
2
+ "use strict";var L=Object.defineProperty,Qe=Object.defineProperties,Ze=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyDescriptors,tt=Object.getOwnPropertyNames,de=Object.getOwnPropertySymbols;var he=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var ce=(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={}))he.call(e,t)&&ce(n,t,e[t]);if(de)for(var t of de(e))nt.call(e,t)&&ce(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))!he.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:()=>ne});module.exports=rt(yt);var T=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",pe="max-widget:register-tools",ue="max-widget:unregister-tool",G="max-widget:tool-result",ge="max-widget:point-ask-result",H="max-widget:point-ask-cancel",k="max-widget:host-styles",me="max-widget:debug-snapshot",P="max-widget:config-features";var fe="max-widget:expand",ve="max-widget:hide",be="max-widget:close",U="max-widget:request-page-context",ye="max-widget:start-point-ask",xe="max-widget:stop-point-ask",Se="max-widget:execute-tool",we="max-widget:request-debug-snapshot",Te="max-widget:request-host-styles",Ee="max-widget:gdpr-consent",Me="max-widget:navigate",ke="max-widget:message",Ie="max-widget:error";var D="max-widget:session-update",N="max-widget:session-request",I="max-widget:session-restore",K="max-widget:session-clear",_e="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 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(ue,{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(pe,{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 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: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 te(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 $=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]=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:lt(t)};this.transport.send(ge,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 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: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 E(){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=`
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,4 +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
- `,ee='<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 ne='<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>',se='<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 At(n){if(!n||n.charAt(0)!=="#")return null;let t=n.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),t.length!==6?null:{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function Ot(n,t){let e=At(n);if(!e)return n;let s=Math.max(0,Math.min(255,Math.round(e.r+255*t))),i=Math.max(0,Math.min(255,Math.round(e.g+255*t))),r=Math.max(0,Math.min(255,Math.round(e.b+255*t))),a=o=>{let l=o.toString(16);return l.length===1?"0"+l:l};return"#"+a(s)+a(i)+a(r)}function P(n,t){let e=At(n);return e?`rgba(${e.r},${e.g},${e.b},${t})`:`rgba(99,102,241,${t})`}function ie(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return"";let e=s=>{let i=s.toString(16);return i.length===1?"0"+i:i};return"#"+e(+t[1])+e(+t[2])+e(+t[3])}function Gt(n,t,e,s){let i=re(e)||s||"#6366f1",r=[n.btn,n.tab];for(let a of r)if(a)if(a.style.background="",a.style.backgroundColor="",a.style.border="none",a.style.backdropFilter="",a.style.webkitBackdropFilter="",a.style.boxShadow="",t==="glassmorphism")a.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",a.style.border="1px solid rgba(255, 255, 255, 0.18)",a.style.backdropFilter="blur(18px) saturate(180%)",a.style.webkitBackdropFilter="blur(18px) saturate(180%)",a.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(t==="auto-adaptive"){let o=Ot(i,.08),l=Ot(i,-.06);a.style.background=`linear-gradient(180deg, ${P(o,.96)}, ${P(l,.92)})`,a.style.border=`1px solid ${P(i,.24)}`,a.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${P(i,.22)}`}else a.style.backgroundColor=s||i,a.style.boxShadow="0 4px 12px rgba(0,0,0,0.3)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),t==="glassmorphism"?n.shell.classList.add("glassmorphism"):t==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function re(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ie(n):"":""}function Rt(n,t,e,s,i,r){if(document.querySelector(".max-widget-container"))return null;let a=document.createElement("style");i&&(a.nonce=i),a.textContent=te,document.head.appendChild(a);let o=document.createElement("div");o.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(o);let l=document.createElement("div");l.className="max-widget-shell "+(e?"right":"left"),o.appendChild(l);let u=document.createElement("div");u.className="max-widget-drag-handle",l.appendChild(u);let m=document.createElement("iframe");m.className="max-widget-frame",m.src=n+"/widget/"+t,m.setAttribute("allow","clipboard-write"),m.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),m.setAttribute("allowtransparency","true"),l.appendChild(m);let h=document.createElement("button");h.className="max-widget-btn",h.style.backgroundColor=s,h.innerHTML=ee,o.appendChild(h);let S=!1,g=!1,x=!1,X=0,j=0,D=0,N=0;function E(d,p){let f=window.innerWidth-o.offsetWidth,q=window.innerHeight-o.offsetHeight;o.style.left=Math.max(0,Math.min(f,d))+"px",o.style.top=Math.max(0,Math.min(q,p))+"px",o.style.bottom="auto",o.style.right="auto"}function F(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(o.style.left),top:parseInt(o.style.top)}))}catch(d){}U()}function U(){let d=l.offsetHeight||600,p=o.getBoundingClientRect(),f=p.top,q=window.innerHeight-p.bottom;f<d+8&&q>=d+8?(l.style.bottom="auto",l.style.top=o.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function zt(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:p,top:f}=JSON.parse(d);typeof p=="number"&&typeof f=="number"&&E(p,f)}catch(d){}}zt(),U(),h.addEventListener("pointerdown",d=>{if(d.button!==0)return;S=!0,g=!1,X=d.clientX,j=d.clientY;let p=o.getBoundingClientRect();D=p.left,N=p.top,E(D,N),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!S)return;let p=d.clientX-X,f=d.clientY-j;!g&&(Math.abs(p)>4||Math.abs(f)>4)&&(g=!0,h.classList.add("dragging")),g&&E(D+p,N+f)}),h.addEventListener("pointerup",()=>{S&&(S=!1,h.classList.remove("dragging"),g&&(x=!0,F(),g=!1))});let M=!1,b=!1,B=0,Y=0,z=0,$=0;u.addEventListener("pointerdown",d=>{if(d.button!==0)return;M=!0,b=!1,B=d.clientX,Y=d.clientY;let p=o.getBoundingClientRect();z=p.left,$=p.top,E(z,$),u.setPointerCapture(d.pointerId),d.preventDefault()}),u.addEventListener("pointermove",d=>{if(!M)return;let p=d.clientX-B,f=d.clientY-Y;!b&&(Math.abs(p)>4||Math.abs(f)>4)&&(b=!0,u.classList.add("dragging")),b&&E(z+p,$+f)}),u.addEventListener("pointerup",()=>{M&&(M=!1,u.classList.remove("dragging"),b&&(F(),b=!1))});let v=document.createElement("button");v.className="max-widget-tab "+(e?"right":"left"),v.style.backgroundColor=s,v.innerHTML=e?ne:se,document.body.appendChild(v);let J=!1;function $t(){J=!1,l.classList.remove("expanded","panel-hidden"),o.classList.remove("panel-expanded","panel-hidden-state"),v.classList.remove("visible"),document.body.style.overflow=""}return h.addEventListener("click",()=>{if(x){x=!1;return}if(J){$t();return}l.classList.contains("open")?(l.classList.remove("open"),r.onClose()):(U(),l.classList.add("open"),r.onOpen())}),v.addEventListener("click",()=>{l.classList.remove("panel-hidden"),o.classList.remove("panel-hidden-state"),v.classList.remove("visible")}),{container:o,shell:l,iframe:m,btn:h,tab:v,style:a}}function Pt(n,t,e){let{container:s,shell:i,tab:r}=n;t?(i.classList.contains("open")||i.classList.add("open"),i.classList.add("expanded"),s.classList.add("panel-expanded"),i.classList.remove("panel-hidden"),s.classList.remove("panel-hidden-state"),r.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(i.classList.remove("expanded","panel-hidden"),s.classList.remove("panel-expanded","panel-hidden-state"),r.classList.remove("visible"),document.body.style.overflow="")}function Ht(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Dt(n){n.container.remove(),n.tab.remove(),n.style.remove()}function Nt(n){n.shell.classList.add("open")}function Ut(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 H=class{constructor(t){this.emitter=new k;this.debug=new A;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.storedSessionToken=null;this.storedIdentity=null;this.key=t.key,this.isRight=t.position!=="bottom-left",this.nonce=t.nonce||null;let e=document.querySelector(`script[data-key="${t.key}"]`);e&&e.src?this.baseUrl=e.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):t.baseUrl?this.baseUrl=t.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new C(this.baseUrl),this.tools=new O(this.transport),this.pointAndAsk=new G(this.transport),this.spaDetector=new R(()=>{var s;if(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.ui){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}}),this.init()}readOrCreateVisitorId(){let t=`maxai_vid_${this.key}`;try{let s=localStorage.getItem(t);if(s)return s}catch(s){}let e=this.getCookie(t);if(e){try{localStorage.setItem(t,e)}catch(s){}return e}return this.generateUUID()}persistVisitorId(t){let e=`maxai_vid_${this.key}`;try{localStorage.setItem(e,t)}catch(s){}this.setCookie(e,t,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(t){}return null}saveSessionToken(t){this.storedSessionToken=t;try{localStorage.setItem(`maxai_st_${this.key}`,t)}catch(e){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(t){}}readStoredIdentity(){try{let t=localStorage.getItem(`maxai_identity_${this.key}`);if(t)return JSON.parse(t)}catch(t){}return null}saveIdentity(t){this.storedIdentity=t;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(t))}catch(e){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}setCookie(t,e,s){try{let i=new Date;i.setTime(i.getTime()+s*864e5),document.cookie=`${t}=${e};expires=${i.toUTCString()};path=/;SameSite=Lax;Secure`}catch(i){}}getCookie(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?e[1]:null}catch(e){return null}}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(e){t={}}this.config={pageContext:t.enable_page_context||!1,pointAndAsk:t.enable_point_and_ask||!1,debugMode:t.enable_debug_mode||!1,bugReport:t.enable_bug_reports||!1,clientTools:t.enable_client_tools||!1,autoTheme:t.theme_mode!=="manual",themeMode:t.theme_mode||"manual",gdprRequired:t.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=t.primary_color||"#6366f1",this.ui=Rt(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.ui&&(this.applyTheme(this.config.autoTheme?w().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var e,s;if(this.transport.markReady(),this.config&&this.transport.send(rt,{features:this.config}),(!((e=this.config)!=null&&e.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme)){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers())}setupMessageHandlers(){this.transport.listen(ot,t=>{this.ui&&Pt(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(at,()=>{this.ui&&Ht(this.ui)}),this.transport.listen(lt,()=>{this.close()}),this.transport.listen(dt,()=>{this.sendPageContext()}),this.transport.listen(ct,()=>{this.pointAndAsk.start()}),this.transport.listen(pt,()=>{this.pointAndAsk.stop()}),this.transport.listen(ht,t=>{let e=t.toolCallId,s=t.slug||t.name,i=t.args;this.emitter.emit("tool:call",{id:e,name:s,args:i}),this.tools.execute(e,s,i).then(r=>{this.emitter.emit("tool:result",{id:e,name:s,ok:r.ok,error:r.error})})}),this.transport.listen(gt,()=>{this.transport.send(it,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(ut,()=>{let t=w();this.applyTheme(t.primaryColor),this.transport.send(T,{styles:t})}),this.transport.listen(mt,()=>{var t,e;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme){let s=w();this.applyTheme(s.primaryColor),this.transport.send(T,{styles:s})}}),this.transport.listen(ft,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(xt,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(vt,t=>{this.emitter.emit("error",{message:t.error})}),this.transport.listen(St,()=>{this.transport.send(bt,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(yt,t=>{t.sessionToken&&this.saveSessionToken(t.sessionToken)}),this.transport.listen(wt,()=>{this.clearSessionToken()}),this.transport.listen(Et,t=>{try{localStorage.setItem(`maxai_draft_${this.key}`,t.text||"")}catch(e){}}),this.transport.listen(Tt,()=>{let t="";try{t=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(e){}this.transport.send(Mt,{text:t})})}applyTheme(t){!this.ui||!this.config||Gt(this.ui,this.config.themeMode,t,this.primaryColor)}sendPageContext(){var s;if(!this.consentGiven&&((s=this.config)!=null&&s.gdprRequired))return;let t=kt(this.key),e=Lt(t,this.explicitContext);this.transport.send(tt,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}setIdentity(t){this.saveIdentity(t),this.transport.send(_t,{identityPayload:t})}registerTool(t){return this.tools.register(t)}unregisterTool(t){this.tools.unregister(t)}on(t,e){return this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}open(){this.ui&&(Nt(this.ui),this.emitter.emit("open"))}close(){this.ui&&(Ut(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&Dt(this.ui),this.ui=null}};var c=null,K={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new H(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,t){return c?c.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},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 t=n.getAttribute("data-key");t&&K.init({key:t,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=K);
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 S(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, ${S(a,.96)}, ${S(l,.92)})`,r.style.border=`1px solid ${S(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${S(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${S(s,.55)}, ${S(s,.4)})`,r.style.border=`1px solid ${S(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,ie=0,se=0,Y=0,J=0;function M(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 re(){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"&&M(u,v)}catch(d){}}Je(),V(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,ie=d.clientX,se=d.clientY;let u=a.getBoundingClientRect();Y=u.left,J=u.top,M(Y,J),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-ie,v=d.clientY-se;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&M(Y+u,J+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,re(),m=!1))});let C=!1,w=!1,oe=0,ae=0,Q=0,Z=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,w=!1,oe=d.clientX,ae=d.clientY;let u=a.getBoundingClientRect();Q=u.left,Z=u.top,M(Q,Z),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-oe,v=d.clientY-ae;!w&&(Math.abs(u)>4||Math.abs(v)>4)&&(w=!0,h.classList.add("dragging")),w&&M(Q+u,Z+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),w&&(re(),w=!1))});let x=document.createElement("button");x.className="max-widget-tab "+(t?"right":"left"),x.style.backgroundColor=i,x.innerHTML=t?gt:mt,document.body.appendChild(x);let le=!1;function Ve(){le=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),x.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(le){Ve();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(V(),l.classList.add("open"),o.onOpen())}),x.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),x.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:x,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 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(O(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(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+`
43
+ `)}if(r.length>e.join(" ").length)return Fe(r.trim(),3e3)}return Fe(e.join(`
44
+ `),3e3)}function _(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 T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(P,{features:e.config}),o()}),s.listen(N,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(D,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(K,()=>{}),s.listen(U,()=>{o()}),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,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),_(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=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var j=class{constructor(e){this.emitter=new A;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 T(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=E();this.applyTheme(r.primaryColor),this.transport.send(k,{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?E().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=E();this.applyTheme(r.primaryColor),this.transport.send(k,{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(fe,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ve,()=>{this.ui&&$e(this.ui)}),this.transport.listen(be,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(ye,()=>{this.pointAndAsk.start()}),this.transport.listen(xe,()=>{this.pointAndAsk.stop()}),this.transport.listen("max-widget:request-tools",()=>{this.tools.hasTools()&&this.tools.sendList()}),this.transport.listen(Se,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(we,()=>{this.transport.send(me,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(Te,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{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=E();this.applyTheme(s.primaryColor),this.transport.send(k,{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(Ie,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(N,()=>{this.transport.send(I,{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(_e,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 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||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=q();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(I,{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=_(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,ne={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&&ne.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=ne);
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /* @maxaiagent/widget-sdk v1.1.0 | MIT License | maxaiagent.app */
2
- var zt=Object.defineProperty;var Y=Object.getOwnPropertySymbols;var $t=Object.prototype.hasOwnProperty,qt=Object.prototype.propertyIsEnumerable;var J=(n,t,e)=>t in n?zt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,y=(n,t)=>{for(var e in t||(t={}))$t.call(t,e)&&J(n,e,t[e]);if(Y)for(var e of Y(t))qt.call(t,e)&&J(n,e,t[e]);return n};var _=class{constructor(t){this.iframe=null;this.ready=!1;this.queue=[];this.handlers=new Map;this.boundListener=null;this.baseUrl=t}attach(t){this.iframe=t,this.boundListener=e=>this.onMessage(e),window.addEventListener("message",this.boundListener)}markReady(){this.ready=!0;for(let t of this.queue)this.sendRaw(t);this.queue=[]}send(t,e){let s=y({type:t},e);this.ready&&this.iframe?this.sendRaw(s):this.queue.push(s)}listen(t,e){this.handlers.set(t,e)}destroy(){this.boundListener&&(window.removeEventListener("message",this.boundListener),this.boundListener=null),this.handlers.clear(),this.queue=[],this.iframe=null,this.ready=!1}sendRaw(t){var e,s;if(!this.baseUrl){console.error("[MaxAI SDK] Cannot send postMessage: baseUrl is not set");return}try{(s=(e=this.iframe)==null?void 0:e.contentWindow)==null||s.postMessage(t,this.baseUrl)}catch(i){}}expectedOrigin(){try{return new URL(this.baseUrl).origin}catch(t){return this.baseUrl}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow||t.origin!==this.expectedOrigin())return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var C=class{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.listeners.get(t))==null||s.delete(e)}emit(t,...e){var s;(s=this.listeners.get(t))==null||s.forEach(i=>{try{i(...e)}catch(r){console.error("[MaxAI SDK]",r)}})}removeAll(){this.listeners.clear()}};var V="max-widget:page-context",Q="max-widget:register-tools",Z="max-widget:unregister-tool",k="max-widget:tool-result",tt="max-widget:point-ask-result",L="max-widget:point-ask-cancel",T="max-widget:host-styles",et="max-widget:debug-snapshot",nt="max-widget:config-features";var st="max-widget:expand",it="max-widget:hide",rt="max-widget:close",ot="max-widget:request-page-context",at="max-widget:start-point-ask",lt="max-widget:stop-point-ask",dt="max-widget:execute-tool",ct="max-widget:request-debug-snapshot",pt="max-widget:request-host-styles",ht="max-widget:gdpr-consent",gt="max-widget:navigate",ut="max-widget:message",mt="max-widget:error";var ft="max-widget:session-update",xt="max-widget:session-request",vt="max-widget:session-restore",yt="max-widget:session-clear",St="max-widget:draft-save",bt="max-widget:draft-request",wt="max-widget:draft-restore",Et="max-widget:identity-set";var I=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.slug||!/^[a-z0-9_]+$/.test(t.slug)?(console.error("[MaxAI SDK] Invalid tool slug (must match /^[a-z0-9_]+$/):",t.slug),()=>{}):(this.tools.set(t.slug,{slug:t.slug,name:t.name,description:t.description,schema:t.schema,context:t.context,handler:t.handler,requiresConfirmation:t.requiresConfirmation||!1,category:t.category||""}),this.sendList(),()=>this.unregister(t.slug))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(Z,{slug:t}),this.sendList())}async execute(t,e,s){let i=this.tools.get(e);if(!(i!=null&&i.handler)){let r=`Tool "${e}" not found or has no handler`;return this.transport.send(k,{toolCallId:t,ok:!1,error:r}),{ok:!1,error:r}}try{let r=await i.handler(s);return this.transport.send(k,{toolCallId:t,ok:!0,data:r}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolSlug:e,args:s}})),{ok:!0}}catch(r){let a=r instanceof Error?r.message:"Tool execution failed";return this.transport.send(k,{toolCallId:t,ok:!1,error:a}),{ok:!1,error:a}}}sendList(){let t=Array.from(this.tools.values()).map(e=>({slug:e.slug,name:e.name,description:e.description,schema:e.schema,context:e.context,requiresConfirmation:e.requiresConfirmation,category:e.category}));this.transport.send(Q,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function Tt(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var Kt=[/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 Xt(n){let t=JSON.stringify(n);for(let e of Kt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var O=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 t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let s=e.map(i=>{try{return typeof i=="string"?i:JSON.stringify(i)}catch(r){return String(i)}}).join(" ");this.consoleLogs.push({level:t,message:Tt(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};this.errorHandler=t=>{this.errors.push({message:t.message||"",source:t.filename||"",line:t.lineno||0,col:t.colno||0,timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{this.errors.push({message:"Unhandled rejection: "+(t.reason?String(t.reason):"unknown"),timestamp:Date.now()}),this.errors.length>50&&this.errors.shift()},window.addEventListener("unhandledrejection",this.rejectionHandler);try{this.perfObserver=new PerformanceObserver(t=>{var e;for(let s of t.getEntries()){let i=s,r=(e=i.responseStatus)!=null?e:0;this.networkLog.push(y({method:"GET",url:Tt(i.name,200),status:r,duration:Math.round(i.duration),timestamp:Math.round(performance.timeOrigin+i.startTime)},r===0||r>=400?{error:r===0?"Network error or blocked":`HTTP ${r}`}:{})),this.networkLog.length>30&&this.networkLog.shift()}}),this.perfObserver.observe({type:"resource",buffered:!0})}catch(t){}}}getSnapshot(){return Xt({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){var t;if(this.initialized){for(let e of Object.keys(this.origConsole))console[e]=this.origConsole[e];(t=this.perfObserver)==null||t.disconnect(),this.perfObserver=null,this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function q(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function jt(n){let t=[],e=n;for(;e&&e.nodeType===1;){let s=1,i=e.previousSibling;for(;i;)i.nodeType===1&&i.tagName===e.tagName&&s++,i=i.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+s+"]"),e=e.parentElement}return"/"+t.join("/")}function Ft(n){let t=n.tagName.toLowerCase();return!!(t==="input"||t==="textarea"||t==="select"||n.getAttribute("type")==="password"||n.getAttribute("data-no-capture")!==null||n.isContentEditable)}var A=class{constructor(t){this.active=!1;this.overlay=null;this.lastHighlighted=null;this.boundMove=null;this.boundClick=null;this.boundKey=null;this.transport=t}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=t=>this.onMouseMove(t),this.boundClick=t=>this.onClick(t),this.boundKey=t=>this.onKeyDown(t),document.addEventListener("mousemove",this.boundMove,!0),document.addEventListener("click",this.boundClick,!0),document.addEventListener("keydown",this.boundKey,!0))}stop(){this.active&&(this.transport.send(L),this.cleanup())}onMouseMove(t){if(!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.overlay.style.pointerEvents="auto",this.highlight(e)}onClick(t){if(t.preventDefault(),t.stopPropagation(),!this.overlay)return;this.overlay.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);if(this.overlay.style.pointerEvents="auto",!e||Ft(e)){this.transport.send(L),this.cleanup();return}let s={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let o=e.getAttribute(a);o&&(s[a]=q(o,200))}let i=e.parentElement?q(e.parentElement.innerText,300):"",r={elementText:q(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:s,surroundingText:i,xpath:jt(e)};this.transport.send(tt,r),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(L),this.cleanup())}highlight(t){this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),t&&t!==document.body&&t!==document.documentElement?(t._prevOutline=t.style.outline,t._prevOffset=t.style.outlineOffset,t.style.outline="2px solid #6366f1",t.style.outlineOffset="2px",this.lastHighlighted=t):this.lastHighlighted=null}cleanup(){var t,e;this.active=!1,this.lastHighlighted&&(this.lastHighlighted.style.outline=this.lastHighlighted._prevOutline||"",this.lastHighlighted.style.outlineOffset=this.lastHighlighted._prevOffset||""),(e=(t=this.overlay)==null?void 0:t.parentNode)==null||e.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 Bt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Mt(n){let t={url:window.location.href,title:document.title||"",description:"",ogTitle:"",ogDescription:"",jsonLd:[],mainContent:"",customContext:{},lang:document.documentElement.lang||""},e=document.querySelector('meta[name="description"]');e&&(t.description=e.getAttribute("content")||"");let s=document.querySelector('meta[property="og:title"]');s&&(t.ogTitle=s.getAttribute("content")||"");let i=document.querySelector('meta[property="og:description"]');i&&(t.ogDescription=i.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(u){}})}catch(o){}let r=document.querySelector("main, article, [role='main']");r&&(t.mainContent=Bt(r.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(o=>{if(o.name.startsWith("data-context-")){let l=o.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=o.value}}),t}function _t(n,t){if(!t)return n;let e=y({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=y(y({},e.customContext),t.customContext)),e}var G=class{constructor(t){this.lastUrl="";this.origPush=null;this.origReplace=null;this.popstateHandler=null;this.observer=null;this.onChange=t,this.lastUrl=window.location.href}start(){this.origPush=history.pushState,this.origReplace=history.replaceState;let t=this.origPush,e=this.origReplace,s=()=>this.checkChange();history.pushState=function(...r){t.apply(this,r),s()},history.replaceState=function(...r){e.apply(this,r),s()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let i=document.querySelector("title");i&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(i,{childList:!0,characterData:!0,subtree:!0}))}destroy(){var t;this.origPush&&(history.pushState=this.origPush),this.origReplace&&(history.replaceState=this.origReplace),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),(t=this.observer)==null||t.disconnect()}checkChange(){let t=window.location.href;t!==this.lastUrl&&(this.lastUrl=t,setTimeout(this.onChange,200))}};function Ct(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return!0;let[e,s,i]=[+t[1],+t[2],+t[3]],r=Math.max(e,s,i),a=Math.min(e,s,i);return(r===0?0:(r-a)/r)<.15}function w(){let n=getComputedStyle(document.documentElement),t=getComputedStyle(document.body),e=t.backgroundColor||"",r={bgColor:!e||e==="rgba(0, 0, 0, 0)"||e==="transparent"?n.backgroundColor||"":e,fontFamily:t.fontFamily||"",textColor:t.color||"",primaryColor:"",accentColors:[]};try{let a=["a","button","h1","h2",".btn",".button",'[class*="primary"]','[class*="brand"]','[class*="accent"]',"nav a","header a",'[role="button"]'],o={};for(let u of a){let m=document.querySelectorAll(u);for(let h=0;h<Math.min(m.length,10);h++){let S=getComputedStyle(m[h]),g=S.color;g&&g!==r.textColor&&g!=="rgb(0, 0, 0)"&&g!=="rgba(0, 0, 0, 0)"&&!Ct(g)&&(o[g]=(o[g]||0)+1);let x=S.backgroundColor;x&&x!=="rgba(0, 0, 0, 0)"&&x!=="transparent"&&x!==r.bgColor&&!Ct(x)&&(o[x]=(o[x]||0)+1)}}let l=Object.keys(o).sort((u,m)=>o[m]-o[u]);r.primaryColor=l[0]||"",r.accentColors=l.slice(0,5)}catch(a){}return r}var Yt=`
2
+ var Je=Object.defineProperty,Ve=Object.defineProperties;var Qe=Object.getOwnPropertyDescriptors;var ae=Object.getOwnPropertySymbols;var Ze=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var le=(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)&&le(n,t,e[t]);if(ae)for(var t of ae(e))et.call(e,t)&&le(n,t,e[t]);return n},L=(n,e)=>Ve(n,Qe(e));var T=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",de="max-widget:register-tools",ce="max-widget:unregister-tool",R="max-widget:tool-result",he="max-widget:point-ask-result",G="max-widget:point-ask-cancel",k="max-widget:host-styles",pe="max-widget:debug-snapshot",H="max-widget:config-features";var ue="max-widget:expand",ge="max-widget:hide",me="max-widget:close",P="max-widget:request-page-context",fe="max-widget:start-point-ask",ve="max-widget:stop-point-ask",be="max-widget:execute-tool",ye="max-widget:request-debug-snapshot",xe="max-widget:request-host-styles",Se="max-widget:gdpr-consent",we="max-widget:navigate",Te="max-widget:message",Ee="max-widget:error";var U="max-widget:session-update",D="max-widget:session-request",I="max-widget:session-restore",N="max-widget:session-clear",Me="max-widget:draft-save",ke="max-widget:draft-request",Ie="max-widget:draft-restore",_e="max-widget:identity-set",Ce="max-widget:browser-metadata";var K=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(ce,{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(de,{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 B=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 ee(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 W=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]=ee(a,200))}let s=t.parentElement?ee(t.parentElement.innerText,300):"",o={elementText:ee(t.innerText,500),elementTag:t.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:it(t)};this.transport.send(he,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 $=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 X(){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 E(){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=`
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,4 +39,6 @@ var zt=Object.defineProperty;var Y=Object.getOwnPropertySymbols;var $t=Object.pr
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
- `,Jt='<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 Vt='<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>',Qt='<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 Lt(n){if(!n||n.charAt(0)!=="#")return null;let t=n.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),t.length!==6?null:{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function kt(n,t){let e=Lt(n);if(!e)return n;let s=Math.max(0,Math.min(255,Math.round(e.r+255*t))),i=Math.max(0,Math.min(255,Math.round(e.g+255*t))),r=Math.max(0,Math.min(255,Math.round(e.b+255*t))),a=o=>{let l=o.toString(16);return l.length===1?"0"+l:l};return"#"+a(s)+a(i)+a(r)}function R(n,t){let e=Lt(n);return e?`rgba(${e.r},${e.g},${e.b},${t})`:`rgba(99,102,241,${t})`}function Zt(n){let t=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!t)return"";let e=s=>{let i=s.toString(16);return i.length===1?"0"+i:i};return"#"+e(+t[1])+e(+t[2])+e(+t[3])}function It(n,t,e,s){let i=te(e)||s||"#6366f1",r=[n.btn,n.tab];for(let a of r)if(a)if(a.style.background="",a.style.backgroundColor="",a.style.border="none",a.style.backdropFilter="",a.style.webkitBackdropFilter="",a.style.boxShadow="",t==="glassmorphism")a.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",a.style.border="1px solid rgba(255, 255, 255, 0.18)",a.style.backdropFilter="blur(18px) saturate(180%)",a.style.webkitBackdropFilter="blur(18px) saturate(180%)",a.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(t==="auto-adaptive"){let o=kt(i,.08),l=kt(i,-.06);a.style.background=`linear-gradient(180deg, ${R(o,.96)}, ${R(l,.92)})`,a.style.border=`1px solid ${R(i,.24)}`,a.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${R(i,.22)}`}else a.style.backgroundColor=s||i,a.style.boxShadow="0 4px 12px rgba(0,0,0,0.3)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),t==="glassmorphism"?n.shell.classList.add("glassmorphism"):t==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function te(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?Zt(n):"":""}function Ot(n,t,e,s,i,r){if(document.querySelector(".max-widget-container"))return null;let a=document.createElement("style");i&&(a.nonce=i),a.textContent=Yt,document.head.appendChild(a);let o=document.createElement("div");o.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(o);let l=document.createElement("div");l.className="max-widget-shell "+(e?"right":"left"),o.appendChild(l);let u=document.createElement("div");u.className="max-widget-drag-handle",l.appendChild(u);let m=document.createElement("iframe");m.className="max-widget-frame",m.src=n+"/widget/"+t,m.setAttribute("allow","clipboard-write"),m.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),m.setAttribute("allowtransparency","true"),l.appendChild(m);let h=document.createElement("button");h.className="max-widget-btn",h.style.backgroundColor=s,h.innerHTML=Jt,o.appendChild(h);let S=!1,g=!1,x=!1,W=0,K=0,H=0,D=0;function E(d,p){let f=window.innerWidth-o.offsetWidth,$=window.innerHeight-o.offsetHeight;o.style.left=Math.max(0,Math.min(f,d))+"px",o.style.top=Math.max(0,Math.min($,p))+"px",o.style.bottom="auto",o.style.right="auto"}function X(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(o.style.left),top:parseInt(o.style.top)}))}catch(d){}N()}function N(){let d=l.offsetHeight||600,p=o.getBoundingClientRect(),f=p.top,$=window.innerHeight-p.bottom;f<d+8&&$>=d+8?(l.style.bottom="auto",l.style.top=o.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function Nt(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:p,top:f}=JSON.parse(d);typeof p=="number"&&typeof f=="number"&&E(p,f)}catch(d){}}Nt(),N(),h.addEventListener("pointerdown",d=>{if(d.button!==0)return;S=!0,g=!1,W=d.clientX,K=d.clientY;let p=o.getBoundingClientRect();H=p.left,D=p.top,E(H,D),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!S)return;let p=d.clientX-W,f=d.clientY-K;!g&&(Math.abs(p)>4||Math.abs(f)>4)&&(g=!0,h.classList.add("dragging")),g&&E(H+p,D+f)}),h.addEventListener("pointerup",()=>{S&&(S=!1,h.classList.remove("dragging"),g&&(x=!0,X(),g=!1))});let M=!1,b=!1,j=0,F=0,U=0,z=0;u.addEventListener("pointerdown",d=>{if(d.button!==0)return;M=!0,b=!1,j=d.clientX,F=d.clientY;let p=o.getBoundingClientRect();U=p.left,z=p.top,E(U,z),u.setPointerCapture(d.pointerId),d.preventDefault()}),u.addEventListener("pointermove",d=>{if(!M)return;let p=d.clientX-j,f=d.clientY-F;!b&&(Math.abs(p)>4||Math.abs(f)>4)&&(b=!0,u.classList.add("dragging")),b&&E(U+p,z+f)}),u.addEventListener("pointerup",()=>{M&&(M=!1,u.classList.remove("dragging"),b&&(X(),b=!1))});let v=document.createElement("button");v.className="max-widget-tab "+(e?"right":"left"),v.style.backgroundColor=s,v.innerHTML=e?Vt:Qt,document.body.appendChild(v);let B=!1;function Ut(){B=!1,l.classList.remove("expanded","panel-hidden"),o.classList.remove("panel-expanded","panel-hidden-state"),v.classList.remove("visible"),document.body.style.overflow=""}return h.addEventListener("click",()=>{if(x){x=!1;return}if(B){Ut();return}l.classList.contains("open")?(l.classList.remove("open"),r.onClose()):(N(),l.classList.add("open"),r.onOpen())}),v.addEventListener("click",()=>{l.classList.remove("panel-hidden"),o.classList.remove("panel-hidden-state"),v.classList.remove("visible")}),{container:o,shell:l,iframe:m,btn:h,tab:v,style:a}}function At(n,t,e){let{container:s,shell:i,tab:r}=n;t?(i.classList.contains("open")||i.classList.add("open"),i.classList.add("expanded"),s.classList.add("panel-expanded"),i.classList.remove("panel-hidden"),s.classList.remove("panel-hidden-state"),r.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(i.classList.remove("expanded","panel-hidden"),s.classList.remove("panel-expanded","panel-hidden-state"),r.classList.remove("visible"),document.body.style.overflow="")}function Gt(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Rt(n){n.container.remove(),n.tab.remove(),n.style.remove()}function Pt(n){n.shell.classList.add("open")}function Ht(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 P=class{constructor(t){this.emitter=new C;this.debug=new O;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.storedSessionToken=null;this.storedIdentity=null;this.key=t.key,this.isRight=t.position!=="bottom-left",this.nonce=t.nonce||null;let e=document.querySelector(`script[data-key="${t.key}"]`);e&&e.src?this.baseUrl=e.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):t.baseUrl?this.baseUrl=t.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new _(this.baseUrl),this.tools=new I(this.transport),this.pointAndAsk=new A(this.transport),this.spaDetector=new G(()=>{var s;if(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.ui){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}}),this.init()}readOrCreateVisitorId(){let t=`maxai_vid_${this.key}`;try{let s=localStorage.getItem(t);if(s)return s}catch(s){}let e=this.getCookie(t);if(e){try{localStorage.setItem(t,e)}catch(s){}return e}return this.generateUUID()}persistVisitorId(t){let e=`maxai_vid_${this.key}`;try{localStorage.setItem(e,t)}catch(s){}this.setCookie(e,t,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(t){}return null}saveSessionToken(t){this.storedSessionToken=t;try{localStorage.setItem(`maxai_st_${this.key}`,t)}catch(e){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(t){}}readStoredIdentity(){try{let t=localStorage.getItem(`maxai_identity_${this.key}`);if(t)return JSON.parse(t)}catch(t){}return null}saveIdentity(t){this.storedIdentity=t;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(t))}catch(e){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}setCookie(t,e,s){try{let i=new Date;i.setTime(i.getTime()+s*864e5),document.cookie=`${t}=${e};expires=${i.toUTCString()};path=/;SameSite=Lax;Secure`}catch(i){}}getCookie(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?e[1]:null}catch(e){return null}}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(e){t={}}this.config={pageContext:t.enable_page_context||!1,pointAndAsk:t.enable_point_and_ask||!1,debugMode:t.enable_debug_mode||!1,bugReport:t.enable_bug_reports||!1,clientTools:t.enable_client_tools||!1,autoTheme:t.theme_mode!=="manual",themeMode:t.theme_mode||"manual",gdprRequired:t.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=t.primary_color||"#6366f1",this.ui=Ot(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.ui&&(this.applyTheme(this.config.autoTheme?w().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var e,s;if(this.transport.markReady(),this.config&&this.transport.send(nt,{features:this.config}),(!((e=this.config)!=null&&e.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme)){let i=w();this.applyTheme(i.primaryColor),this.transport.send(T,{styles:i})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers())}setupMessageHandlers(){this.transport.listen(st,t=>{this.ui&&At(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(it,()=>{this.ui&&Gt(this.ui)}),this.transport.listen(rt,()=>{this.close()}),this.transport.listen(ot,()=>{this.sendPageContext()}),this.transport.listen(at,()=>{this.pointAndAsk.start()}),this.transport.listen(lt,()=>{this.pointAndAsk.stop()}),this.transport.listen(dt,t=>{let e=t.toolCallId,s=t.slug||t.name,i=t.args;this.emitter.emit("tool:call",{id:e,name:s,args:i}),this.tools.execute(e,s,i).then(r=>{this.emitter.emit("tool:result",{id:e,name:s,ok:r.ok,error:r.error})})}),this.transport.listen(ct,()=>{this.transport.send(et,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(pt,()=>{let t=w();this.applyTheme(t.primaryColor),this.transport.send(T,{styles:t})}),this.transport.listen(ht,()=>{var t,e;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme){let s=w();this.applyTheme(s.primaryColor),this.transport.send(T,{styles:s})}}),this.transport.listen(gt,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(ut,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(mt,t=>{this.emitter.emit("error",{message:t.error})}),this.transport.listen(xt,()=>{this.transport.send(vt,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(ft,t=>{t.sessionToken&&this.saveSessionToken(t.sessionToken)}),this.transport.listen(yt,()=>{this.clearSessionToken()}),this.transport.listen(St,t=>{try{localStorage.setItem(`maxai_draft_${this.key}`,t.text||"")}catch(e){}}),this.transport.listen(bt,()=>{let t="";try{t=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(e){}this.transport.send(wt,{text:t})})}applyTheme(t){!this.ui||!this.config||It(this.ui,this.config.themeMode,t,this.primaryColor)}sendPageContext(){var s;if(!this.consentGiven&&((s=this.config)!=null&&s.gdprRequired))return;let t=Mt(this.key),e=_t(t,this.explicitContext);this.transport.send(V,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}setIdentity(t){this.saveIdentity(t),this.transport.send(Et,{identityPayload:t})}registerTool(t){return this.tools.register(t)}unregisterTool(t){this.tools.unregister(t)}on(t,e){return this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}open(){this.ui&&(Pt(this.ui),this.emitter.emit("open"))}close(){this.ui&&(Ht(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&Rt(this.ui),this.ui=null}};var c=null,Dt={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new P(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,t){return c?c.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},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 t=n.getAttribute("data-key");t&&Dt.init({key:t,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=Dt);export{Dt as MaxAI};
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 S(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, ${S(a,.96)}, ${S(l,.92)})`,r.style.border=`1px solid ${S(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${S(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${S(s,.55)}, ${S(s,.4)})`,r.style.border=`1px solid ${S(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,te=0,ne=0,j=0,Y=0;function M(d,u){let v=window.innerWidth-a.offsetWidth,Z=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(v,d))+"px",a.style.top=Math.max(0,Math.min(Z,u))+"px",a.style.bottom="auto",a.style.right="auto"}function ie(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}J()}function J(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),v=u.top,Z=window.innerHeight-u.bottom;v<d+8&&Z>=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"&&M(u,v)}catch(d){}}je(),J(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,te=d.clientX,ne=d.clientY;let u=a.getBoundingClientRect();j=u.left,Y=u.top,M(j,Y),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-te,v=d.clientY-ne;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&M(j+u,Y+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,ie(),m=!1))});let C=!1,w=!1,se=0,re=0,V=0,Q=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,w=!1,se=d.clientX,re=d.clientY;let u=a.getBoundingClientRect();V=u.left,Q=u.top,M(V,Q),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-se,v=d.clientY-re;!w&&(Math.abs(u)>4||Math.abs(v)>4)&&(w=!0,h.classList.add("dragging")),w&&M(V+u,Q+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),w&&(ie(),w=!1))});let x=document.createElement("button");x.className="max-widget-tab "+(t?"right":"left"),x.style.backgroundColor=i,x.innerHTML=t?dt:ct,document.body.appendChild(x);let oe=!1;function Ye(){oe=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),x.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(oe){Ye();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(J(),l.classList.add("open"),o.onOpen())}),x.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),x.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:x,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 q=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=X(),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 z=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+`
43
+ `)}if(r.length>e.join(" ").length)return Xe(r.trim(),3e3)}return Xe(e.join(`
44
+ `),3e3)}function _(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 T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(H,{features:e.config}),o()}),s.listen(D,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(U,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(N,()=>{}),s.listen(P,()=>{o()}),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,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),_(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=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var F=class{constructor(e){this.emitter=new O;this.debug=new B;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 T(this.baseUrl),this.tools=new K(this.transport),this.pointAndAsk=new W(this.transport),this.spaDetector=new $(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{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?E().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=E();this.applyTheme(r.primaryColor),this.transport.send(k,{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(ue,e=>{this.ui&&Ne(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ge,()=>{this.ui&&Ke(this.ui)}),this.transport.listen(me,()=>{this.close()}),this.transport.listen(P,()=>{this.sendPageContext()}),this.transport.listen(fe,()=>{this.pointAndAsk.start()}),this.transport.listen(ve,()=>{this.pointAndAsk.stop()}),this.transport.listen("max-widget:request-tools",()=>{this.tools.hasTools()&&this.tools.sendList()}),this.transport.listen(be,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(ye,()=>{this.transport.send(pe,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(xe,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{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=E();this.applyTheme(s.primaryColor),this.transport.send(k,{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(D,()=>{this.transport.send(I,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(U,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(N,()=>{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(Ie,{text:e})})}startIntelligence(e){this.presence||(this.presence=new q({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new z({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=X();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(I,{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=_(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(_e,{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 F(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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxaiagent/widget-sdk",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
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",