@maxaiagent/widget-sdk 1.0.1 → 1.0.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.global.js +2 -2
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.global.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* @maxaiagent/widget-sdk v1.0.1 | MIT License | maxaiagent.app */
|
|
2
|
-
"use strict";var MaxAISDK=(()=>{var u=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames,R=Object.getOwnPropertySymbols;var G=Object.prototype.hasOwnProperty,pt=Object.prototype.propertyIsEnumerable;var k=(n,t,e)=>t in n?u(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))G.call(t,e)&&k(n,e,t[e]);if(R)for(var e of R(t))pt.call(t,e)&&k(n,e,t[e]);return n};var ct=(n,t)=>{for(var e in t)u(n,e,{get:t[e],enumerable:!0})},ht=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!G.call(n,s)&&s!==e&&u(n,s,{get:()=>t[s],enumerable:!(i=lt(t,s))||i.enumerable});return n};var ut=n=>ht(u({},"__esModule",{value:!0}),n);var bt={};ct(bt,{MaxAI:()=>H});var g=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 i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}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,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var m=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 i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var I="max-widget:page-context",P="max-widget:register-tools",D="max-widget:unregister-tool",f="max-widget:tool-result",U="max-widget:point-ask-result",v="max-widget:point-ask-cancel",x="max-widget:host-styles",N="max-widget:debug-snapshot",X="max-widget:config-features";var q="max-widget:expand",z="max-widget:hide",W="max-widget:request-page-context",K="max-widget:start-point-ask",j="max-widget:stop-point-ask",F="max-widget:execute-tool",B="max-widget:request-debug-snapshot",Y="max-widget:request-host-styles",$="max-widget:gdpr-consent",Z="max-widget:navigate",Q="max-widget:message",V="max-widget:error";var y=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(D,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(f,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(f,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(f,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(P,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function w(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var mt=[/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 ft(n){let t=JSON.stringify(n);for(let e of mt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var E=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.origFetch=null;this.origXHROpen=null;this.origXHRSend=null;this.errorHandler=null;this.rejectionHandler=null;this.initialized=!1}init(){if(this.initialized)return;this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...i)=>{this.origConsole[e](...i);try{let s=i.map(o=>{try{return typeof o=="string"?o:JSON.stringify(o)}catch(a){return String(o)}}).join(" ");this.consoleLogs.push({level:e,message:w(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};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),this.origFetch=window.fetch,window.fetch=(...e)=>{let i=e[0],o=((e[1]||{}).method||"GET").toUpperCase(),a=Date.now();return this.origFetch(...e).then(r=>(this.networkLog.push({method:o,url:typeof i=="string"?w(i,200):"(Request)",status:r.status,duration:Date.now()-a,timestamp:a}),this.networkLog.length>30&&this.networkLog.shift(),r)).catch(r=>{throw this.networkLog.push({method:o,url:typeof i=="string"?w(i,200):"(Request)",status:0,error:r.message||"Network error",duration:Date.now()-a,timestamp:a}),this.networkLog.length>30&&this.networkLog.shift(),r})},this.origXHROpen=XMLHttpRequest.prototype.open,this.origXHRSend=XMLHttpRequest.prototype.send;let t=this;XMLHttpRequest.prototype.open=function(e,i){return this._m=e,this._u=String(i),this._t=Date.now(),t.origXHROpen.apply(this,arguments)},XMLHttpRequest.prototype.send=function(){let e=this;return e.addEventListener("loadend",()=>{t.networkLog.push({method:(e._m||"GET").toUpperCase(),url:w(e._u||"",200),status:e.status,duration:Date.now()-(e._t||Date.now()),timestamp:e._t||Date.now()}),t.networkLog.length>30&&t.networkLog.shift()}),t.origXHRSend.apply(this,arguments)}}getSnapshot(){return ft({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];this.origFetch&&(window.fetch=this.origFetch),this.origXHROpen&&(XMLHttpRequest.prototype.open=this.origXHROpen),this.origXHRSend&&(XMLHttpRequest.prototype.send=this.origXHRSend),this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function L(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 i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function xt(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 S=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(v),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||xt(e)){this.transport.send(v),this.cleanup();return}let i={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let r=e.getAttribute(a);r&&(i[a]=L(r,200))}let s=e.parentElement?L(e.parentElement.innerText,300):"",o={elementText:L(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:vt(e)};this.transport.send(U,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(v),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 yt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function J(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 i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(d=>{try{t.jsonLd.push(JSON.parse(d.textContent||""))}catch(p){}})}catch(r){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=yt(o.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(r=>{if(r.name.startsWith("data-context-")){let d=r.name.replace("data-context-","").replace(/-/g,"_");t.customContext[d]=r.value}}),t}function tt(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var b=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;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{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 M(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let a=document.querySelectorAll(o);for(let r=0;r<Math.min(a.length,10);r++){let d=getComputedStyle(a[r]),p=d.color;p&&p!==t.textColor&&p!=="rgb(0, 0, 0)"&&p!=="rgba(0, 0, 0, 0)"&&(i[p]=(i[p]||0)+1);let c=d.backgroundColor;c&&c!=="rgba(0, 0, 0, 0)"&&c!=="transparent"&&c!==t.bgColor&&(i[c]=(i[c]||0)+1)}}let s=Object.keys(i).sort((o,a)=>i[a]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var wt=`
|
|
2
|
+
"use strict";var MaxAISDK=(()=>{var u=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols;var H=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var k=(n,t,e)=>t in n?u(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))H.call(t,e)&&k(n,e,t[e]);if(G)for(var e of G(t))ct.call(t,e)&&k(n,e,t[e]);return n};var pt=(n,t)=>{for(var e in t)u(n,e,{get:t[e],enumerable:!0})},ht=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!H.call(n,s)&&s!==e&&u(n,s,{get:()=>t[s],enumerable:!(i=lt(t,s))||i.enumerable});return n};var ut=n=>ht(u({},"__esModule",{value:!0}),n);var St={};pt(St,{MaxAI:()=>A});var g=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 i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}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,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var m=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 i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",P="max-widget:register-tools",I="max-widget:unregister-tool",f="max-widget:tool-result",U="max-widget:point-ask-result",v="max-widget:point-ask-cancel",x="max-widget:host-styles",N="max-widget:debug-snapshot",D="max-widget:config-features";var z="max-widget:expand",W="max-widget:hide",K="max-widget:request-page-context",j="max-widget:start-point-ask",q="max-widget:stop-point-ask",X="max-widget:execute-tool",F="max-widget:request-debug-snapshot",B="max-widget:request-host-styles",Y="max-widget:gdpr-consent",$="max-widget:navigate",Z="max-widget:message",Q="max-widget:error";var y=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(I,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(f,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(f,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(f,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(P,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function V(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var mt=[/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 ft(n){let t=JSON.stringify(n);for(let e of mt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){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 t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let i=e.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:t,message:V(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};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 i of t.getEntries()){let s=i,o=(e=s.responseStatus)!=null?e:0;this.networkLog.push(h({method:"GET",url:V(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(t){}}}getSnapshot(){return ft({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 _(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 i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function xt(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 w=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(v),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||xt(e)){this.transport.send(v),this.cleanup();return}let i={};for(let d of["class","id","href","src","alt","title","data-id","data-name"]){let a=e.getAttribute(d);a&&(i[d]=_(a,200))}let s=e.parentElement?_(e.parentElement.innerText,300):"",o={elementText:_(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:vt(e)};this.transport.send(U,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(v),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 yt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function J(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 i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=yt(o.innerText,2e3));let d=document.querySelector(`script[data-key="${n}"]`);return d&&Array.from(d.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=a.value}}),t}function tt(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var E=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;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{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 S(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let d=document.querySelectorAll(o);for(let a=0;a<Math.min(d.length,10);a++){let l=getComputedStyle(d[a]),c=l.color;c&&c!==t.textColor&&c!=="rgb(0, 0, 0)"&&c!=="rgba(0, 0, 0, 0)"&&(i[c]=(i[c]||0)+1);let p=l.backgroundColor;p&&p!=="rgba(0, 0, 0, 0)"&&p!=="transparent"&&p!==t.bgColor&&(i[p]=(i[p]||0)+1)}}let s=Object.keys(i).sort((o,d)=>i[d]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var bt=`
|
|
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}
|
|
@@ -26,4 +26,4 @@
|
|
|
26
26
|
.max-widget-tab svg{width:18px;height:18px;fill:white}
|
|
27
27
|
@media(max-width:420px){.max-widget-frame{width:calc(100vw - 40px);height:calc(100vh - 120px)}}
|
|
28
28
|
@media(max-width:420px){.max-widget-frame.expanded{width:100vw}}
|
|
29
|
-
`,
|
|
29
|
+
`,L='<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>',C='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>',wt='<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>',Et='<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 et(n,t,e,i,s,o){let d=document.createElement("style");s&&(d.nonce=s),d.textContent=bt,document.head.appendChild(d);let a=document.createElement("div");a.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(a);let l=document.createElement("iframe");l.className="max-widget-frame "+(e?"right":"left"),l.src=n+"/widget/"+t,l.setAttribute("allow","clipboard-write"),a.appendChild(l);let c=document.createElement("button");c.className="max-widget-btn",c.style.backgroundColor=i,c.innerHTML=L,a.appendChild(c);let p=document.createElement("button");p.className="max-widget-tab "+(e?"right":"left"),p.style.backgroundColor=i,p.innerHTML=e?wt:Et,document.body.appendChild(p);let T=!1,O=!1;function at(){O=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),p.classList.remove("visible"),l.style.position="",l.style.top="",l.style.bottom="",document.body.style.overflow=""}return c.addEventListener("click",()=>{if(O){at();return}T=!T,T?(l.classList.add("open"),c.innerHTML=C,o.onOpen()):(l.classList.remove("open"),c.innerHTML=L,o.onClose())}),p.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),p.classList.remove("visible")}),{container:a,iframe:l,btn:c,tab:p,style:d}}function nt(n,t,e){let{container:i,iframe:s,btn:o,tab:d}=n;t?(s.classList.contains("open")||(s.classList.add("open"),o.innerHTML=C),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),d.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"),d.classList.remove("visible"),s.style.position="",s.style.top="",s.style.bottom="",document.body.style.overflow="")}function it(n){n.iframe.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function st(n){n.container.remove(),n.tab.remove(),n.style.remove()}function ot(n){n.iframe.classList.add("open"),n.btn.innerHTML=C}function rt(n){n.iframe.classList.remove("open"),n.btn.innerHTML=L}var M=class{constructor(t){this.emitter=new m;this.debug=new b;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=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.transport=new g(this.baseUrl),this.tools=new y(this.transport),this.pointAndAsk=new w(this.transport),this.spaDetector=new E(()=>this.sendPageContext()),this.init()}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){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.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init();let e=t.primary_color||"#6366f1";this.ui=et(this.baseUrl,this.key,this.isRight,e,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s;this.transport.markReady(),this.config&&this.transport.send(D,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.transport.send(x,{styles:S()})),this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers()}setupMessageHandlers(){this.transport.listen(z,t=>{this.ui&&nt(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(W,()=>{this.ui&&it(this.ui)}),this.transport.listen(K,()=>{this.sendPageContext()}),this.transport.listen(j,()=>{this.pointAndAsk.start()}),this.transport.listen(q,()=>{this.pointAndAsk.stop()}),this.transport.listen(X,t=>{let{toolCallId:e,name:i,args:s}=t;this.emitter.emit("tool:call",{id:e,name:i,args:s}),this.tools.execute(e,i,s).then(()=>{this.emitter.emit("tool:result",{id:e,name:i,ok:!0})})}),this.transport.listen(F,()=>{this.transport.send(N,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(B,()=>{this.transport.send(x,{styles:S()})}),this.transport.listen(Y,()=>{var t,e;this.consentGiven=!0,this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme&&this.transport.send(x,{styles:S()})}),this.transport.listen($,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(Z,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(Q,t=>{this.emitter.emit("error",{message:t.error})})}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let t=J(this.key),e=tt(t,this.explicitContext);this.transport.send(R,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}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&&(ot(this.ui),this.emitter.emit("open"))}close(){this.ui&&(rt(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&st(this.ui),this.ui=null}};var r=null,A={init(n){return r?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),r):(r=new M(n),r)},setPageContext(n){if(!r){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}r.setPageContext(n)},registerTool(n){return r?r.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){r&&r.unregisterTool(n)},on(n,t){return r?r.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},open(){r==null||r.open()},close(){r==null||r.close()},destroy(){r==null||r.destroy(),r=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let t=n.getAttribute("data-key");t&&A.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=A);return ut(St);})();
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* @maxaiagent/widget-sdk v1.0.1 | MIT License | maxaiagent.app */
|
|
2
|
-
"use strict";var u=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames,R=Object.getOwnPropertySymbols;var G=Object.prototype.hasOwnProperty,pt=Object.prototype.propertyIsEnumerable;var k=(n,t,e)=>t in n?u(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))G.call(t,e)&&k(n,e,t[e]);if(R)for(var e of R(t))pt.call(t,e)&&k(n,e,t[e]);return n};var ct=(n,t)=>{for(var e in t)u(n,e,{get:t[e],enumerable:!0})},ht=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!G.call(n,s)&&s!==e&&u(n,s,{get:()=>t[s],enumerable:!(i=lt(t,s))||i.enumerable});return n};var ut=n=>ht(u({},"__esModule",{value:!0}),n);var bt={};ct(bt,{MaxAI:()=>H});module.exports=ut(bt);var g=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 i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}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,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var m=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 i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var I="max-widget:page-context",P="max-widget:register-tools",D="max-widget:unregister-tool",f="max-widget:tool-result",U="max-widget:point-ask-result",v="max-widget:point-ask-cancel",x="max-widget:host-styles",N="max-widget:debug-snapshot",X="max-widget:config-features";var q="max-widget:expand",z="max-widget:hide",W="max-widget:request-page-context",K="max-widget:start-point-ask",j="max-widget:stop-point-ask",F="max-widget:execute-tool",B="max-widget:request-debug-snapshot",Y="max-widget:request-host-styles",$="max-widget:gdpr-consent",Z="max-widget:navigate",Q="max-widget:message",V="max-widget:error";var y=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(D,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(f,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(f,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(f,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(P,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function w(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var mt=[/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 ft(n){let t=JSON.stringify(n);for(let e of mt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var E=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.origFetch=null;this.origXHROpen=null;this.origXHRSend=null;this.errorHandler=null;this.rejectionHandler=null;this.initialized=!1}init(){if(this.initialized)return;this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...i)=>{this.origConsole[e](...i);try{let s=i.map(o=>{try{return typeof o=="string"?o:JSON.stringify(o)}catch(a){return String(o)}}).join(" ");this.consoleLogs.push({level:e,message:w(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};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),this.origFetch=window.fetch,window.fetch=(...e)=>{let i=e[0],o=((e[1]||{}).method||"GET").toUpperCase(),a=Date.now();return this.origFetch(...e).then(r=>(this.networkLog.push({method:o,url:typeof i=="string"?w(i,200):"(Request)",status:r.status,duration:Date.now()-a,timestamp:a}),this.networkLog.length>30&&this.networkLog.shift(),r)).catch(r=>{throw this.networkLog.push({method:o,url:typeof i=="string"?w(i,200):"(Request)",status:0,error:r.message||"Network error",duration:Date.now()-a,timestamp:a}),this.networkLog.length>30&&this.networkLog.shift(),r})},this.origXHROpen=XMLHttpRequest.prototype.open,this.origXHRSend=XMLHttpRequest.prototype.send;let t=this;XMLHttpRequest.prototype.open=function(e,i){return this._m=e,this._u=String(i),this._t=Date.now(),t.origXHROpen.apply(this,arguments)},XMLHttpRequest.prototype.send=function(){let e=this;return e.addEventListener("loadend",()=>{t.networkLog.push({method:(e._m||"GET").toUpperCase(),url:w(e._u||"",200),status:e.status,duration:Date.now()-(e._t||Date.now()),timestamp:e._t||Date.now()}),t.networkLog.length>30&&t.networkLog.shift()}),t.origXHRSend.apply(this,arguments)}}getSnapshot(){return ft({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];this.origFetch&&(window.fetch=this.origFetch),this.origXHROpen&&(XMLHttpRequest.prototype.open=this.origXHROpen),this.origXHRSend&&(XMLHttpRequest.prototype.send=this.origXHRSend),this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function L(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 i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function xt(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 S=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(v),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||xt(e)){this.transport.send(v),this.cleanup();return}let i={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let r=e.getAttribute(a);r&&(i[a]=L(r,200))}let s=e.parentElement?L(e.parentElement.innerText,300):"",o={elementText:L(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:vt(e)};this.transport.send(U,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(v),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 yt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function J(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 i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(d=>{try{t.jsonLd.push(JSON.parse(d.textContent||""))}catch(p){}})}catch(r){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=yt(o.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(r=>{if(r.name.startsWith("data-context-")){let d=r.name.replace("data-context-","").replace(/-/g,"_");t.customContext[d]=r.value}}),t}function tt(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var b=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;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{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 M(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let a=document.querySelectorAll(o);for(let r=0;r<Math.min(a.length,10);r++){let d=getComputedStyle(a[r]),p=d.color;p&&p!==t.textColor&&p!=="rgb(0, 0, 0)"&&p!=="rgba(0, 0, 0, 0)"&&(i[p]=(i[p]||0)+1);let c=d.backgroundColor;c&&c!=="rgba(0, 0, 0, 0)"&&c!=="transparent"&&c!==t.bgColor&&(i[c]=(i[c]||0)+1)}}let s=Object.keys(i).sort((o,a)=>i[a]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var wt=`
|
|
2
|
+
"use strict";var u=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols;var H=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var k=(n,t,e)=>t in n?u(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))H.call(t,e)&&k(n,e,t[e]);if(G)for(var e of G(t))ct.call(t,e)&&k(n,e,t[e]);return n};var pt=(n,t)=>{for(var e in t)u(n,e,{get:t[e],enumerable:!0})},ht=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!H.call(n,s)&&s!==e&&u(n,s,{get:()=>t[s],enumerable:!(i=lt(t,s))||i.enumerable});return n};var ut=n=>ht(u({},"__esModule",{value:!0}),n);var St={};pt(St,{MaxAI:()=>A});module.exports=ut(St);var g=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 i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}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,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var m=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 i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",P="max-widget:register-tools",I="max-widget:unregister-tool",f="max-widget:tool-result",U="max-widget:point-ask-result",v="max-widget:point-ask-cancel",x="max-widget:host-styles",N="max-widget:debug-snapshot",D="max-widget:config-features";var z="max-widget:expand",W="max-widget:hide",K="max-widget:request-page-context",j="max-widget:start-point-ask",q="max-widget:stop-point-ask",X="max-widget:execute-tool",F="max-widget:request-debug-snapshot",B="max-widget:request-host-styles",Y="max-widget:gdpr-consent",$="max-widget:navigate",Z="max-widget:message",Q="max-widget:error";var y=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(I,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(f,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(f,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(f,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(P,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function V(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var mt=[/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 ft(n){let t=JSON.stringify(n);for(let e of mt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){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 t of["log","warn","error"])this.origConsole[t]=console[t].bind(console),console[t]=(...e)=>{this.origConsole[t](...e);try{let i=e.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:t,message:V(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};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 i of t.getEntries()){let s=i,o=(e=s.responseStatus)!=null?e:0;this.networkLog.push(h({method:"GET",url:V(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(t){}}}getSnapshot(){return ft({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 _(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 i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function xt(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 w=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(v),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||xt(e)){this.transport.send(v),this.cleanup();return}let i={};for(let d of["class","id","href","src","alt","title","data-id","data-name"]){let a=e.getAttribute(d);a&&(i[d]=_(a,200))}let s=e.parentElement?_(e.parentElement.innerText,300):"",o={elementText:_(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:vt(e)};this.transport.send(U,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(v),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 yt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function J(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 i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=yt(o.innerText,2e3));let d=document.querySelector(`script[data-key="${n}"]`);return d&&Array.from(d.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=a.value}}),t}function tt(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var E=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;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{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 S(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let d=document.querySelectorAll(o);for(let a=0;a<Math.min(d.length,10);a++){let l=getComputedStyle(d[a]),c=l.color;c&&c!==t.textColor&&c!=="rgb(0, 0, 0)"&&c!=="rgba(0, 0, 0, 0)"&&(i[c]=(i[c]||0)+1);let p=l.backgroundColor;p&&p!=="rgba(0, 0, 0, 0)"&&p!=="transparent"&&p!==t.bgColor&&(i[p]=(i[p]||0)+1)}}let s=Object.keys(i).sort((o,d)=>i[d]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var bt=`
|
|
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}
|
|
@@ -26,4 +26,4 @@
|
|
|
26
26
|
.max-widget-tab svg{width:18px;height:18px;fill:white}
|
|
27
27
|
@media(max-width:420px){.max-widget-frame{width:calc(100vw - 40px);height:calc(100vh - 120px)}}
|
|
28
28
|
@media(max-width:420px){.max-widget-frame.expanded{width:100vw}}
|
|
29
|
-
`,
|
|
29
|
+
`,L='<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>',C='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>',wt='<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>',Et='<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 et(n,t,e,i,s,o){let d=document.createElement("style");s&&(d.nonce=s),d.textContent=bt,document.head.appendChild(d);let a=document.createElement("div");a.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(a);let l=document.createElement("iframe");l.className="max-widget-frame "+(e?"right":"left"),l.src=n+"/widget/"+t,l.setAttribute("allow","clipboard-write"),a.appendChild(l);let c=document.createElement("button");c.className="max-widget-btn",c.style.backgroundColor=i,c.innerHTML=L,a.appendChild(c);let p=document.createElement("button");p.className="max-widget-tab "+(e?"right":"left"),p.style.backgroundColor=i,p.innerHTML=e?wt:Et,document.body.appendChild(p);let T=!1,O=!1;function at(){O=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),p.classList.remove("visible"),l.style.position="",l.style.top="",l.style.bottom="",document.body.style.overflow=""}return c.addEventListener("click",()=>{if(O){at();return}T=!T,T?(l.classList.add("open"),c.innerHTML=C,o.onOpen()):(l.classList.remove("open"),c.innerHTML=L,o.onClose())}),p.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),p.classList.remove("visible")}),{container:a,iframe:l,btn:c,tab:p,style:d}}function nt(n,t,e){let{container:i,iframe:s,btn:o,tab:d}=n;t?(s.classList.contains("open")||(s.classList.add("open"),o.innerHTML=C),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),d.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"),d.classList.remove("visible"),s.style.position="",s.style.top="",s.style.bottom="",document.body.style.overflow="")}function it(n){n.iframe.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function st(n){n.container.remove(),n.tab.remove(),n.style.remove()}function ot(n){n.iframe.classList.add("open"),n.btn.innerHTML=C}function rt(n){n.iframe.classList.remove("open"),n.btn.innerHTML=L}var M=class{constructor(t){this.emitter=new m;this.debug=new b;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=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.transport=new g(this.baseUrl),this.tools=new y(this.transport),this.pointAndAsk=new w(this.transport),this.spaDetector=new E(()=>this.sendPageContext()),this.init()}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){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.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init();let e=t.primary_color||"#6366f1";this.ui=et(this.baseUrl,this.key,this.isRight,e,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s;this.transport.markReady(),this.config&&this.transport.send(D,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.transport.send(x,{styles:S()})),this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers()}setupMessageHandlers(){this.transport.listen(z,t=>{this.ui&&nt(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(W,()=>{this.ui&&it(this.ui)}),this.transport.listen(K,()=>{this.sendPageContext()}),this.transport.listen(j,()=>{this.pointAndAsk.start()}),this.transport.listen(q,()=>{this.pointAndAsk.stop()}),this.transport.listen(X,t=>{let{toolCallId:e,name:i,args:s}=t;this.emitter.emit("tool:call",{id:e,name:i,args:s}),this.tools.execute(e,i,s).then(()=>{this.emitter.emit("tool:result",{id:e,name:i,ok:!0})})}),this.transport.listen(F,()=>{this.transport.send(N,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(B,()=>{this.transport.send(x,{styles:S()})}),this.transport.listen(Y,()=>{var t,e;this.consentGiven=!0,this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme&&this.transport.send(x,{styles:S()})}),this.transport.listen($,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(Z,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(Q,t=>{this.emitter.emit("error",{message:t.error})})}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let t=J(this.key),e=tt(t,this.explicitContext);this.transport.send(R,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}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&&(ot(this.ui),this.emitter.emit("open"))}close(){this.ui&&(rt(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&st(this.ui),this.ui=null}};var r=null,A={init(n){return r?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),r):(r=new M(n),r)},setPageContext(n){if(!r){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}r.setPageContext(n)},registerTool(n){return r?r.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){r&&r.unregisterTool(n)},on(n,t){return r?r.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},open(){r==null||r.open()},close(){r==null||r.close()},destroy(){r==null||r.destroy(),r=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let t=n.getAttribute("data-key");t&&A.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=A);
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* @maxaiagent/widget-sdk v1.0.1 | MIT License | maxaiagent.app */
|
|
2
|
-
var rt=Object.defineProperty;var H=Object.getOwnPropertySymbols;var at=Object.prototype.hasOwnProperty,lt=Object.prototype.propertyIsEnumerable;var O=(n,t,e)=>t in n?rt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))at.call(t,e)&&O(n,e,t[e]);if(H)for(var e of H(t))lt.call(t,e)&&O(n,e,t[e]);return n};var u=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 i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}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,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var g=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 i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var R="max-widget:page-context",k="max-widget:register-tools",G="max-widget:unregister-tool",m="max-widget:tool-result",I="max-widget:point-ask-result",f="max-widget:point-ask-cancel",v="max-widget:host-styles",P="max-widget:debug-snapshot",D="max-widget:config-features";var U="max-widget:expand",N="max-widget:hide",X="max-widget:request-page-context",q="max-widget:start-point-ask",z="max-widget:stop-point-ask",W="max-widget:execute-tool",K="max-widget:request-debug-snapshot",j="max-widget:request-host-styles",F="max-widget:gdpr-consent",B="max-widget:navigate",Y="max-widget:message",$="max-widget:error";var x=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(G,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(m,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(m,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(m,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(k,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function y(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var pt=[/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 ct(n){let t=JSON.stringify(n);for(let e of pt)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var w=class{constructor(){this.consoleLogs=[];this.networkLog=[];this.errors=[];this.origConsole={};this.origFetch=null;this.origXHROpen=null;this.origXHRSend=null;this.errorHandler=null;this.rejectionHandler=null;this.initialized=!1}init(){if(this.initialized)return;this.initialized=!0;for(let e of["log","warn","error"])this.origConsole[e]=console[e].bind(console),console[e]=(...i)=>{this.origConsole[e](...i);try{let s=i.map(o=>{try{return typeof o=="string"?o:JSON.stringify(o)}catch(a){return String(o)}}).join(" ");this.consoleLogs.push({level:e,message:y(s,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(s){}};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),this.origFetch=window.fetch,window.fetch=(...e)=>{let i=e[0],o=((e[1]||{}).method||"GET").toUpperCase(),a=Date.now();return this.origFetch(...e).then(r=>(this.networkLog.push({method:o,url:typeof i=="string"?y(i,200):"(Request)",status:r.status,duration:Date.now()-a,timestamp:a}),this.networkLog.length>30&&this.networkLog.shift(),r)).catch(r=>{throw this.networkLog.push({method:o,url:typeof i=="string"?y(i,200):"(Request)",status:0,error:r.message||"Network error",duration:Date.now()-a,timestamp:a}),this.networkLog.length>30&&this.networkLog.shift(),r})},this.origXHROpen=XMLHttpRequest.prototype.open,this.origXHRSend=XMLHttpRequest.prototype.send;let t=this;XMLHttpRequest.prototype.open=function(e,i){return this._m=e,this._u=String(i),this._t=Date.now(),t.origXHROpen.apply(this,arguments)},XMLHttpRequest.prototype.send=function(){let e=this;return e.addEventListener("loadend",()=>{t.networkLog.push({method:(e._m||"GET").toUpperCase(),url:y(e._u||"",200),status:e.status,duration:Date.now()-(e._t||Date.now()),timestamp:e._t||Date.now()}),t.networkLog.length>30&&t.networkLog.shift()}),t.origXHRSend.apply(this,arguments)}}getSnapshot(){return ct({consoleLogs:this.consoleLogs.slice(),networkLog:this.networkLog.slice(),errors:this.errors.slice(),pageUrl:window.location.href,timestamp:Date.now()})}destroy(){if(this.initialized){for(let t of Object.keys(this.origConsole))console[t]=this.origConsole[t];this.origFetch&&(window.fetch=this.origFetch),this.origXHROpen&&(XMLHttpRequest.prototype.open=this.origXHROpen),this.origXHRSend&&(XMLHttpRequest.prototype.send=this.origXHRSend),this.errorHandler&&window.removeEventListener("error",this.errorHandler),this.rejectionHandler&&window.removeEventListener("unhandledrejection",this.rejectionHandler),this.initialized=!1}}};function _(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function ht(n){let t=[],e=n;for(;e&&e.nodeType===1;){let i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function ut(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 E=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(f),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||ut(e)){this.transport.send(f),this.cleanup();return}let i={};for(let a of["class","id","href","src","alt","title","data-id","data-name"]){let r=e.getAttribute(a);r&&(i[a]=_(r,200))}let s=e.parentElement?_(e.parentElement.innerText,300):"",o={elementText:_(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:ht(e)};this.transport.send(I,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(f),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 gt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Z(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 i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(d=>{try{t.jsonLd.push(JSON.parse(d.textContent||""))}catch(p){}})}catch(r){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=gt(o.innerText,2e3));let a=document.querySelector(`script[data-key="${n}"]`);return a&&Array.from(a.attributes).forEach(r=>{if(r.name.startsWith("data-context-")){let d=r.name.replace("data-context-","").replace(/-/g,"_");t.customContext[d]=r.value}}),t}function Q(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var S=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;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{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 b(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let a=document.querySelectorAll(o);for(let r=0;r<Math.min(a.length,10);r++){let d=getComputedStyle(a[r]),p=d.color;p&&p!==t.textColor&&p!=="rgb(0, 0, 0)"&&p!=="rgba(0, 0, 0, 0)"&&(i[p]=(i[p]||0)+1);let c=d.backgroundColor;c&&c!=="rgba(0, 0, 0, 0)"&&c!=="transparent"&&c!==t.bgColor&&(i[c]=(i[c]||0)+1)}}let s=Object.keys(i).sort((o,a)=>i[a]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var mt=`
|
|
2
|
+
var rt=Object.defineProperty;var A=Object.getOwnPropertySymbols;var at=Object.prototype.hasOwnProperty,lt=Object.prototype.propertyIsEnumerable;var O=(n,t,e)=>t in n?rt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,h=(n,t)=>{for(var e in t||(t={}))at.call(t,e)&&O(n,e,t[e]);if(A)for(var e of A(t))lt.call(t,e)&&O(n,e,t[e]);return n};var u=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 i=h({type:t},e);this.ready&&this.iframe?this.sendRaw(i):this.queue.push(i)}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,i;try{(i=(e=this.iframe)==null?void 0:e.contentWindow)==null||i.postMessage(t,this.baseUrl||"*")}catch(s){}}onMessage(t){if(!t.data||!t.data.type||this.iframe&&t.source!==this.iframe.contentWindow)return;let e=this.handlers.get(t.data.type);e&&e(t.data)}};var g=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 i;(i=this.listeners.get(t))==null||i.delete(e)}emit(t,...e){var i;(i=this.listeners.get(t))==null||i.forEach(s=>{try{s(...e)}catch(o){console.error("[MaxAI SDK]",o)}})}removeAll(){this.listeners.clear()}};var G="max-widget:page-context",k="max-widget:register-tools",H="max-widget:unregister-tool",m="max-widget:tool-result",R="max-widget:point-ask-result",f="max-widget:point-ask-cancel",v="max-widget:host-styles",P="max-widget:debug-snapshot",I="max-widget:config-features";var U="max-widget:expand",N="max-widget:hide",D="max-widget:request-page-context",z="max-widget:start-point-ask",W="max-widget:stop-point-ask",K="max-widget:execute-tool",j="max-widget:request-debug-snapshot",q="max-widget:request-host-styles",X="max-widget:gdpr-consent",F="max-widget:navigate",B="max-widget:message",Y="max-widget:error";var x=class{constructor(t){this.tools=new Map;this.transport=t}register(t){return!t.name||!/^[a-zA-Z0-9_]+$/.test(t.name)?(console.error("[MaxAI SDK] Invalid tool name:",t.name),()=>{}):(this.tools.set(t.name,h({},t)),this.sendList(),()=>this.unregister(t.name))}unregister(t){this.tools.has(t)&&(this.tools.delete(t),this.transport.send(H,{name:t}),this.sendList())}async execute(t,e,i){let s=this.tools.get(e);if(!(s!=null&&s.handler)){this.transport.send(m,{toolCallId:t,ok:!1,error:`Tool "${e}" not found or has no handler`});return}try{let o=await s.handler(i);this.transport.send(m,{toolCallId:t,ok:!0,data:o}),window.dispatchEvent(new CustomEvent("MaxAI:DataMutated",{detail:{toolName:e,args:i}}))}catch(o){this.transport.send(m,{toolCallId:t,ok:!1,error:o instanceof Error?o.message:"Tool execution failed"})}}sendList(){let t=Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,schema:e.schema,requiresConfirmation:e.requiresConfirmation||!1,category:e.category||""}));this.transport.send(k,{tools:t})}hasTools(){return this.tools.size>0}destroy(){this.tools.clear()}};function $(n,t){return n.length>t?n.slice(0,t)+"\u2026":n}var ct=[/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 pt(n){let t=JSON.stringify(n);for(let e of ct)t=t.replace(e,"[REDACTED]");try{return JSON.parse(t)}catch(e){return n}}var y=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 i=e.map(s=>{try{return typeof s=="string"?s:JSON.stringify(s)}catch(o){return String(s)}}).join(" ");this.consoleLogs.push({level:t,message:$(i,500),timestamp:Date.now()}),this.consoleLogs.length>50&&this.consoleLogs.shift()}catch(i){}};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 i of t.getEntries()){let s=i,o=(e=s.responseStatus)!=null?e:0;this.networkLog.push(h({method:"GET",url:$(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(t){}}}getSnapshot(){return pt({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 T(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function ht(n){let t=[],e=n;for(;e&&e.nodeType===1;){let i=1,s=e.previousSibling;for(;s;)s.nodeType===1&&s.tagName===e.tagName&&i++,s=s.previousSibling;t.unshift(e.tagName.toLowerCase()+"["+i+"]"),e=e.parentElement}return"/"+t.join("/")}function ut(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 b=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(f),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||ut(e)){this.transport.send(f),this.cleanup();return}let i={};for(let d of["class","id","href","src","alt","title","data-id","data-name"]){let a=e.getAttribute(d);a&&(i[d]=T(a,200))}let s=e.parentElement?T(e.parentElement.innerText,300):"",o={elementText:T(e.innerText,500),elementTag:e.tagName.toLowerCase(),elementAttrs:i,surroundingText:s,xpath:ht(e)};this.transport.send(R,o),this.cleanup()}onKeyDown(t){t.key==="Escape"&&(this.transport.send(f),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 gt(n,t){return n?n.length>t?n.slice(0,t)+"\u2026":n:""}function Z(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 i=document.querySelector('meta[property="og:title"]');i&&(t.ogTitle=i.getAttribute("content")||"");let s=document.querySelector('meta[property="og:description"]');s&&(t.ogDescription=s.getAttribute("content")||"");try{document.querySelectorAll('script[type="application/ld+json"]').forEach(l=>{try{t.jsonLd.push(JSON.parse(l.textContent||""))}catch(c){}})}catch(a){}let o=document.querySelector("main, article, [role='main']");o&&(t.mainContent=gt(o.innerText,2e3));let d=document.querySelector(`script[data-key="${n}"]`);return d&&Array.from(d.attributes).forEach(a=>{if(a.name.startsWith("data-context-")){let l=a.name.replace("data-context-","").replace(/-/g,"_");t.customContext[l]=a.value}}),t}function Q(n,t){if(!t)return n;let e=h({},n);return t.pageType&&(e.pageType=t.pageType),t.visibleData&&(e.visibleData=t.visibleData),t.customContext&&(e.customContext=h(h({},e.customContext),t.customContext)),e}var w=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;history.pushState=function(...i){t.origPush.apply(this,i),t.checkChange()},history.replaceState=function(...i){t.origReplace.apply(this,i),t.checkChange()},this.popstateHandler=()=>this.checkChange(),window.addEventListener("popstate",this.popstateHandler);let e=document.querySelector("title");e&&(this.observer=new MutationObserver(()=>this.checkChange()),this.observer.observe(e,{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 E(){let n=getComputedStyle(document.body),t={bgColor:n.backgroundColor||"",fontFamily:n.fontFamily||"",textColor:n.color||"",primaryColor:"",accentColors:[]};try{let e=["a","button","h1","h2",".btn",".button",'[class*="primary"]'],i={};for(let o of e){let d=document.querySelectorAll(o);for(let a=0;a<Math.min(d.length,10);a++){let l=getComputedStyle(d[a]),c=l.color;c&&c!==t.textColor&&c!=="rgb(0, 0, 0)"&&c!=="rgba(0, 0, 0, 0)"&&(i[c]=(i[c]||0)+1);let p=l.backgroundColor;p&&p!=="rgba(0, 0, 0, 0)"&&p!=="transparent"&&p!==t.bgColor&&(i[p]=(i[p]||0)+1)}}let s=Object.keys(i).sort((o,d)=>i[d]-i[o]);t.primaryColor=s[0]||"",t.accentColors=s.slice(0,5)}catch(e){}return t}var mt=`
|
|
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}
|
|
@@ -26,4 +26,4 @@ var rt=Object.defineProperty;var H=Object.getOwnPropertySymbols;var at=Object.pr
|
|
|
26
26
|
.max-widget-tab svg{width:18px;height:18px;fill:white}
|
|
27
27
|
@media(max-width:420px){.max-widget-frame{width:calc(100vw - 40px);height:calc(100vh - 120px)}}
|
|
28
28
|
@media(max-width:420px){.max-widget-frame.expanded{width:100vw}}
|
|
29
|
-
`,
|
|
29
|
+
`,_='<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>',L='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>',ft='<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>',vt='<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 V(n,t,e,i,s,o){let d=document.createElement("style");s&&(d.nonce=s),d.textContent=mt,document.head.appendChild(d);let a=document.createElement("div");a.className="max-widget-container "+(e?"right":"left"),document.body.appendChild(a);let l=document.createElement("iframe");l.className="max-widget-frame "+(e?"right":"left"),l.src=n+"/widget/"+t,l.setAttribute("allow","clipboard-write"),a.appendChild(l);let c=document.createElement("button");c.className="max-widget-btn",c.style.backgroundColor=i,c.innerHTML=_,a.appendChild(c);let p=document.createElement("button");p.className="max-widget-tab "+(e?"right":"left"),p.style.backgroundColor=i,p.innerHTML=e?ft:vt,document.body.appendChild(p);let M=!1,C=!1;function ot(){C=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),p.classList.remove("visible"),l.style.position="",l.style.top="",l.style.bottom="",document.body.style.overflow=""}return c.addEventListener("click",()=>{if(C){ot();return}M=!M,M?(l.classList.add("open"),c.innerHTML=L,o.onOpen()):(l.classList.remove("open"),c.innerHTML=_,o.onClose())}),p.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),p.classList.remove("visible")}),{container:a,iframe:l,btn:c,tab:p,style:d}}function J(n,t,e){let{container:i,iframe:s,btn:o,tab:d}=n;t?(s.classList.contains("open")||(s.classList.add("open"),o.innerHTML=L),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),d.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"),d.classList.remove("visible"),s.style.position="",s.style.top="",s.style.bottom="",document.body.style.overflow="")}function tt(n){n.iframe.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function et(n){n.container.remove(),n.tab.remove(),n.style.remove()}function nt(n){n.iframe.classList.add("open"),n.btn.innerHTML=L}function it(n){n.iframe.classList.remove("open"),n.btn.innerHTML=_}var S=class{constructor(t){this.emitter=new g;this.debug=new y;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=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.transport=new u(this.baseUrl),this.tools=new x(this.transport),this.pointAndAsk=new b(this.transport),this.spaDetector=new w(()=>this.sendPageContext()),this.init()}async init(){let t;try{t=await(await fetch(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){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.pageContext&&this.spaDetector.start(),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init();let e=t.primary_color||"#6366f1";this.ui=V(this.baseUrl,this.key,this.isRight,e,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s;this.transport.markReady(),this.config&&this.transport.send(I,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),(s=this.config)!=null&&s.autoTheme&&this.transport.send(v,{styles:E()})),this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready")}),this.setupMessageHandlers()}setupMessageHandlers(){this.transport.listen(U,t=>{this.ui&&J(this.ui,!!t.expanded,this.isRight)}),this.transport.listen(N,()=>{this.ui&&tt(this.ui)}),this.transport.listen(D,()=>{this.sendPageContext()}),this.transport.listen(z,()=>{this.pointAndAsk.start()}),this.transport.listen(W,()=>{this.pointAndAsk.stop()}),this.transport.listen(K,t=>{let{toolCallId:e,name:i,args:s}=t;this.emitter.emit("tool:call",{id:e,name:i,args:s}),this.tools.execute(e,i,s).then(()=>{this.emitter.emit("tool:result",{id:e,name:i,ok:!0})})}),this.transport.listen(j,()=>{this.transport.send(P,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(q,()=>{this.transport.send(v,{styles:E()})}),this.transport.listen(X,()=>{var t,e;this.consentGiven=!0,this.sendPageContext(),(t=this.config)!=null&&t.debugMode&&this.debug.init(),(e=this.config)!=null&&e.autoTheme&&this.transport.send(v,{styles:E()})}),this.transport.listen(F,t=>{if(t.url)try{window.location.href=t.url}catch(e){}}),this.transport.listen(B,t=>{this.emitter.emit("message",t.message)}),this.transport.listen(Y,t=>{this.emitter.emit("error",{message:t.error})})}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let t=Z(this.key),e=Q(t,this.explicitContext);this.transport.send(G,{context:e})}setPageContext(t){this.explicitContext=t,this.sendPageContext()}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&&(it(this.ui),this.emitter.emit("close"))}destroy(){this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),this.ui&&et(this.ui),this.ui=null}};var r=null,st={init(n){return r?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),r):(r=new S(n),r)},setPageContext(n){if(!r){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}r.setPageContext(n)},registerTool(n){return r?r.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){r&&r.unregisterTool(n)},on(n,t){return r?r.on(n,t):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},open(){r==null||r.open()},close(){r==null||r.close()},destroy(){r==null||r.destroy(),r=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let t=n.getAttribute("data-key");t&&st.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=st);export{st as MaxAI};
|
package/package.json
CHANGED