@marketrix.ai/widget 4.0.131 → 4.0.133
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.
|
@@ -3,13 +3,17 @@
|
|
|
3
3
|
* and published through `WidgetConfigContext` — and the one place the root element is published through
|
|
4
4
|
* `PortalContainerContext`. Renders `MessengerShell` (inside an `ErrorBoundary`, so a panel crash still leaves the
|
|
5
5
|
* launcher and toasts alive), `WidgetFab`, `WidgetNotifications`, and a fixed screen-edge glow while a reply or
|
|
6
|
-
* task is in flight;
|
|
6
|
+
* task is in flight; an effect arms the greeting toast.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* so
|
|
11
|
-
*
|
|
12
|
-
*
|
|
8
|
+
* `widgetPosition`'s stored/drag-pinned corner is read in `useState`'s lazy initializer, not a mount effect —
|
|
9
|
+
* `index.tsx`'s `updateMarketrixConfig` re-mounts the whole tree on any config change (this file's header note
|
|
10
|
+
* above), so `WidgetRoot` never receives an updated `config` prop in place; a sync effect keyed on `config`
|
|
11
|
+
* could only ever re-run for a config this component was never given, which is to say never. The position
|
|
12
|
+
* storage key is written ONLY by a drag — seeding it with `config.widget_position` would pin the dashboard's
|
|
13
|
+
* setting at whatever it was on a visitor's first load — and preview mode neither reads nor writes it, so the
|
|
14
|
+
* dashboard always shows the configured corner. Preview mode overrides the hidden check (`show_widget: false` /
|
|
15
|
+
* `widget_appearance: 'hidden'` suppress the widget on a host page, but the dashboard preview must still render)
|
|
16
|
+
* with its `null` return sitting below every hook so hook order stays stable either way.
|
|
13
17
|
*
|
|
14
18
|
* The published z-index is `max(tenant value, LAYER_TOKENS.panel)` so a tenant's low setting cannot sink the
|
|
15
19
|
* widget under the host page's own stacking context. The root `Surface` IS the `[data-marketrix-widget]` element
|
|
@@ -18,6 +18,16 @@
|
|
|
18
18
|
* as the console: an undelivered `tool/response` leaves the agent waiting on a reply that never comes, so
|
|
19
19
|
* the run stalls with nothing on screen unless the visitor is told, and `do` mode may still be clicking.
|
|
20
20
|
*
|
|
21
|
+
* `lastStreamErrorRef`/`currentErrorRef` close the loop `handleError` alone leaves open: `StreamClient`
|
|
22
|
+
* calls `onError` on every failed dial, not only a terminal give-up, so the visitor sees "Stream
|
|
23
|
+
* connection failed" while a transient blip is still auto-retrying, and nothing else ever un-shows it —
|
|
24
|
+
* without this pair, a single reconnect blip leaves a stale error banner on screen forever after the
|
|
25
|
+
* stream has already recovered. `registered` clears it, but ONLY when the error still on screen
|
|
26
|
+
* (`currentErrorRef`, a `useLatest` mirror of `uiState.error`) is byte-identical to the one this same
|
|
27
|
+
* effect set (`lastStreamErrorRef`): the visitor dismissing the banner themselves, or a later unrelated
|
|
28
|
+
* error (a tool failure, a stop failure) overwriting it, both change `currentErrorRef` away from that
|
|
29
|
+
* remembered string, so `registered` arriving later never clears a message it didn't put there.
|
|
30
|
+
*
|
|
21
31
|
* `event.type === 'task/status' && isTerminalTaskStatus(event.status)` reads `event.status` on every
|
|
22
32
|
* branch, but only the `task/status` variant of `WidgetEvent` carries a `status` field at all — on any
|
|
23
33
|
* other event it is `undefined`, which `isTerminalTaskStatus` (an `in` check against the status map)
|
package/dist/widget.mjs
CHANGED
|
@@ -17,8 +17,8 @@ return v(zs,{toast:e,className:"mtx-toast",render:/* @__PURE__ */b(bc,{align:"ce
|
|
|
17
17
|
/* @__PURE__ */b(lc,{src:Za,alt:"",size:28,rounded:"pill"}),
|
|
18
18
|
/* @__PURE__ */v(vc,{grow:!0,minWidth:"0",children:[/* @__PURE__ */b(Ys,{render:/* @__PURE__ */b(Mc,{as:"span",block:!0,inheritColor:!0,truncate:!0,weight:"medium",style:{fontSize:"13px",color:t.titleColor,...e.actionProps&&{whiteSpace:"normal"}}})}),null!=e.description&&/* @__PURE__ */b(Vs,{render:/* @__PURE__ */b(Mc,{as:"span",block:!0,inheritColor:!0,truncate:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8}})})]}),e.actionProps&&/* @__PURE__ */b(ea,{render:/* @__PURE__ */b(pc,{variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
|
|
19
19
|
/* @__PURE__ */b(Qs,{onMouseDown:e=>e.preventDefault(),render:/* @__PURE__ */b(kc,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */b(Sc,{name:"closeSmall",size:12})})]},e.id)})},Rc=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(Zi,{children:[e,/* @__PURE__ */b(pa,{container:t??void 0,children:/* @__PURE__ */b(Ss,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */b(Tc,{})})})]}),Oc=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Ja();return a(()=>{null!=e?s({id:"error",type:"error",title:e,timeout:0,priority:"high",onClose:t,...n&&{actionProps:{children:"Retry",onClick:n}}}):c("error")},[e,n,s,c,t]),a(()=>{r?s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}):c("greeting")},[r,o,s,c,i]),null};function Ac(e){const t=d(e);return t.current=e,t}var _c=e=>e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement,Dc=e=>e instanceof HTMLButtonElement||"button"===e.getAttribute("role");function Pc(e,t){const n=1===t?"ArrowDown":"ArrowUp",r=e.selectedIndex+t;return r<0||r>=e.options.length?`${n}: already at ${1===t?"last":"first"} option`:(e.selectedIndex=r,e.dispatchEvent(new Event("change",{bubbles:!0})),`${n}: selected "${e.options[r]?.text??""}"`)}function Nc(e,t){const n=e.value,r=e.selectionStart??n.length,o=e.selectionEnd??n.length;let i,s;if(r!==o)i=n.slice(0,r)+n.slice(o),s=r;else if("Backspace"===t&&r>0)i=n.slice(0,r-1)+n.slice(o),s=r-1;else{if(!("Delete"===t&&r<n.length))return`${t}: ${"Backspace"===t?"cursor at start":"cursor at end"}, nothing to delete`;i=n.slice(0,r)+n.slice(r+1),s=r}return function(e,t,n){Lc(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}(e,i,s),`${t}: deleted character, value is now "${i}"`}function Lc(e,t){const n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;n?n.call(e,t):e.value=t}var Fc=e=>({success:!0,data:{text:e}}),zc=e=>({success:!0,data:e}),$c=e=>({success:!1,error:e}),Bc=(e,t)=>({success:!0,data:{text:e},afterResponseAttempt:t}),Wc="finish",Uc=new class{tools={navigate:{label:"Navigating",run:e=>this.navigate(e)},search_web:{label:"Searching",run:e=>this.search(e)},click_element:{label:"Clicking element",waitForUser:!0,run:e=>this.clickElement(e)},type_text:{label:"Typing text",waitForUser:!0,run:e=>this.typeText(e)},scroll:{label:"Scrolling",run:e=>this.scroll(e)},scroll_to_text:{label:"Scrolling to text",run:e=>this.scrollToText(e)},extract:{label:"Extracting content",run:e=>this.extract(e)},go_back:{label:"Going back",run:()=>this.goBack()},wait_seconds:{label:"Waiting",run:e=>this.wait(e)},select_dropdown:{label:"Selecting option",waitForUser:!0,run:e=>this.selectDropdownOption(e)},get_dropdown_options:{label:"Reading dropdown options",run:e=>this.getDropdownOptions(e)},send_keys:{label:"Pressing key",waitForUser:!0,run:e=>this.sendKeys(e)},close_tab:{label:"Closing tab",run:()=>this.closeTab()},[Wc]:{label:"Done",run:e=>this.done(e)},get_html:{label:"Reading the page",run:()=>this.getHtml()},get_screenshot:{label:"Taking screenshot",run:()=>this.getScreenshot()}};element(e){if(void 0===e)throw new Error("Index required");const{element:t,error:n}=_r.getValidatedElement(e);if(!t)throw new Error(n||`Element ${e} not found`);return t}selectElement(e){const t=this.element(e);if(!(t instanceof HTMLSelectElement))throw new Error(`Element ${e} is not a select element`);return t}getFriendlyToolName(e){return this.tools[e]?.label??e}isWaitForUserTool(e){return!!this.tools[e]?.waitForUser}async executeTool(e,t,n,r=""){const o=t,i=this.tools[e];try{return"show"===n&&i?.waitForUser&&void 0!==o.index&&await Lr.showToolAction({element:this.element(o.index),explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e}),i?await i.run(o):$c(`Unknown tool: ${e}`)}catch(s){return $c(Oe(s))}}navigate(e){const t=(e=>{if(!e)return null;try{const t=new URL(e,window.location.href);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}})(e.url);return t?e.new_tab?window.open(t,"_blank")?Fc(`Opened ${t} in new tab`):$c("The browser blocked opening a new tab"):Bc(`Navigating to ${t}`,()=>{window.location.href=t}):$c("An http(s) URL is required")}search(e){if(!e.query)return $c("Query is required");const t=e.engine||"duckduckgo",n=encodeURIComponent(e.query);let r=`https://duckduckgo.com/?q=${n}`;return"google"===t&&(r=`https://www.google.com/search?q=${n}`),"bing"===t&&(r=`https://www.bing.com/search?q=${n}`),Bc(`Searching for "${e.query}" on ${t}`,()=>{window.location.href=r})}async clickElement(e){const t=this.element(e.index);return t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),Bc(`Clicking element ${e.index}`,()=>t.click())}typeText(e){if(void 0===e.text)return $c("Text required");const t=!1!==e.clear,n=this.element(e.index);if(_c(n))n.focus(),Lc(n,t?e.text:n.value+e.text),n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}));else if(n.isContentEditable){n.focus();const r=window.getSelection();if(t?r?.selectAllChildren(n):r?.collapse(n,n.childNodes.length),!document.execCommand("insertText",!1,e.text))return $c(`Could not insert text into element ${e.index}`)}else"value"in n?(n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))):(n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})));return Fc(`Typed text into element ${e.index}`)}scroll(e){const t=.8*window.innerHeight;switch(e.direction){case"down":window.scrollBy({top:t,behavior:"smooth"});break;case"up":window.scrollBy({top:-t,behavior:"smooth"});break;case"left":window.scrollBy({left:-t,behavior:"smooth"});break;case"right":window.scrollBy({left:t,behavior:"smooth"});break;default:return $c("Invalid direction")}return Fc(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return $c("Text required");const t=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let n;for(;n=t.nextNode();)if(n.textContent?.includes(e.text))return n.parentElement?.scrollIntoView({behavior:"smooth",block:"center"}),Fc(`Scrolled to "${e.text}"`);return $c(`Text "${e.text}" not found`)}extract(e){const t=!1!==e.extract_links,n={title:document.title,url:window.location.href,text:document.body.innerText.slice(0,1e4),links:t?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]};return zc(n)}goBack(){return window.history.length<=1?$c("No history"):Bc("Going back",()=>window.history.back())}async wait({seconds:e}){return void 0===e?$c("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),Fc(`Waited ${e}s`))}selectDropdownOption(e){if(!e.option)return $c("Option required");const t=this.selectElement(e.index),n=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return n?(t.value=n.value,t.dispatchEvent(new Event("change",{bubbles:!0})),Fc(`Selected ${e.option}`)):$c(`Option ${e.option} not found`)}getDropdownOptions(e){const t=Array.from(this.selectElement(e.index).options).map(e=>({value:e.value,text:e.text}));return zc({options:t})}sendKeys(e){if(!e.keys)return $c("Keys required");const t=this.element(e.index);t.focus(),t.dispatchEvent(new KeyboardEvent("keydown",{key:e.keys,bubbles:!0,cancelable:!0})),t.dispatchEvent(new KeyboardEvent("keyup",{key:e.keys,bubbles:!0,cancelable:!0}));const n=function(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=Tr(document),o=r.indexOf(e),i=-1===o?void 0:r[o+n];return i?(i.focus(),`${t}: moved focus to ${i.tagName.toLowerCase()}${i.id?`#${i.id}`:""}`):`${t}: no ${n>0?"next":"previous"} focusable element`}case"Enter":if(Dc(e))return e.click(),"Enter: clicked button";if(_c(e)){const t=e.closest("form");if(t){const e=t.querySelector('button[type="submit"], input[type="submit"]');return e?(e.click(),"Enter: clicked form submit button"):(t.requestSubmit(),"Enter: submitted form")}}return e instanceof HTMLAnchorElement?(e.click(),"Enter: clicked link"):"Enter: dispatched event";case"Escape":return e.blur(),document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),"Escape: blurred element and dispatched to document";case" ":case"Space":return e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)?(e.click(),`Space: toggled ${e.type}`):Dc(e)?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":return e instanceof HTMLSelectElement?Pc(e,1):"ArrowDown: dispatched event";case"ArrowUp":return e instanceof HTMLSelectElement?Pc(e,-1):"ArrowUp: dispatched event";case"Home":return _c(e)?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(_c(e)){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":return _c(e)?Nc(e,"Backspace"):"Backspace: dispatched event";case"Delete":return _c(e)?Nc(e,"Delete"):"Delete: dispatched event";default:return null}}(t,e.keys);return Fc(n||`Sent keys ${e.keys}`)}closeTab(){return window.close(),window.closed?Fc("Tab closed"):$c("The browser refused to close a tab this script did not open")}done(e){return Fc(e.message||"Task ended")}getHtml(){return Fc(_r.reindexAndSnapshot())}async getScreenshot(){const e=br();if(!e)return $c("The visitor is not sharing their screen.");const t=document.createElement("video");try{t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),await new Promise((e,n)=>{const r=setTimeout(()=>n(/* @__PURE__ */new Error("Screen capture produced no frame")),5e3);t.onloadeddata=()=>{clearTimeout(r),e()},t.onerror=()=>{clearTimeout(r),n(/* @__PURE__ */new Error("Screen capture failed"))}});const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;const r=n.getContext("2d");return r?(r.drawImage(t,0,0),Fc(n.toDataURL("image/jpeg",.75))):$c("Could not read the shared screen: the browser refused a 2d canvas context.")}finally{t.remove()}}},Hc={show:"Show",tell:"Tell",do:"Do"},jc=e=>Hc[e];function qc(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(void 0!==r&&t(r))return n}return-1}function Vc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest&&!e.taskStatus,o=e=>e.isPlaceholder&&void 0===e.mode||e.mode===n,i=[];!t||"show"!==n&&"do"!==n||i.push(e=>r(e)&&o(e)&&!!e.isPlaceholder,e=>r(e)&&o(e)),i.push(e=>r(e)&&!!e.isPlaceholder,r);const s=qc(e,e=>"agent"===e.sender&&!!e.taskStatus)+1,a=e.slice(s);for(const c of i){const e=qc(a,c),t=e>=0?a[e]:void 0;if(t)return{index:s+e,message:t}}return Ae(`[MessageFinder] No message found for progress update: totalMessages=${e.length} isTaskRunning=${t} currentMode=${n}`),null}var Yc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function Kc(e,t,n){const r=t>=0?e.parts[t]:void 0;if(!r)return e;const o=[...e.parts];return o[t]={...r,...n},{...e,parts:o}}var Xc=(e,t)=>e.parts.findIndex(e=>"progress"===e.type&&"in_progress"===e.status&&e.browserToolName===t);function Gc(e,t,n,r={}){return{id:`${e}-${globalThis.crypto.randomUUID()}`,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Jc=(e,t,n="user-message")=>Gc(n,"user",e.trim(),{mode:t}),Zc=e=>Gc("agent-message","agent",e.trim()),Qc=(e,t)=>Gc(t,"agent",e,{isSystemMessage:!0}),el="I'm sorry, I encountered an error processing your request. Please try again.",tl=e=>({state:e,effects:[]});function nl(e,t,n,r,o,i,s){const a=Vc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=Xc(e,t),o=r>=0?e.parts[r]:void 0;if(!o)return e;const i=Yc(o.content),s=Yc(n);return Kc(e,r,{status:"failed",content:s?`${i} (${s})`:i})}(c,r,s||""):"finish"!==r&&(c="in_progress"===i?function(e,t,n){const r=Yc(n),o=Xc(e,t);return o>=0?Kc(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||Uc.getFriendlyToolName(r)):((e,t)=>Kc(e,Xc(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&Uc.isWaitForUserTool(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var rl=(e,t)=>"running"===e.task.phase?e.task.mode??t:t,ol=e=>({...e,isPlaceholder:!1}),il=e=>"stopped"===e.phase?e:{phase:"idle"};function sl(e,t,n){const r=Vc({messages:e.messages,isTaskRunning:"running"===e.task.phase,currentMode:rl(e,t)}),o=[...e.messages];return r&&(o[r.index]=ol(n(r.message))),{messages:o,task:il(e.task)}}var al={completed:"done",failed:"failed",stopped:"stopped"};function cl(e,t,n,r){const o=e.messages.map(e=>{if(e.id!==t)return e;const o=[...e.parts],i=o[o.length-1],s="text"===i?.type&&!0===i.streaming;if("text"===i?.type&&!s&&i.content===n)return e;const a={type:"text",content:r&&s?i.content+n:n,...r&&{streaming:!0}};return s?o[o.length-1]=a:o.push(a),{...e,isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var ll=(e,t)=>({...e,parts:[...e.parts,{type:"text",content:t}]}),ul=(e,t)=>({...ol(ll(e,t)),placeholderState:void 0,taskStatus:"failed"});function dl(e,t,n){const r=e.messages.map(e=>e.id===t?ul(e,n):e);return{...e,messages:r}}var pl=n(void 0),hl=({children:e})=>{const[t,n]=p({isOpen:!1,activeView:"home",currentMode:"tell"}),r=u(()=>({setActiveView:e=>n(t=>({...t,activeView:e})),toggleWidget:()=>n(e=>({...e,isOpen:!e.isOpen})),closeWidget:()=>n(e=>({...e,isOpen:!1})),setMode:e=>n(t=>({...t,currentMode:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]),o=u(()=>({uiState:t,uiActions:r}),[t,r]);/* @__PURE__ */
|
|
20
|
-
return b(pl.Provider,{value:o,children:e})},fl=()=>{const e=s(pl);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},ml=n(void 0),gl=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=fl(),[o,s]=p(()=>({messages:[],task:{phase:"idle"}})),c=d(o),l=Ac(n.currentMode),h=d(/* @__PURE__ */new Set),f=i(e=>{const t=c.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(c.current=n,s(n))},[]),
|
|
21
|
-
return b(ml.Provider,{value:
|
|
20
|
+
return b(pl.Provider,{value:o,children:e})},fl=()=>{const e=s(pl);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},ml=n(void 0),gl=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=fl(),[o,s]=p(()=>({messages:[],task:{phase:"idle"}})),c=d(o),l=Ac(n.currentMode),h=d(/* @__PURE__ */new Set),f=Ac(n.error),m=d(void 0),g=i(e=>{const t=c.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(c.current=n,s(n))},[]),y=i(e=>{g(t=>({...t,messages:[...t.messages,e]}))},[g]),v=i((e,t)=>{g(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[g]),w=i(e=>{g(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[g]),x=i(e=>{g(t=>({...t,messages:e}))},[g]),S=i(()=>{g(e=>({...e,messages:[]}))},[g]),k=i(()=>{g(e=>({...e,task:{phase:"idle"}}))},[g]),C=o.messages.filter(e=>e.isPlaceholder).map(e=>`${e.id}:${e.parts.length}`).join(" ");a(()=>{const e=C.split(" ").filter(Boolean).map(e=>e.split(":")[0]).filter(e=>void 0!==e).map(e=>setTimeout(()=>g(t=>function(e,t){const n=e.messages.find(e=>e.id===t);return n?.isPlaceholder&&"waiting-for-user"!==n.placeholderState?dl(e,t,"This is taking longer than expected. Please try again."):e}(t,e)),12e4));return()=>e.forEach(clearTimeout)},[C,g]);const E=i(async(e,n,r)=>{const o=n??l.current;if(t)return r||y(Jc(e,o)),void y(Zc("This is a preview. In production, I'll respond to your messages here."));if(!Be.getCredentialedConfig())return console.error("Config not loaded or incomplete"),void y(Zc("Configuration error: Missing API credentials. Please check your widget settings."));r||y(Jc(e,o));const i=(e=>Gc("temp","agent","",{mode:e,isPlaceholder:!0,placeholderState:"thinking"}))(o);g(e=>function(e,t){return{messages:[...e.messages,t],task:{phase:"idle"}}}(e,i));try{await async function(e,t,n){const r=await We.getOrCreateChatId(),o={type:`chat/${t}`,request_id:n,content:e};await fr.ready(r),await fr.send(o)}(e,o,i.id)}catch(s){console.error("Failed to send message:",s),g(e=>dl(e,i.id,el))}},[t,y,g]);a(()=>{if(t)return;const{handleMessage:e,handleError:n}=function(e){const{commit:t,currentModeRef:n,setError:r,processedToolCallIds:o,currentErrorRef:i,lastStreamErrorRef:s}=e,a=async e=>{const{toolCallId:o,tool:i,args:s,mode:a,explanation:c}=e,l=await Uc.executeTool(i,s,a,c),u=l.success?void 0:l.error;t(e=>function(e,t,n,r,o,i){return{...e,messages:nl(e.messages,"running"===e.task.phase,rl(e,o),t,n,r,i)}}(e,i,c,u?"failed":"completed",n.current,u)),u||"finish"!==i||t(e=>sl(e,n.current,e=>({...e,taskStatus:"done",parts:e.parts.filter(e=>"progress"!==e.type)}))),await fr.send({type:"tool/response",tool_call_id:o,success:l.success,...l.success&&{data:JSON.stringify(l.data)},error:u}).catch(e=>{console.error("Failed to send tool response:",e),r("Could not report that step back to the assistant — it may stop responding.")}),l.success&&l.afterResponseAttempt?.()};return{handleMessage:e=>{if("tool/call"===e.type){const t=e.tool_call_id;if(o.current.has(t))return;o.current.add(t),o.current.size>1e3&&(o.current=new Set([...o.current].slice(-500)))}else"task/status"===e.type&&e.status in al?o.current.clear():"chat/error"===e.type?Ae("[Widget] Chat error from server:",e.error):"registered"===e.type&&void 0!==s.current&&i.current===s.current&&(s.current=void 0,r(void 0));let c=[];t(t=>{const r=function(e,t,n){switch(t.type){case"tool/call":{if("stopped"===e.task.phase)return tl(e);const r="running"===e.task.phase?e.task:{phase:"running",mode:t.mode||n},o=t.explanation||"";return{state:{messages:nl(e.messages,!0,r.mode??n,t.browser_tool,o,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:t.mode||n,explanation:o}]}}case"task/status":{if("running"===t.status)return tl(e);const r=t.status,o=e=>t.message?ll(e,t.message):e;return{state:sl(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:al[r]})),effects:[]}}case"chat/delta":return{state:cl(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:cl(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:dl(e,t.request_id,el),effects:[]};default:return tl(e)}}(t,e,n.current);return c=r.effects,r.state});for(const t of c)a(t).catch(e=>{console.error("[Widget] Tool call failed:",e),r("Something went wrong running that step. Please try again.")})},handleError:e=>{r(e.message),s.current=e.message,e instanceof hr&&t(t=>{return n=t,r=e.message,{messages:n.messages.map(e=>e.isPlaceholder?ul(e,r):e),task:il(n.task)};var n,r})}}}({commit:g,currentModeRef:l,setError:r.setError,processedToolCallIds:h,currentErrorRef:f,lastStreamErrorRef:m}),o={onMessage:e,onError:n};return fr.addCallbacks(o),()=>{fr.removeCallbacks(o)}},[t,g,r,l]);const I=i(async()=>{g(e=>function(e,t){return{...sl(e,t,e=>({...e,taskStatus:"stopped"})),task:{phase:"stopped"}}}(e,l.current)),t||fr.send({type:"chat/stop"}).catch(e=>{console.error("Failed to stop task remotely:",e),r.setError("Could not stop the assistant — it may still be working.")})},[t,g,r]),M=u(()=>({addMessage:y,updateMessage:v,removeMessage:w,setMessages:x,clearMessages:S,messageDispatch:E}),[y,v,w,x,S,E]),T=u(()=>({resetTask:k,stopTask:I}),[k,I]),R=u(()=>({messages:o.messages,chatActions:M,taskState:o.task,taskActions:T}),[o.messages,M,o.task,T]);/* @__PURE__ */
|
|
21
|
+
return b(ml.Provider,{value:R,children:e})},yl=()=>{const e=s(ml);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},bl=n(null),vl=()=>{const{uiState:e}=fl(),{messages:t}=yl();return a(()=>{const{currentMode:n,isOpen:r}=e;var o;o={messages:t,currentMode:n,isOpen:r},Be.updateContext({...o,messages:o.messages.map(({videoStream:e,...t})=>{const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n,content:Re(t.parts)};const r="Screen sharing ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}})})},[t,e]),null},wl=({children:e,previewMode:t})=>{const{uiActions:n}=fl(),{chatActions:r}=yl(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const{messages:t,...o}=function(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=Be.getContext();return{...o,messages:r.map(({content:e,...t})=>{const n=[...t.parts],r=e.trim();return 0===n.length&&r&&n.push({type:"text",content:r}),{...t,timestamp:new Date(t.timestamp),parts:n}})}}();n.applyState(o),r.setMessages(t),i(!0);const s=await We.getOrCreateChatId();e||fr.connect(s)})().catch(t=>{e||(console.error("Widget initialization failed:",t),n.setError("Widget failed to initialise — please refresh the page."))}),()=>{e=!0}},[t,n,r]),/* @__PURE__ */v(y,{children:[e,o&&/* @__PURE__ */b(vl,{})]})},xl=({children:e,previewMode:t=!1})=>/* @__PURE__ */b(hl,{children:/* @__PURE__ */b(gl,{previewMode:t,children:/* @__PURE__ */b(wl,{previewMode:t,children:e})})}),Sl=/^#?([a-f\d]{3}|[a-f\d]{6})$/i,kl=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i;function Cl(e){const t=Sl.exec(e.trim())?.[1];if(t){const[e,n,r]=3===t.length?[t.charAt(0)+t.charAt(0),t.charAt(1)+t.charAt(1),t.charAt(2)+t.charAt(2)]:[t.slice(0,2),t.slice(2,4),t.slice(4,6)];return{r:parseInt(e??"",16),g:parseInt(n??"",16),b:parseInt(r??"",16)}}const n=kl.exec(e.trim());if(!n)return null;const r=Number(n[1]),o=Number(n[2]),i=Number(n[3]);return r>255||o>255||i>255?null:{r:r,g:o,b:i}}function El({r:e,g:t,b:n}){const r=e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4);return.2126*r(e/255)+.7152*r(t/255)+.0722*r(n/255)}function Il(e,t){const n=Cl(e),r=Cl(t);if(!n||!r)return null;const o=El(n),i=El(r);return(Math.max(o,i)+.05)/(Math.min(o,i)+.05)}function Ml(e){return Cl(e)?(Il(e,"#000000")??0)>=(Il(e,"#ffffff")??0)?"#000000":"#ffffff":"#000000"}function Tl(e,t){const n=Cl(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}function Rl(e){return e.includes("gradient")?e:`linear-gradient(135deg, ${e} 0%, ${e} 100%)`}var Ol={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"},Al=n(null),_l=()=>{const e=s(Al);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},Dl=()=>{const{uiState:e,uiActions:t}=fl(),{messages:n,chatActions:r,taskState:o,taskActions:i}=yl();return{state:u(()=>({...e,messages:n,isTaskRunning:"running"===o.phase,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),actions:u(()=>({...t,...i,...r,clearChatHistory:()=>{r.clearMessages(),i.resetTask(),t.setError(void 0)}}),[t,i,r])}},Pl={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},Nl=Object.keys(Pl),Ll=e=>Pl[e],Fl=e=>{const{vertical:t,horizontal:n}=Ll(e);return{[t]:"20px",[n]:"20px"}},zl={top:"bottom",bottom:"top",left:"right",right:"left"},$l=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Ll(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},Bl=class extends t.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`${this.props.label} Error Boundary caught error:`,e,t)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},Wl="cubic-bezier(0.16, 1, 0.3, 1)",Ul=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=_l(),{state:c,actions:u}=Dl(),h=c.isOpen,f=c.isTaskRunning,m=!!c.error,g=!h&&(c.isAwaitingReply||f),y=!h&&f,w=m?"error":"processing",x=d(null),{isDragging:S,pixelPositionStyle:k,onPointerDown:C,onPointerMove:E,onPointerUp:I,onPointerCancel:M,suppressUntilRef:T}=function({position:e,onPositionCommit:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=p(!1),[c,u]=p({w:56,h:56}),[,h]=p(0),f=d(null),m=d(null),g=d(null),y=d(0),b=d([]),v=d(0),w=()=>{null!==g.current&&window.cancelAnimationFrame(g.current),g.current=null};t.useEffect(()=>()=>{w(),f.current?.()},[]),t.useEffect(()=>{if(r)return;const e=()=>h(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[r]);const x=i(()=>{if(!o.current||"undefined"==typeof window)return;const e=o.current.getBoundingClientRect();u(t=>t.w===e.width&&t.h===e.height?t:{w:e.width,h:e.height})},[o]);l(()=>{x();const e="undefined"!=typeof window&&o.current?new ResizeObserver(x):null;return e&&o.current&&e.observe(o.current),()=>e?.disconnect()},[x,e,o]);const S="undefined"!=typeof window?window.innerWidth:0,k="undefined"!=typeof window?window.innerHeight:0,C=$l(e,S,k,c.w,c.h),E=!r&&S>0&&k>0?{left:C.x,top:C.y}:void 0,I=i(()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="",o.current.style.left="",o.current.style.top="")},[o]),M=i((e,t)=>{f.current?.();let r=!1;const i=()=>{r=!0,window.clearTimeout(c),t.removeEventListener("transitionend",l),f.current=null},s=()=>{r||(i(),t.style.transition="none",t.style.willChange="",t.style.left="",t.style.top="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))},c=window.setTimeout(s,650),l=e=>{e.target===t&&"left"===e.propertyName&&s()};t.addEventListener("transitionend",l),f.current=i},[n,o]),T=i((t,r,i)=>{if(!o.current||!E)return I(),n(t),void a(!1);w();const s=o.current,l=$l(e,S,k,c.w,c.h),u=$l(t,S,k,c.w,c.h);s.style.transition="none",s.style.transform="none",s.style.willChange="left, top",s.style.left=`${l.x+r}px`,s.style.top=`${l.y+i}px`,requestAnimationFrame(()=>{s.style.transition=`left 600ms ${Wl}, top 600ms ${Wl}`,s.style.left=`${u.x}px`,s.style.top=`${u.y}px`}),M(t,s)},[M,n,E,e,I,S,k,c.w,c.h,o]),R=e=>{I(),m.current=null,a(!1),e.currentTarget.releasePointerCapture(e.pointerId)};return{isDragging:s,pixelPositionStyle:E,onPointerDown:e=>{m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragging:!1,lastX:0,lastY:0},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{const t=m.current;if(t?.pointerId!==e.pointerId)return;const n=e.clientX-t.startX,r=e.clientY-t.startY;if(!t.dragging&&Math.hypot(n,r)>5&&(t.dragging=!0,a(!0),b.current=[],v.current=0,o.current&&(o.current.style.willChange="transform",o.current.style.transition="none")),!t.dragging)return;t.lastX=n,t.lastY=r;const i=Date.now();i-v.current>=10&&(v.current=i,b.current=[...b.current.slice(-5),{x:e.clientX,y:e.clientY,t:i}]),null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null;const e=m.current,t=o.current;t&&e&&(t.style.transform=`translate3d(${e.lastX}px, ${e.lastY}px, 0)`)}))},onPointerUp:t=>{const n=m.current;if(n?.pointerId===t.pointerId){if(n.dragging){const r=function(e,t=.999){if(e.length<2)return{x:0,y:0};const n=e[0],r=e[e.length-1];if(!n||!r)return{x:0,y:0};const o=r.t-n.t;if(o<=0)return{x:0,y:0};const i=e=>e/o*t/(1-t);return{x:i(r.x-n.x),y:i(r.y-n.y)}}(b.current),i={dx:n.lastX+r.x,dy:n.lastY+r.y},s=o.current?.getBoundingClientRect(),a=s?((e,t,n,r,o,i)=>{const s=$l(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,u=1/0;for(const d of Nl){const e=$l(d,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<u&&(u=t,l=d)}return l})(i,e,window.innerWidth,window.innerHeight,s.width,s.height):e;return T(a,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}R(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&R(e)},suppressUntilRef:y}}({position:s,onPositionCommit:e,isPreviewMode:n,wrapperRef:x});/* @__PURE__ */
|
|
22
22
|
return b(yc,{ref:x,className:"mtx-fab-anchor","data-animated":S?"false":"true","data-preview":n?"true":"false",style:{zIndex:a,pointerEvents:h?"none":"auto",...S?k:Fl(s)},children:/* @__PURE__ */v(yc,{className:"mtx-fab","data-open":h?"true":"false",children:[g&&/* @__PURE__ */b(yc,{className:"mtx-fab-glow","data-tone":w,"aria-hidden":!0}),y&&!S&&/* @__PURE__ */b(pc,{variant:"secondary",size:"sm",className:"mtx-fab-stop","data-side":s.includes("left")?"left":"right",onClick:e=>{e.preventDefault(),e.stopPropagation(),u.stopTask()},children:"Stop"}),
|
|
23
23
|
/* @__PURE__ */b(pc,{variant:"bare",onClick:()=>{Date.now()<T.current||u.toggleWidget()},onDragStart:e=>e.preventDefault(),onPointerDown:C,onPointerMove:E,onPointerUp:I,onPointerCancel:M,className:"mtx-fab-trigger",style:{touchAction:"none",cursor:S?"grabbing":"grab",userSelect:"none",WebkitUserSelect:"none"},"aria-label":h?"Close":"Open","aria-live":"polite",children:/* @__PURE__ */b(bc,{className:"mtx-fab-center",children:/* @__PURE__ */v(yc,{className:"mtx-fab-badge",style:{borderRadius:"12px",backgroundColor:h?o:r,boxShadow:kr.fab},children:[g&&/* @__PURE__ */b("svg",{className:"mtx-fab-ring","data-tone":w,viewBox:"0 0 54 54",fill:"none","aria-hidden":!0,children:/* @__PURE__ */b("rect",{x:"1.25",y:"1.25",width:"51.5",height:"51.5",rx:13,ry:13})}),
|
|
24
24
|
/* @__PURE__ */b(bc,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(30deg) scale(0)":"rotate(0deg) scale(1)",opacity:h?0:1},"aria-hidden":h,children:/* @__PURE__ */b(lc,{src:Za,alt:"",className:"mtx-fab-avatar",draggable:!1,onDragStart:e=>e.preventDefault(),style:{borderRadius:"12px",border:"none",outline:"none",backgroundColor:"transparent",pointerEvents:"none",userSelect:"none"}})}),
|
|
@@ -58,8 +58,8 @@ return v(vc,{height:"full",overflow:"hidden",children:[/* @__PURE__ */v(vc,{grow
|
|
|
58
58
|
/* @__PURE__ */b(Mc,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))});function hd(e){const t=e.getRootNode();return(t instanceof ShadowRoot?t.activeElement:document.activeElement)??null}function fd({width:e,height:t}){return{width:Math.min(Math.max(e,280),600),height:Math.min(Math.max(t,320),Math.floor(.85*window.innerHeight))}}function md(e,t){const n=/^\s*(\d+(?:\.\d+)?)px\s*$/.exec(e??"");return n?Number(n[1]):t}var gd=["home","chat"],yd=()=>{const e=_l(),{state:t,actions:n}=Dl(),{isOpen:r,activeView:o}=t,{isPreviewMode:s}=e,{widthPx:c,heightPx:l,grip:h,onResizeStart:f,onResizeKeyDown:m,containerRef:g}=function(e,t,n,r,o){const s=De("marketrix_widget_size",r),c=d(null),l=u(()=>(e=>{const t=Ll(e),n=zl[t.vertical],r=zl[t.horizontal];return{vertical:n,horizontal:r,growX:"left"===r?-1:1,growY:"top"===n?-1:1,cursor:"top"===n==("left"===r)?"nwse-resize":"nesw-resize"}})(n),[n]),[h,f]=p(()=>function(e){try{const t=JSON.parse(Ne(e)??"null");return function(e){return"object"==typeof e&&null!==e&&"number"==typeof e.width&&"number"==typeof e.height}(t)?fd(t):null}catch(t){return Ae("[useResize] Ignoring an unparseable stored size:",t),null}}(s)??fd({width:md(e,360),height:md(t,450)})),m=d(h);m.current=h;const g=d(null);a(()=>()=>g.current?.(),[]);const y=i(e=>{if(e.preventDefault(),e.stopPropagation(),o)return;const t=e.clientX,n=e.clientY,r=m.current.width,i=m.current.height,{growX:a,growY:u,cursor:d}=l;c.current&&(c.current.dataset.resizing="true");const p=e=>{const o=fd({width:r+(e.clientX-t)*a,height:i+(e.clientY-n)*u});m.current=o,c.current&&(c.current.style.width=`${o.width}px`,c.current.style.height=`${o.height}px`)},h=()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",h),document.body.style.cursor="",document.body.style.userSelect="",g.current=null,c.current&&delete c.current.dataset.resizing,f({...m.current}),Le(s,JSON.stringify(m.current))};document.body.style.cursor=d,document.body.style.userSelect="none",document.addEventListener("mousemove",p),document.addEventListener("mouseup",h),g.current=h},[o,s,l]),b=i(e=>{if(o)return;const t={ArrowLeft:{width:-16,height:0},ArrowRight:{width:16,height:0},ArrowUp:{width:0,height:-16},ArrowDown:{width:0,height:16}}[e.key];if(!t)return;e.preventDefault();const n=fd({width:m.current.width+t.width,height:m.current.height+t.height});m.current=n,f(n),Le(s,JSON.stringify(n))},[o,s]);return{widthPx:`${h.width}px`,heightPx:`${h.height}px`,grip:l,onResizeStart:y,onResizeKeyDown:b,containerRef:c}}(e.widget_width,e.widget_height,e.widget_position,e,s),y=d(null),w="chat"===o?"forward":"back";!function(e,t,n){const r=d(!1),o=d(null);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=hd(i)),r.current=!0,(n?.focusTargetRef?.current??Tr(i)[0])?.focus({preventScroll:!0});const s=e=>{const t=hd(i);if(!t||!i.contains(t))return;if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const r=Tr(i);if(0===r.length)return;const o=r.indexOf(t);-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),r[r.length-1]?.focus()):o===r.length-1&&(e.preventDefault(),r[0]?.focus()))};return document.addEventListener("keydown",s,!0),()=>document.removeEventListener("keydown",s,!0)},[t,e,n?.focusTargetRef,n?.onEscape])}(g,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?y:void 0});const x=Fl(e.widget_position),[S,k]=p(!1),C=d(null);if(!r)return null;const E=Rl(e.widget_background_color),{vertical:I,horizontal:M}=Ll(e.widget_position),T="chat"===o&&!1!==e.use_screenshare?()=>C.current?.():void 0;/* @__PURE__ */
|
|
59
59
|
return v(vc,{ref:g,position:s?"absolute":"fixed",rounded:"lg",border:!0,overflow:"hidden",style:{zIndex:e.widget_position_z_index,backgroundImage:E,transformOrigin:`${I} ${M}`,width:c,height:l,fontSize:"14px",...x,pointerEvents:"auto",scrollbarWidth:"thin",animation:"messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)",boxShadow:kr.panel},children:[
|
|
60
60
|
/* @__PURE__ */b(ku,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:T&&/* @__PURE__ */v(kc,{variant:"ghost",size:"sm",label:S?"Stop screen sharing":"Start screen sharing",onClick:T,children:[S&&/* @__PURE__ */b(Su,{style:{position:"absolute",top:"2px",right:"2px"}}),/* @__PURE__ */b(Sc,{name:"screenShare",size:16})]})}),
|
|
61
|
-
/* @__PURE__ */v(Ql,{value:o,onValueChange:e=>{"string"==typeof e&&(e=>gd.includes(e))(e)&&n.setActiveView(e)},render:/* @__PURE__ */b(vc,{grow:!0,minHeight:"0"}),children:[/* @__PURE__ */v(vc,{grow:!0,overflow:"hidden",minHeight:"0",children:[/* @__PURE__ */b(lu,{value:"home","data-view-transition":!0,"data-direction":w,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(ud,{onNavigateToChat:()=>n.setActiveView("chat"),onChipClick:e=>{n.addMessage(Jc(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */b(lu,{value:"chat","data-view-transition":!0,"data-direction":w,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(cd,{onScreenSharingChange:k,toggleScreenShareRef:C,messageInputRef:y})})]}),/* @__PURE__ */b(pd,{})]}),!s&&/* @__PURE__ */b("div",{role:"separator","aria-label":`Resize widget from ${h.vertical} ${h.horizontal}. Use arrow keys to resize.`,title:"Drag to resize",tabIndex:0,style:{position:"absolute",[h.vertical]:0,[h.horizontal]:0,width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:"top"===h.vertical?"flex-start":"flex-end",justifyContent:"left"===h.horizontal?"flex-start":"flex-end",cursor:h.cursor},onMouseDown:f,onKeyDown:m})]})},bd=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=Dl(),c=e.isPreviewMode??!1;var l;l=i.isOpen,a(()=>{if(!l)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[l]);const
|
|
62
|
-
return b(Al,{value:g,children:/* @__PURE__ */b(yc,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...w,...c&&{width:"100%",height:"100%"}},children:/* @__PURE__ */b(bl,{value:r,children:/* @__PURE__ */v(Rc,{container:r,offsetBottom:"top"===Ll(
|
|
61
|
+
/* @__PURE__ */v(Ql,{value:o,onValueChange:e=>{"string"==typeof e&&(e=>gd.includes(e))(e)&&n.setActiveView(e)},render:/* @__PURE__ */b(vc,{grow:!0,minHeight:"0"}),children:[/* @__PURE__ */v(vc,{grow:!0,overflow:"hidden",minHeight:"0",children:[/* @__PURE__ */b(lu,{value:"home","data-view-transition":!0,"data-direction":w,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(ud,{onNavigateToChat:()=>n.setActiveView("chat"),onChipClick:e=>{n.addMessage(Jc(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */b(lu,{value:"chat","data-view-transition":!0,"data-direction":w,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(cd,{onScreenSharingChange:k,toggleScreenShareRef:C,messageInputRef:y})})]}),/* @__PURE__ */b(pd,{})]}),!s&&/* @__PURE__ */b("div",{role:"separator","aria-label":`Resize widget from ${h.vertical} ${h.horizontal}. Use arrow keys to resize.`,title:"Drag to resize",tabIndex:0,style:{position:"absolute",[h.vertical]:0,[h.horizontal]:0,width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:"top"===h.vertical?"flex-start":"flex-end",justifyContent:"left"===h.horizontal?"flex-start":"flex-end",cursor:h.cursor},onMouseDown:f,onKeyDown:m})]})},bd=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=Dl(),c=e.isPreviewMode??!1;var l;l=i.isOpen,a(()=>{if(!l)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[l]);const u=De("marketrix_widget_position",e),[d,h]=p(()=>{const t=c?null:Ne(u);return(e=>Nl.includes(e))(t)?t:e.widget_position??"bottom_right"});a(()=>{if(i.isOpen||c||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,c,e.widget_greeting_toast]);const f=!1===e.show_widget||"hidden"===e.widget_appearance;if(!c&&f)return null;const m=Math.max(e.widget_position_z_index??0,2147483002),g={...e,widget_position:d,widget_position_z_index:m,isPreviewMode:c},y=i.isAwaitingReply||i.isTaskRunning,w=(x=function(e={}){const t=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)),n={...Ol,...t};return{color:{background:n.widget_background_color,foreground:n.widget_text_color,foregroundMuted:Tl(n.widget_text_color,.6),foregroundFaint:Tl(n.widget_text_color,.4),border:n.widget_border_color,primary:n.widget_accent_color,primaryForeground:Ml(n.widget_accent_color),primaryHover:Tl(n.widget_accent_color,.85),secondary:n.widget_secondary_color,secondaryForeground:Ml(n.widget_secondary_color),secondaryBg:Tl(n.widget_secondary_color,.2),secondaryHover:Tl(n.widget_secondary_color,.3),ring:Ml(n.widget_background_color)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}(e),{"--foreground":x.color.foreground,"--card":x.color.background,"--card-foreground":x.color.foreground,"--primary":x.color.primary,"--foreground-muted":x.color.foregroundMuted,"--foreground-faint":x.color.foregroundFaint,"--primary-foreground":x.color.primaryForeground,"--primary-hover":x.color.primaryHover,"--secondary":x.color.secondary,"--secondary-foreground":x.color.secondaryForeground,"--secondary-bg":x.color.secondaryBg,"--secondary-hover":x.color.secondaryHover,"--border":x.color.border,"--ring":x.color.ring,"--ring-offset":x.color.background,"--radius":x.radius,"--duration-animation":x.motion.durationAnimation,"--duration-fade":x.motion.durationFade});var x;/* @__PURE__ */
|
|
62
|
+
return b(Al,{value:g,children:/* @__PURE__ */b(yc,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...w,...c&&{width:"100%",height:"100%"}},children:/* @__PURE__ */b(bl,{value:r,children:/* @__PURE__ */v(Rc,{container:r,offsetBottom:"top"===Ll(d).vertical?20:90,children:[y&&/* @__PURE__ */b(yc,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${Tl(g.widget_accent_color,.72)}, inset 0 0 46px 10px ${Tl(g.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:2147483001}}),
|
|
63
63
|
/* @__PURE__ */b(Bl,{label:"Widget",children:/* @__PURE__ */b(yd,{})}),
|
|
64
|
-
/* @__PURE__ */b(Ul,{onPositionCommit:e=>{
|
|
64
|
+
/* @__PURE__ */b(Ul,{onPositionCommit:e=>{h(e),c||Le(u,e)}}),
|
|
65
65
|
/* @__PURE__ */b(Oc,{error:i.error,onClearError:()=>s.setError(void 0),...fr.canReconnect()&&{onRetry:()=>{s.setError(void 0),fr.reconnectNow()}},greeting:t&&!i.error?e.widget_greeting:void 0,greetingBody:e.widget_body,onGreetingDismiss:()=>n(!1)})]})})})})},vd={mount:null},wd=null,xd=(e,t)=>{const n=e.attachShadow({mode:"closed"}),r=document.createElement("style");r.textContent=':root,:host{--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--border:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--ring-offset:oklch(100% 0 0);--foreground-muted:#1f293799;--foreground-faint:#1f293766;--primary-hover:#3b82f6d9;--secondary-bg:#6b728033;--secondary-hover:#6b72804d;--font-sans:"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--radius:.625rem;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--duration-animation:.3s;--duration-fade:.2s;--radius-pill:9999px;--status-processing-rgb:49, 208, 109;--status-error-rgb:208, 52, 44;--overlay-dark:#111827}*,:before,:after{box-sizing:border-box;border:0 solid var(--border);margin:0;padding:0}:host,[data-marketrix-widget]{font-family:var(--font-sans);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;line-height:1.5}:where([data-marketrix-widget]) :where(h1,h2,h3){font-size:inherit;font-weight:inherit}:where([data-marketrix-widget]) :where(img,svg,video,canvas){vertical-align:middle;display:block}:where([data-marketrix-widget]) :where(img,video){max-width:100%;height:auto}:where([data-marketrix-widget]) :where(button,input,textarea){font:inherit;color:inherit;background:0 0;border-radius:0}:where([data-marketrix-widget]) :where(button){appearance:button}:where([data-marketrix-widget]) :where(textarea){resize:vertical}[data-marketrix-widget] [hidden]{display:none!important}[data-marketrix-widget],[data-marketrix-widget] *{pointer-events:auto;transition:color .2s ease-in-out,background-color .2s ease-in-out,border-color .2s ease-in-out,opacity .2s ease-in-out,box-shadow .2s ease-in-out,transform .2s ease-in-out}[data-resizing=true],[data-resizing=true] *{transition:none!important}@media (prefers-reduced-motion:reduce){[data-marketrix-widget]{--duration-animation:0s!important;--duration-fade:0s!important}}.mtx-button,.mtx-icon-button{cursor:pointer;justify-content:center;align-items:center;transition:all .2s ease-in-out;display:inline-flex}.mtx-button{border:1px solid #0000;gap:8px;font-weight:500}.mtx-button:focus-visible,.mtx-icon-button:focus-visible{box-shadow:0 0 0 2px var(--ring-offset), 0 0 0 4px var(--ring);outline:none}.mtx-button[data-size=sm]{min-height:28px;padding:4px 8px;font-size:.75rem}.mtx-button[data-size=md]{min-height:36px;padding:8px 16px;font-size:.875rem}.mtx-button[data-variant=primary]:hover{background:color-mix(in oklab, var(--primary) 90%, transparent)}.mtx-button[data-variant=secondary]{background:var(--secondary);color:var(--secondary-foreground)}.mtx-button[data-variant=secondary]:hover{background:color-mix(in oklab, var(--secondary) 80%, transparent)}.mtx-button[data-variant=ghost]{color:var(--foreground);border-color:var(--border);background:0 0}.mtx-button[data-variant=ghost]:hover{background:var(--border)}.mtx-button[data-variant=chip]{background:var(--secondary-bg);color:var(--foreground)}.mtx-button[data-variant=chip]:hover{background:var(--primary);color:var(--primary-foreground);border-color:var(--primary)}.mtx-button[data-variant=bare],.mtx-button[data-variant=tab]{background:0 0;border-color:#0000;min-height:0;padding:0}.mtx-button[data-variant=bare]{color:inherit}.mtx-button[data-variant=tab]{color:var(--foreground-muted);flex:1;min-width:0;height:100%;position:relative}.mtx-button[data-variant=tab]:hover{color:var(--foreground)}.mtx-button[data-variant=tab][aria-selected=true]{color:var(--primary);font-weight:600}.mtx-button[data-stacked=true]{flex-direction:column;gap:2px}.mtx-button[data-full=true]{width:100%}.mtx-icon-button{border-radius:var(--radius-pill);border:none;flex-shrink:0}.mtx-icon-button[data-size=xs]{width:20px;min-width:20px;height:20px}.mtx-icon-button[data-size=sm]{width:28px;min-width:28px;height:28px}.mtx-button[data-variant=primary],.mtx-icon-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-icon-button[data-variant=primary]:hover{background:var(--primary-hover)}.mtx-icon-button[data-variant=secondary]{background:var(--secondary-bg);color:var(--foreground)}.mtx-icon-button[data-variant=secondary]:hover{background:var(--secondary-hover)}.mtx-icon-button[data-variant=ghost]{color:var(--foreground);opacity:.6;background:0 0}.mtx-icon-button[data-variant=ghost]:hover{opacity:1}.mtx-button[data-disabled=true],.mtx-icon-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon{flex-shrink:0;display:inline-block}.mtx-avatar{flex-shrink:0}.mtx-spinner-ring{border-radius:var(--radius-pill);border-style:solid;border-color:#0000 currentColor currentColor;flex-shrink:0;animation:1s linear infinite mtx-spin}.mtx-visually-hidden{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.mtx-composer:focus-within{border-color:var(--foreground-faint)}.mtx-composer-input{resize:none;width:100%;min-height:0;color:var(--foreground);background:0 0;border:none;padding-left:12px;padding-right:12px;font-size:.875rem;display:block}.mtx-composer-input::placeholder{color:var(--foreground-faint)}.mtx-composer-input:focus{outline:none}.mtx-composer-input:disabled{cursor:not-allowed;opacity:.5}.mtx-mode-chip{border-radius:var(--radius-pill);cursor:pointer;background:var(--secondary-bg);color:var(--foreground-muted);border:none;align-items:center;gap:2px;padding:2px 8px;font-size:11px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-mode-chip[data-active=true]{background:var(--primary);color:var(--primary-foreground);box-shadow:var(--shadow-sm)}.mtx-toast-viewport{flex-direction:column;gap:8px;max-width:420px;display:flex;position:fixed;left:50%;transform:translate(-50%)}.mtx-toast{animation:mtx-fade-in var(--duration-animation) ease-out}.mtx-toast[data-ending-style]{opacity:0;transition:opacity var(--duration-animation) ease-out}.mtx-dialog-backdrop{animation:mtx-dialog-overlay-in var(--duration-fade) ease-out;background:#0003;position:fixed;inset:0}.mtx-dialog-popup{border-radius:var(--radius);background:var(--card);width:100%;max-width:24rem;max-height:85vh;animation:mtx-dialog-content-in var(--duration-animation) ease-out;flex-direction:column;padding:16px;display:flex;position:fixed;top:50%;left:50%;overflow:auto;transform:translate(-50%,-50%)}.mtx-dialog-title{color:var(--foreground);margin-bottom:4px;font-size:1rem;font-weight:600}.mtx-dialog-description{color:var(--foreground-muted);margin-bottom:16px;font-size:.875rem;line-height:1.625}.mtx-fab-anchor{position:fixed}.mtx-fab-anchor[data-preview=true]{position:absolute}.mtx-fab-anchor[data-animated=true]{transition:transform var(--duration-animation) ease-in-out}.mtx-fab{width:56px;height:56px;transition:all var(--duration-animation) ease-in-out;position:relative;overflow:visible}.mtx-fab[data-open=false]:hover{transform:scale(1.1)}.mtx-fab[data-open=true]{opacity:0;pointer-events:none;transform:scale(0)}.mtx-fab-trigger{z-index:10;width:56px;min-width:56px;height:56px;position:relative}.mtx-fab-center{justify-content:center;align-items:center;width:100%;height:100%;position:relative}.mtx-fab-badge{width:48px;height:48px;transition:transform .167s cubic-bezier(.33,0,0,1),opacity .167s cubic-bezier(.33,0,0,1),background-color .167s cubic-bezier(.33,0,0,1);animation:.25s ease-out forwards mtx-launcher-entrance;position:relative;overflow:hidden}.mtx-fab-badge:hover{transition-duration:.25s;transform:scale(1.1)}.mtx-fab-badge:active{transition-duration:.134s;transition-timing-function:cubic-bezier(.45,0,.2,1);transform:scale(.85)}.mtx-fab-icon-layer{justify-content:center;align-items:center;transition-property:transform,opacity;transition-duration:.16s,80ms;transition-timing-function:linear;position:absolute;inset:0}.mtx-fab-avatar{z-index:10;object-fit:contain;width:100%;height:100%;position:relative}.mtx-fab-chevron{z-index:10;color:var(--foreground);pointer-events:none;position:relative}.mtx-fab-stop{z-index:20;border-radius:var(--radius-pill);background:var(--overlay-dark);text-transform:uppercase;letter-spacing:.025em;color:#fff;box-shadow:var(--shadow-lg);opacity:0;pointer-events:none;border:1px solid #ffffff40;padding:4px 10px;font-size:11px;font-weight:600;transition:opacity .15s ease-in-out;position:absolute;top:50%;transform:translateY(-50%)}.mtx-fab-stop[data-side=left]{margin-left:8px;left:100%}.mtx-fab-stop[data-side=right]{margin-right:8px;right:100%}.mtx-fab:hover .mtx-fab-stop,.mtx-fab:focus-within .mtx-fab-stop{opacity:1;pointer-events:auto}.mtx-tab-underline{border-radius:var(--radius-pill);background:var(--primary);opacity:0;height:2px;position:absolute;top:0;left:25%;right:25%}[aria-selected=true]>.mtx-tab-underline{opacity:1}.mtx-live-dot{width:6px;height:6px;display:inline-flex;position:relative}.mtx-live-dot-ping{border-radius:var(--radius-pill);opacity:.75;background:currentColor;width:100%;height:100%;animation:1s cubic-bezier(0,0,.2,1) infinite mtx-ping;display:inline-flex;position:absolute}.mtx-live-dot-core{border-radius:var(--radius-pill);background:currentColor;width:6px;height:6px;display:inline-flex;position:relative}.mtx-fab-glow{pointer-events:none;filter:blur(14px);will-change:transform, opacity;border-radius:50%;width:140%;height:140%;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.mtx-fab-ring{pointer-events:none;z-index:0;position:absolute;inset:-3px;overflow:visible}.mtx-fab-ring rect{fill:none;stroke-width:2.5px;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:40 120;animation:1.9s cubic-bezier(.4,0,.2,1) infinite mtx-fab-ring-travel}.mtx-fab-ring[data-tone=processing] rect{stroke:rgb(var(--status-processing-rgb));filter:drop-shadow(0 0 3px rgba(var(--status-processing-rgb), .7))}.mtx-fab-ring[data-tone=error] rect{stroke:rgb(var(--status-error-rgb));filter:drop-shadow(0 0 3px rgba(var(--status-error-rgb), .7))}.mtx-fab-glow[data-tone=processing]{--glow-rgb:var(--status-processing-rgb);--glow-op-base:.72;--glow-op-peak:1;--glow-op-near:.38;--glow-op-far:.24;--glow-op-near-peak:.55;--glow-op-far-peak:.33;animation:2s ease-in-out infinite mtx-fab-glow-pulse}.mtx-fab-glow[data-tone=error]{--glow-rgb:var(--status-error-rgb);--glow-op-base:.65;--glow-op-peak:.95;--glow-op-near:.34;--glow-op-far:.22;--glow-op-near-peak:.5;--glow-op-far-peak:.3;animation:1.5s ease-in-out infinite mtx-fab-glow-pulse}[data-screen-edge-glow]{animation:1.6s ease-in-out infinite mtx-screen-edge-pulse}[data-view-transition][data-direction=forward]{animation:.3s both mtx-view-slide-forward}[data-view-transition][data-direction=back]{animation:.3s both mtx-view-slide-back}@keyframes mtx-spin{to{transform:rotate(360deg)}}@keyframes mtx-ping{75%,to{opacity:0;transform:scale(2)}}@keyframes mtx-dialog-overlay-in{0%{opacity:0}to{opacity:1}}@keyframes mtx-dialog-content-in{0%{opacity:0;scale:.96}to{opacity:1;scale:1}}@keyframes mtx-fade-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes mtx-launcher-entrance{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes mtx-screen-edge-pulse{0%,to{opacity:.55}50%{opacity:1}}@keyframes mtx-fab-ring-travel{0%{stroke-dashoffset:0;opacity:.5}18%{stroke-dashoffset:-112px;opacity:1}35%{stroke-dashoffset:-160px;opacity:.65}60%{stroke-dashoffset:-160px;opacity:.45}82%{stroke-dashoffset:-272px;opacity:1}to{stroke-dashoffset:-320px;opacity:.6}}@keyframes mtx-fab-glow-pulse{0%,to{opacity:var(--glow-op-base);background:radial-gradient(circle, rgba(var(--glow-rgb), 0) 38%, rgba(var(--glow-rgb), var(--glow-op-near)) 58%, rgba(var(--glow-rgb), var(--glow-op-far)) 68%, transparent 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:var(--glow-op-peak);background:radial-gradient(circle, rgba(var(--glow-rgb), 0) 34%, rgba(var(--glow-rgb), var(--glow-op-near-peak)) 56%, rgba(var(--glow-rgb), var(--glow-op-far-peak)) 68%, transparent 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes mtx-view-slide-forward{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes mtx-view-slide-back{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}',n.appendChild(r);const o=document.createElement("div");return o.id=t,n.appendChild(o),{shadowRoot:n,mountEl:o}},Sd=e=>{const t=e??document.body,n=document.createElement("div");n.className="marketrix-widget-container",n.style.pointerEvents="auto",e&&Object.assign(n.style,{width:"100%",height:"100%",position:"relative",overflow:"visible"}),t.appendChild(n);const{shadowRoot:r,mountEl:o}=xd(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},kd=(e,n,r=!1)=>{const o=m(e);return o.render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(xl,{previewMode:r,children:/* @__PURE__ */b(bd,{config:n})})})),o},Cd=()=>null!==vd.mount,Ed=()=>vd.mount?.config??null,Id=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;Md();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=xd(r,"marketrix-widget-notice-root");(wd=m(o)).render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(Rc,{container:o,children:/* @__PURE__ */b(Oc,{error:"error"===n?e:void 0,onClearError:Md,greeting:"error"===n?void 0:e,onGreetingDismiss:Md})})}))},Md=()=>{wd?.unmount(),wd=null,document.getElementById("marketrix-widget-notice-container")?.remove()},Td=null,Rd=0,Od=null;function Ad(e,t={}){const n=Hr(e);return n.invalidFields?(console.error(`Marketrix Widget: ${jr(n.invalidFields)}`),null):{...qr(n.settings,t),isPreviewMode:!0}}function _d(e,t,n=!1){const{container:r,mountEl:o}=Sd(t),i=kd(o,e,n);vd.mount={instance:i,config:e,container:r,host:t,previewMode:n}}var Dd=(e,t)=>{if(Td)return Td;if(window.__mtx?.state)return Promise.resolve();if(Cd())return Ae("Marketrix Widget: already initialized"),Promise.resolve();const n=async function(e,t,n){let r;window.__mtx={state:"initializing"},Id("Loading widget settings...");try{(e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==Ie&&(Ie=e,Me=Ee(e))})(e.mtxApiHost??""),r=await async function(e){const{mtxId:t,mtxKey:n}=e;if(!t||!n)throw new Error("Please provide mtxId + mtxKey");const r=`${t}:${n}`;let o=Vr.get(r);o||(o=async function(e,t,n){let r;try{({items:r}=await Te.widgetPublicSearch({marketrix_id:e,marketrix_key:t}))}catch(s){const e=Oe(s);throw function(e,t){return Object.assign(new Error(e),{cause:t})}(["Failed to fetch","ERR_CONNECTION_REFUSED","NetworkError","Network request failed"].some(t=>e.includes(t))?`Cannot connect to API server. Please ensure the API server is running at ${n||"configured API server"}. Error: ${e}`:`Widget validation failed: ${e}`,s)}if(!r.length)throw new Error("Widget not found or invalid credentials");const o=r.find(e=>"active"===e.status);if(!o){const e=r.map(e=>e.status).join(", ");throw new Error(`Found widget(s) but none are active. Current status(es): ${e}. Please activate the widget in the dashboard.`)}if(!o.application_id)throw new Error("Widget missing application_id");const i=Hr(o.settings);if(i.invalidFields)throw new Error(jr(i.invalidFields));return{settings:i.settings,applicationId:o.application_id}}(t,n,e.mtxApiHost),Vr.set(r,o),o.catch(()=>Vr.delete(r)));const{settings:i,applicationId:s}=await o;return{...qr(i,e),mtxId:t,mtxKey:n,mtxApp:s,isPreviewMode:!1}}(e)}catch(o){if(n!==Rd)return;return console.error("Marketrix Widget initialization failed:",o),Id(Oe(o,"Failed to initialize widget"),"error"),void(window.__mtx=void 0)}n===Rd&&(Md(),r.widget_enabled?(Be.setConfig(r),_d(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await We.getOrCreateChatId();if(n!==Rd)return;const t=new mr(e,r.mtxApp);Od=t,await t.start(),n!==Rd&&(t.stop(),Od===t&&(Od=null))}catch(o){n===Rd&&console.error("Failed to start session recording:",o)}})()):window.__mtx=void 0)}(e,t,++Rd);return Td=n,n.then(()=>{Td===n&&(Td=null)},()=>{Td===n&&(Td=null)}),n},Pd=()=>{Rd++,fr.disconnect(),Od?.stop(),Od=null,vr(),Lr.cleanup();const e=vd.mount;vd.mount=null,e&&(e.instance.unmount(),e.container.remove()),Td=null,window.__mtx=void 0,Md()},Nd=async e=>{const t=vd.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};Pd(),o?_d(i,r,!0):await Dd(i,r)},Ld=({settings:e,container:t})=>{const n=d(null),r=d(null),o=d(null);return a(()=>{const i=t??n.current??document.body;if(!(i&&(s=i,s instanceof HTMLElement)))return void console.error("MarketrixWidgetPreview: Invalid container");var s;const a=Ad(e);if(!a)return;const{container:c,mountEl:l}=Sd(i);return o.current=c,r.current=kd(l,a,!0),()=>{r.current&&(r.current.unmount(),r.current=null),o.current&&(o.current.remove(),o.current=null)}},[e,t]),t?null:/* @__PURE__ */b("div",{ref:n,style:{width:"100%",height:"100%",position:"relative"}})},Fd=async e=>{const t=e.container;if(void 0!==e.settings){const{settings:n,container:r,...o}=e,i=Ad(e.settings,o);if(!i)return;Pd(),_d(i,t,!0)}else{if(void 0===e.mtxId||void 0===e.mtxKey)throw new Error("Invalid configuration: provide either settings (preview) or mtxId+mtxKey (production)");{const{container:n,...r}=e;await Dd(r,t)}}};"undefined"!=typeof window&&setTimeout(()=>{try{(e=>{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__mtx?.state)return;const t=document.querySelectorAll("script[mtx-id]"),n=t[t.length-1];if(!(n&&(r=n,r instanceof HTMLScriptElement)))return;var r;const o=n.getAttribute("mtx-id"),i=n.getAttribute("mtx-key"),s=n.getAttribute("mtx-api-host");if(!o||!i||!s){if(Cd())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void Id("Please configure mtx-id, mtx-key and mtx-api-host","error")}const a={mtxId:o,mtxKey:i,mtxApiHost:s};"false"===n.getAttribute("mtx-use-screenshare")&&(a.use_screenshare=!1),e(a).catch(e=>console.error("[AutoInit] Failed to initialize widget:",e))})(Dd)}catch(e){console.error("Marketrix Widget: Auto-init registration failed",e)}},0);var zd={MarketrixWidgetPreview:Ld,mountWidget:Fd,initWidget:Dd,unmountWidget:Pd,updateMarketrixConfig:Nd,getCurrentConfig:Ed};export{Ld as MarketrixWidgetPreview,zd as default,Ed as getCurrentConfig,Dd as initWidget,Fd as mountWidget,Pd as unmountWidget,Nd as updateMarketrixConfig};
|