@marketrix.ai/widget 3.8.142 → 3.8.144
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/src/components/base/Card.d.ts +0 -4
- package/dist/src/components/base/Flex.d.ts +0 -9
- package/dist/src/components/base/icons.d.ts +0 -8
- package/dist/src/components/blocks/HeaderBar.d.ts +0 -1
- package/dist/src/components/navigation/ViewTransition.d.ts +0 -6
- package/dist/src/components/ui/StateMessage.d.ts +0 -4
- package/dist/src/components/views/ChatView.d.ts +0 -1
- package/dist/src/context/ChatContext.d.ts +0 -14
- package/dist/src/context/UIStateContext.d.ts +0 -1
- package/dist/src/context/WidgetProviders.d.ts +0 -11
- package/dist/src/context/sseReducer.d.ts +0 -17
- package/dist/src/design-system/semantic-tokens.d.ts +0 -7
- package/dist/src/design-system/shadows.d.ts +0 -6
- package/dist/src/hooks/useFocusTrap.d.ts +0 -5
- package/dist/src/hooks/useScrollLock.d.ts +0 -5
- package/dist/src/hooks/useWidget.d.ts +0 -5
- package/dist/src/index.d.ts +0 -17
- package/dist/src/sdk/contracts/common.d.ts +0 -3
- package/dist/src/sdk/contracts/entities.d.ts +3 -9
- package/dist/src/sdk/contracts/widget.d.ts +2 -5
- package/dist/src/services/ApiService.d.ts +2 -10
- package/dist/src/services/BrowserToolService.d.ts +1 -5
- package/dist/src/services/ChatService.d.ts +3 -13
- package/dist/src/services/ChatSessionManager.d.ts +1 -13
- package/dist/src/services/ConfigManager.d.ts +1 -5
- package/dist/src/services/DomService.d.ts +8 -33
- package/dist/src/services/RrwebSessionRecorder.d.ts +5 -18
- package/dist/src/services/ScreenShareService.d.ts +1 -9
- package/dist/src/services/StorageService.d.ts +8 -31
- package/dist/src/services/ValidationService.d.ts +3 -9
- package/dist/src/services/WidgetService.d.ts +1 -9
- package/dist/src/test/a11y-utils.d.ts +0 -5
- package/dist/src/test/fixtures.d.ts +0 -4
- package/dist/src/types/browserTools.d.ts +0 -7
- package/dist/src/types/index.d.ts +2 -18
- package/dist/src/utils/apiUtils.d.ts +0 -4
- package/dist/src/utils/bootstrap.d.ts +0 -28
- package/dist/src/utils/chat.d.ts +0 -38
- package/dist/src/utils/color.d.ts +0 -7
- package/dist/src/utils/dom.d.ts +0 -6
- package/dist/src/utils/logger.d.ts +0 -6
- package/dist/src/utils/validation.d.ts +0 -6
- package/dist/widget.mjs +3 -3
- package/dist/widget.mjs.map +1 -1
- package/package.json +1 -1
package/dist/widget.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import*as e from"react";import t,{createContext as n,createElement as r,forwardRef as i,useCallback as o,useContext as a,useEffect as s,useId as c,useLayoutEffect as l,useMemo as d,useRef as u,useState as p}from"react";import{createRoot as h}from"react-dom/client";import{Fragment as m,jsx as f,jsxs as g}from"react/jsx-runtime";var w=2147483002,b=2147483001,y=2147483005;function v(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}function x(e){return function(e){const t=v(e);if(!t)return.5;const[n,r,i]=[t.r/255,t.g/255,t.b/255].map(e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4));return.2126*n+.7152*r+.0722*i}(e)>.5?"#000000":"#ffffff"}function k(e,t){if(e.startsWith("rgba")||e.startsWith("rgb")){const n=e.match(/(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(n)return`rgba(${n[1]}, ${n[2]}, ${n[3]}, ${t})`}const n=v(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:(e.includes("gradient")||e.includes("linear-gradient"),e)}function _(e,t){const n=v(e);if(!n)return e;const r=1-t;return i=Math.round(n.r*r),o=Math.round(n.g*r),a=Math.round(n.b*r),`#${[i,o,a].map(e=>e.toString(16).padStart(2,"0")).join("")}`;var i,o,a}var S=e=>e?e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):/* @__PURE__ */(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),z=e=>{switch(e){case"show":return"Show";case"tell":return"Tell";case"do":return"Do";default:return e}},E={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280",widget_border_radius:"20px",widget_font_size:"14px",widget_width:"400px",widget_height:"600px",widget_shadow:"0 5px 40px 0 rgba(0, 0, 0, 0.3)",widget_animation_duration:"300ms",widget_fade_duration:"200ms"};function I(e){return{color:{background:e.widget_background_color,foreground:e.widget_text_color,foregroundMuted:k(e.widget_text_color,.6),foregroundFaint:k(e.widget_text_color,.4),border:e.widget_border_color,borderMuted:k(e.widget_border_color,.3),primary:e.widget_accent_color,primaryForeground:x(e.widget_accent_color),primaryHover:k(e.widget_accent_color,.85),primaryMuted:k(e.widget_accent_color,.3),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:k(e.widget_secondary_color,.2),secondaryHover:k(e.widget_secondary_color,.3)},radius:e.widget_border_radius,shadow:e.widget_shadow,typography:{fontSizeBase:e.widget_font_size},motion:{durationAnimation:e.widget_animation_duration,durationFade:e.widget_fade_duration},size:{widgetWidth:e.widget_width,widgetHeight:e.widget_height}}}I(E);function C(e){return Array.isArray(e)?e:null==e?[]:[e]}var T="orpc",A=class extends Error{constructor(...e){super(...e),this.name="AbortError"}};function $(e){let t;return()=>{if(t)return t.result;const n=e();return t={result:n},n}}function M(){return globalThis["__@orpc/shared@1.14.6/otel/config__"]}function N(e,t={},n){return(M()?.tracer)?.startSpan(e,t,n)}function O(e,t,n={}){if(!e)return;const r=function(e){if(e instanceof Error){const t={message:e.message,name:e.name,stack:e.stack};return!("code"in e)||"string"!=typeof e.code&&"number"!=typeof e.code||(t.code=e.code),t}return{message:String(e)}}(t);e.recordException(r),n.signal?.aborted&&n.signal.reason===t||e.setStatus({code:2,message:r.message})}async function P({name:e,context:t,...n},r){const i=M()?.tracer;if(!i)return r();const o=async e=>{try{return await r(e)}catch(t){throw O(e,t,n),t}finally{e.end()}};return t?i.startActiveSpan(e,n,t,o):i.startActiveSpan(e,n,o)}async function R(e,t){const n=M();if(!e||!n)return t();const r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function L(e){return!(!e||"object"!=typeof e)&&("next"in e&&"function"==typeof e.next&&Symbol.asyncIterator in e&&"function"==typeof e[Symbol.asyncIterator])}var j=Symbol.asyncDispose??Symbol.for("asyncDispose"),D=class{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=function(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}(async()=>{if(this.#e)return{done:!0,value:void 0};try{const t=await e();return t.done&&(this.#e=!0),t}catch(t){throw this.#e=!0,t}finally{this.#e&&!this.#t&&(this.#t=!0,await this.#n("next"))}})}next(){return this.#r()}async return(e){return this.#e=!0,this.#t||(this.#t=!0,await this.#n("return")),{done:!0,value:e}}async throw(e){throw this.#e=!0,this.#t||(this.#t=!0,await this.#n("throw")),e}async[j](){this.#e=!0,this.#t||(this.#t=!0,await this.#n("dispose"))}[Symbol.asyncIterator](){return this}};function H({name:e,...t},n){let r;return new D(async()=>{r??=N(e);try{const e=await R(r,()=>n.next());return r?.addEvent(e.done?"completed":"yielded"),e}catch(i){throw O(r,i,t),i}},async e=>{try{"next"!==e&&await R(r,()=>n.return?.())}catch(i){throw O(r,i,t),i}finally{r?.end()}})}function Z(e,t,n){const r=(t,i)=>{const o=e[i];return o?o({...t,next:(e=t)=>r(e,i+1)}):n(t)};return r(t,0)}function F(e){if(e)return JSON.parse(e)}function U(e){return JSON.stringify(e)}function B(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function W(e){return!!e&&("object"==typeof e||"function"==typeof e)}function q(e,...t){return"function"==typeof e?e(...t):e}function V(e){return new Proxy(e,{get(e,t,n){const r=Reflect.get(e,t,n);return"then"!==t||"function"!=typeof r?r:new Proxy(r,{apply(t,n,r){if(2!==r.length||r.some(e=>{return!("function"==typeof(t=e)&&G.test(t.toString()));var t}))return Reflect.apply(t,n,r);let i=!0;r[0].call(n,V(new Proxy(e,{get:(e,t,n)=>{if(!i||"then"!==t)return Reflect.get(e,t,n);i=!1}})))}})}})}var G=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;var J,K={BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_SUPPORTED:{status:405,message:"Method Not Supported"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},UNPROCESSABLE_CONTENT:{status:422,message:"Unprocessable Content"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},CLIENT_CLOSED_REQUEST:{status:499,message:"Client Closed Request"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"}};var Y=class e extends Error{defined;code;status;data;static{const t=Symbol.for("__@orpc/client@1.14.6/error/ORPC_ERROR_CONSTRUCTORS__");globalThis[t]??=/* @__PURE__ */new WeakSet,(J=globalThis[t]).add(e)}constructor(e,...t){const n=function(e){return e[0]??{}}(t);if(void 0!==n.status&&!X(n.status))throw new Error("[ORPCError] Invalid error status code.");const r=function(e,t){return t||K[e]?.message||e}(e,n.message);super(r,n),this.code=e,this.status=function(e,t){return t??K[e]?.status??500}(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(J.has(this)){const t=function(e){return W(e)?Object.getPrototypeOf(e)?.constructor:null}(e);if(t&&J.has(t))return!0}return super[Symbol.hasInstance](e)}};function X(e){return e<200||e>=400}function Q(e){if(!B(e))return!1;const t=["defined","code","status","message","data"];return!Object.keys(e).some(e=>!t.includes(e))&&("defined"in e&&"boolean"==typeof e.defined&&"code"in e&&"string"==typeof e.code&&"status"in e&&"number"==typeof e.status&&X(e.status)&&"message"in e&&"string"==typeof e.message)}function ee(e,t={}){return new Y(e.code,{...t,...e})}var te=class extends TypeError{},ne=class extends TypeError{},re=class extends Error{data;constructor(e){super(e?.message??"An error event was received",e),this.data=e?.data}};function ie(e){const t=e.replace(/\n+$/,"").split(/\n/),n={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(const r of t){const e=r.indexOf(":"),t=-1===e?r:r.slice(0,e),i=-1===e?"":r.slice(e+1).replace(/^\s/,"");if(0===e)n.comments.push(i);else if("data"===t)n.data??="",n.data+=`${i}\n`;else if("event"===t)n.event=i;else if("id"===t)n.id=i;else if("retry"===t){const e=Number.parseInt(i);Number.isInteger(e)&&e>=0&&e.toString()===i&&(n.retry=e)}}return n.data=n.data?.replace(/\n$/,""),n}var oe=class{constructor(e={}){this.options=e}incomplete="";feed(e){this.incomplete+=e;const t=this.incomplete.lastIndexOf("\n\n");if(-1===t)return;const n=this.incomplete.slice(0,t).split(/\n\n/);this.incomplete=this.incomplete.slice(t+2);for(const r of n){const e=ie(`${r}\n\n`);this.options.onEvent&&this.options.onEvent(e)}}end(){if(this.incomplete)throw new ne("Event Iterator ended before complete")}},ae=class extends TransformStream{constructor(){let e;super({start(t){e=new oe({onEvent:e=>{t.enqueue(e)}})},transform(t){e.feed(t)},flush(){e.end()}})}};function se(e){if(e.includes("\n"))throw new te("Event's id must not contain a newline character")}function ce(e){if(!Number.isInteger(e)||e<0)throw new te("Event's retry must be a integer and >= 0")}function le(e){if(e.includes("\n"))throw new te("Event's comment must not contain a newline character")}function de(e){let t="";return t+=function(e){let t="";for(const n of e??[])le(n),t+=`: ${n}\n`;return t}(e.comments),void 0!==e.event&&(!function(e){if(e.includes("\n"))throw new te("Event's event must not contain a newline character")}(e.event),t+=`event: ${e.event}\n`),void 0!==e.retry&&(ce(e.retry),t+=`retry: ${e.retry}\n`),void 0!==e.id&&(se(e.id),t+=`id: ${e.id}\n`),t+=function(e){const t=e?.split(/\n/)??[];let n="";for(const r of t)n+=`data: ${r}\n`;return n}(e.data),t+="\n",t}var ue=Symbol("ORPC_EVENT_SOURCE_META");function pe(e,t){if(void 0===t.id&&void 0===t.retry&&!t.comments?.length)return e;if(void 0!==t.id&&se(t.id),void 0!==t.retry&&ce(t.retry),void 0!==t.comments)for(const n of t.comments)le(n);return new Proxy(e,{get:(e,n,r)=>n===ue?t:Reflect.get(e,n,r)})}function he(e){return W(e)?Reflect.get(e,ue):void 0}function me(e){const t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&"string"==typeof t[2])return function(e){try{return decodeURIComponent(e)}catch{return e}}(t[2]);const n=e.match(/filename="((?:\\"|[^"])*)"/i);return n&&"string"==typeof n[1]?n[1].replace(/\\"/g,'"'):void 0}function fe(e,t){const n=async e=>{let n=await t.error(e);if(n!==e){const t=he(e);t&&W(n)&&(n=pe(n,t))}return n};return new D(async()=>{const{done:r,value:i}=await(async()=>{try{return await e.next()}catch(t){throw await n(t)}})();let o=await t.value(i,r);if(o!==i){const e=he(i);e&&W(o)&&(o=pe(o,e))}return{done:r,value:o}},async()=>{try{await(e.return?.())}catch(t){throw await n(t)}})}function ge(e,t={}){const n=t.path??[];return V(new Proxy(async(...[t,r={}])=>await e.call(n,t,function(e){return{...e,context:e.context??{}}}(r)),{get:(r,i)=>"string"!=typeof i?Reflect.get(r,i):ge(e,{...t,path:[...n,i]})}))}function we(e,t={}){return P({name:"parse_standard_body",signal:t.signal},async()=>{const n=e.headers.get("content-disposition");if("string"==typeof n){const t=me(n)??"blob",r=await e.blob();return new File([r],t,{type:r.type})}const r=e.headers.get("content-type");if(!r||r.startsWith("application/json"))return F(await e.text());if(r.startsWith("multipart/form-data"))return await e.formData();if(r.startsWith("application/x-www-form-urlencoded")){const t=await e.text();return new URLSearchParams(t)}if(r.startsWith("text/event-stream"))return function(e,t={}){const n=(e?.pipeThrough(new TextDecoderStream).pipeThrough(new ae))?.getReader();let r,i=!1;return new D(async()=>{r??=N("consume_event_iterator_stream");try{for(;;){if(void 0===n)return{done:!0,value:void 0};const{done:e,value:t}=await R(r,()=>n.read());if(e){if(i)throw new A("Stream was cancelled");return{done:!0,value:void 0}}switch(t.event){case"message":{let e=F(t.data);return W(e)&&(e=pe(e,t)),r?.addEvent("message"),{done:!1,value:e}}case"error":{let e=new re({data:F(t.data)});throw e=pe(e,t),r?.addEvent("error"),e}case"done":{let e=F(t.data);return W(e)&&(e=pe(e,t)),r?.addEvent("done"),{done:!0,value:e}}default:r?.addEvent("maybe_keepalive")}}}catch(e){throw e instanceof re||O(r,e,t),e}},async e=>{try{"next"!==e&&(i=!0,r?.addEvent("cancelled")),await R(r,()=>n?.cancel())}catch(o){throw O(r,o,t),o}finally{r?.end()}})}(e.body,t);if(r.startsWith("text/plain"))return await e.text();const i=await e.blob();return new File([i],"blob",{type:i.type})})}function be(e,t,n={}){if(e instanceof ReadableStream)return e;const r=t.get("content-disposition");return t.delete("content-type"),t.delete("content-disposition"),void 0!==e?e instanceof Blob?(t.set("content-type",e.type),t.set("content-length",e.size.toString()),t.set("content-disposition",r??function(e,t="inline"){return`${t}; filename="${e.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,'\\"')}"; filename*=utf-8''${encodeURIComponent(e).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}`}(e instanceof File?e.name:"blob")),e):e instanceof FormData||e instanceof URLSearchParams?e:L(e)?(t.set("content-type","text/event-stream"),function(e,t={}){const n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5e3,i=t.eventIteratorKeepAliveComment??"",o=t.eventIteratorInitialCommentEnabled??!0,a=t.eventIteratorInitialComment??"";let s,c,l=!1;return new ReadableStream({start(e){c=N("stream_event_iterator"),o&&e.enqueue(de({comments:[a]}))},async pull(t){try{n&&(s=setInterval(()=>{t.enqueue(de({comments:[i]})),c?.addEvent("keepalive")},r));const o=await R(c,()=>e.next());if(clearInterval(s),l)return;const a=he(o.value);if(!o.done||void 0!==o.value||void 0!==a){const e=o.done?"done":"message";t.enqueue(de({...a,event:e,data:U(o.value)})),c?.addEvent(e)}o.done&&(t.close(),c?.end())}catch(o){if(clearInterval(s),l)return;o instanceof re?(t.enqueue(de({...he(o),event:"error",data:U(o.data)})),c?.addEvent("error"),t.close()):(O(c,o),t.error(o)),c?.end()}},async cancel(){try{l=!0,clearInterval(s),c?.addEvent("cancelled"),await R(c,()=>e.return?.())}catch(t){throw O(c,t),t}finally{c?.end()}}}).pipeThrough(new TextEncoderStream)}(e,n)):(t.set("content-type","application/json"),U(e)):void 0}function ye(e,t={}){return e.forEach((e,n)=>{Array.isArray(t[n])?t[n].push(e):void 0!==t[n]?t[n]=[t[n],e]:t[n]=e}),t}function ve(e,t={}){const n=function(e,t=new Headers){for(const[n,r]of Object.entries(e))if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.append(n,r);return t}(e.headers),r=be(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}var xe=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e){for(const t of this.plugins)t.init?.(e)}},ke=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new xe(n.plugins).init(n),this.interceptors=C(n.interceptors),this.clientInterceptors=C(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return P({name:`${T}.${e.join("/")}`,signal:n.signal},r=>(r?.setAttribute("rpc.system",T),r?.setAttribute("rpc.method",e.join(".")),L(t)&&(t=H({name:"consume_event_iterator_input",signal:n.signal},t)),Z(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{const i=M();let o;const a=i?.trace.getActiveSpan()??r;a&&i&&(o=i?.trace.setSpan(i.context.active(),a));const s=await P({name:"encode_request",context:o},()=>this.codec.encode(e,t,n)),c=await Z(this.clientInterceptors,{...n,input:t,path:e,request:s},({input:e,path:t,request:n,...r})=>P({name:"send_request",signal:r.signal,context:o},()=>this.sender.call(n,r,t,e))),l=await P({name:"decode_response",context:o},()=>this.codec.decode(c,n,e,t));return L(l)?H({name:"consume_event_iterator_output",signal:n.signal},l):l})))}},_e=0,Se=1,ze=2,Ee=3,Ie=4,Ce=5,Te=6,Ae=7,$e=class{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map(e=>e.type)).size)throw new Error("Custom serializer type must be unique.")}serialize(e,t=[],n=[],r=[],i=[]){for(const o of this.customSerializers)if(o.condition(e)){const a=this.serialize(o.serialize(e),t,n,r,i);return n.push([o.type,...t]),a}if(e instanceof Blob)return r.push(t),i.push(e),[e,n,r,i];if("bigint"==typeof e)return n.push([_e,...t]),[e.toString(),n,r,i];if(e instanceof Date)return n.push([Se,...t]),Number.isNaN(e.getTime())?[null,n,r,i]:[e.toISOString(),n,r,i];if(Number.isNaN(e))return n.push([ze,...t]),[null,n,r,i];if(e instanceof URL)return n.push([Ie,...t]),[e.toString(),n,r,i];if(e instanceof RegExp)return n.push([Ce,...t]),[e.toString(),n,r,i];if(e instanceof Set){const o=this.serialize(Array.from(e),t,n,r,i);return n.push([Te,...t]),o}if(e instanceof Map){const o=this.serialize(Array.from(e.entries()),t,n,r,i);return n.push([Ae,...t]),o}if(Array.isArray(e))return[e.map((e,o)=>void 0===e?(n.push([Ee,...t,o]),null):this.serialize(e,[...t,o],n,r,i)[0]),n,r,i];if(B(e)){const o={};for(const a in e)"toJSON"===a&&"function"==typeof e[a]||(o[a]=this.serialize(e[a],[...t,a],n,r,i)[0]);return[o,n,r,i]}return[e,n,r,i]}deserialize(e,t,n,r){const i={data:e};n&&r&&n.forEach((e,t)=>{let n=i,o="data";e.forEach(e=>{if(n=n[o],o=e,!Object.hasOwn(n,o))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${o}`)}),n[o]=r(t)});for(const o of t){const e=o[0];let t=i,n="data";for(let r=1;r<o.length;r++)if(t=t[n],n=o[r],!Object.hasOwn(t,n))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${n}`);for(const r of this.customSerializers)if(r.type===e){t[n]=r.deserialize(t[n]);break}switch(e){case _e:t[n]=BigInt(t[n]);break;case Se:t[n]=new Date(t[n]??"Invalid Date");break;case ze:t[n]=NaN;break;case Ee:t[n]=void 0;break;case Ie:t[n]=new URL(t[n]);break;case Ce:{const[,e,r]=t[n].match(/^\/(.*)\/([a-z]*)$/);t[n]=new RegExp(e,r);break}case Te:t[n]=new Set(t[n]);break;case Ae:t[n]=new Map(t[n])}}return i.data}};var Me,Ne=class{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??"POST",this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=function(e){return"function"==typeof e.forEach?ye(e):e}(await q(this.headers,n,e,t));void 0!==n.lastEventId&&(r=function(e,t){const n={...e};for(const r in t)Array.isArray(t[r])?n[r]=[...C(n[r]),...t[r]]:void 0!==t[r]&&(Array.isArray(n[r])?n[r]=[...n[r],t[r]]:void 0!==n[r]?n[r]=[n[r],t[r]]:n[r]=t[r]);return n}(r,{"last-event-id":n.lastEventId}));const i=await q(this.expectedMethod,n,e,t),o=await q(this.baseUrl,n,e,t),a=new URL(o);a.pathname=`${a.pathname.replace(/\/$/,"")}${function(e){return`/${e.map(encodeURIComponent).join("/")}`}(e)}`;const s=this.serializer.serialize(t);if(!("GET"!==i||s instanceof FormData||L(s))){const o=await q(this.maxUrlLength,n,e,t),c=new URL(a);if(c.searchParams.append("data",U(s)),c.toString().length<=o)return{body:void 0,method:i,headers:r,url:c,signal:n.signal}}return{url:a,method:"GET"===i?this.fallbackMethod:i,headers:r,body:s,signal:n.signal}}async decode(e){const t=!X(e.status),n=await(async()=>{let t=!1;try{const n=await e.body();return t=!0,this.serializer.deserialize(n)}catch(n){if(!t)throw new Error("Cannot parse response body, please check the response body and content-type.",{cause:n});throw new Error("Invalid RPC response format.",{cause:n})}})();if(!t){if(Q(n))throw ee(n);throw new Y((r=e.status,Object.entries(K).find(([,e])=>e.status===r)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"),{status:e.status,data:{...e,body:n}})}var r;return n}},Oe=class{constructor(e){this.jsonSerializer=e}serialize(e){return L(e)?fe(e,{value:async e=>this.#i(e,!1),error:async e=>{return new re({data:this.#i((t=e,t instanceof Y?t:new Y("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:t})).toJSON(),!1),cause:e});var t}}):this.#i(e,!0)}#i(e,t){const[n,r,i,o]=this.jsonSerializer.serialize(e),a=0===r.length?void 0:r;if(!t||0===o.length)return{json:n,meta:a};const s=new FormData;return s.set("data",U({json:n,meta:a,maps:i})),o.forEach((e,t)=>{s.set(t.toString(),e)}),s}deserialize(e){return L(e)?fe(e,{value:async e=>this.#o(e),error:async e=>{if(!(e instanceof re))return e;const t=this.#o(e.data);return Q(t)?ee(t,{cause:e}):new re({data:t,cause:e})}}):this.#o(e)}#o(e){if(void 0===e)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);const t=JSON.parse(e.get("data"));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,t=>e.get(t.toString()))}},Pe=class extends ke{constructor(e,t){super(new Ne(new Oe(new $e(t)),t),e,t)}},Re=class extends xe{initRuntimeAdapter(e){for(const t of this.plugins)t.initRuntimeAdapter?.(e)}},Le=class{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new Re(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=C(e.adapterInterceptors)}async call(e,t,n,r){const i=ve(e,this.toFetchRequestOptions);return function(e,t={}){return{body:$(()=>we(e,t)),status:e.status,get headers(){const t=ye(e.headers);return Object.defineProperty(this,"headers",{value:t,writable:!0}),t},set headers(e){Object.defineProperty(this,"headers",{value:e,writable:!0})}}}(await Z(this.adapterInterceptors,{...t,request:i,path:n,input:r,init:{redirect:"manual"}},({request:e,path:t,input:n,init:r,...i})=>this.fetch(e,r,i,t,n)),{signal:i.signal})}},je=class extends Pe{constructor(e){super(new Le(e),e)}};function De(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:/* @__PURE__ */new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const i=a.prototype,o=Object.keys(i);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=i[t].bind(n))}}const i=n?.Parent??Object;class o extends i{}function a(e){var t;const i=n?.Parent?new o:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const n of i._zod.deferred)n();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var He=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ze=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Me=globalThis).__zod_globalConfig??(Me.__zod_globalConfig={});var Fe=globalThis.__zod_globalConfig;function Ue(e){return e&&Object.assign(Fe,e),Fe}function Be(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function We(e,t){return"bigint"==typeof t?t.toString():t}function qe(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ve(e){return null==e}function Ge(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var Je=/* @__PURE__*/Symbol("evaluating");function Ke(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Je)return void 0===r&&(r=Je,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ye(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Xe(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Qe(e){return JSON.stringify(e)}var et="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function tt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var nt=/* @__PURE__*/qe(()=>{if(Fe.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function rt(e){if(!1===tt(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==tt(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function it(e){return rt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ot=/* @__PURE__*/new Set(["string","number","symbol"]);function at(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function ct(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}var lt={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function dt(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function ut(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function pt(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ht(e){return"string"==typeof e?e:e?.message}function mt(e,t,n){const r=e.message?e.message:ht(e.inst?._zod.def?.error?.(e))??ht(t?.error?.(e))??ht(n.customError?.(e))??ht(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:a,...s}=e;return s.path??(s.path=[]),s.message=r,t?.reportInput&&(s.input=a),s}function ft(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function gt(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}var wt=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,We,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},bt=De("$ZodError",wt),yt=De("$ZodError",wt,{Parent:Error});var vt=e=>(t,n,r,i)=>{const o=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new He;if(a.issues.length){const t=new(i?.Err??e)(a.issues.map(e=>mt(e,o,Ue())));throw et(t,i?.callee),t}return a.value},xt=e=>async(t,n,r,i)=>{const o=r?{...r,async:!0}:{async:!0};let a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(i?.Err??e)(a.issues.map(e=>mt(e,o,Ue())));throw et(t,i?.callee),t}return a.value},kt=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new He;return o.issues.length?{success:!1,error:new(e??bt)(o.issues.map(e=>mt(e,i,Ue())))}:{success:!0,data:o.value}},_t=/* @__PURE__*/kt(yt),St=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>mt(e,i,Ue())))}:{success:!0,data:o.value}},zt=/* @__PURE__*/St(yt),Et=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return vt(e)(t,n,i)},It=e=>(t,n,r)=>vt(e)(t,n,r),Ct=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return xt(e)(t,n,i)},Tt=e=>async(t,n,r)=>xt(e)(t,n,r),At=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return kt(e)(t,n,i)},$t=e=>(t,n,r)=>kt(e)(t,n,r),Mt=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return St(e)(t,n,i)},Nt=e=>async(t,n,r)=>St(e)(t,n,r),Ot=/^[cC][0-9a-z]{6,}$/,Pt=/^[0-9a-z]+$/,Rt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lt=/^[0-9a-vA-V]{20}$/,jt=/^[A-Za-z0-9]{27}$/,Dt=/^[a-zA-Z0-9_-]{21}$/,Ht=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Zt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ft=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ut=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Bt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,qt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Vt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Gt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Jt=/^[A-Za-z0-9_-]*$/,Kt=/^https?$/,Yt=/^\+[1-9]\d{6,14}$/,Xt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Qt=/*@__PURE__*/new RegExp(`^${Xt}$`);function en(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}var tn=/^-?\d+$/,nn=/^-?\d+(?:\.\d+)?$/,rn=/^(?:true|false)$/i,on=/^[^A-Z]*$/,an=/^[^a-z]*$/,sn=/*@__PURE__*/De("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),cn={number:"number",bigint:"bigint",object:"date"},ln=/*@__PURE__*/De("$ZodCheckLessThan",(e,t)=>{sn.init(e,t);const n=cn[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),dn=/*@__PURE__*/De("$ZodCheckGreaterThan",(e,t)=>{sn.init(e,t);const n=cn[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),un=/*@__PURE__*/De("$ZodCheckMultipleOf",(e,t)=>{sn.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value!==BigInt(0):0!==function(e,t){const n=e/t,r=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}(n.value,t.value))&&n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),pn=/*@__PURE__*/De("$ZodCheckNumberFormat",(e,t)=>{sn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,o]=lt[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=o,n&&(r.pattern=tn)}),e._zod.check=a=>{const s=a.value;if(n){if(!Number.isInteger(s))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}s<i&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),hn=/*@__PURE__*/De("$ZodCheckMaxLength",(e,t)=>{var n;sn.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ve(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const i=ft(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),mn=/*@__PURE__*/De("$ZodCheckMinLength",(e,t)=>{var n;sn.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ve(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const i=ft(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),fn=/*@__PURE__*/De("$ZodCheckLengthEquals",(e,t)=>{var n;sn.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ve(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const o=ft(r),a=i>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),gn=/*@__PURE__*/De("$ZodCheckStringFormat",(e,t)=>{var n,r;sn.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=/* @__PURE__ */new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),wn=/*@__PURE__*/De("$ZodCheckRegex",(e,t)=>{gn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),bn=/*@__PURE__*/De("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=on),gn.init(e,t)}),yn=/*@__PURE__*/De("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=an),gn.init(e,t)}),vn=/*@__PURE__*/De("$ZodCheckIncludes",(e,t)=>{sn.init(e,t);const n=at(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),xn=/*@__PURE__*/De("$ZodCheckStartsWith",(e,t)=>{sn.init(e,t);const n=new RegExp(`^${at(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),kn=/*@__PURE__*/De("$ZodCheckEndsWith",(e,t)=>{sn.init(e,t);const n=new RegExp(`.*${at(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),_n=/*@__PURE__*/De("$ZodCheckOverwrite",(e,t)=>{sn.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Sn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const i of r)this.content.push(i)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}},zn={major:4,minor:4,patch:3},En=/*@__PURE__*/De("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=zn;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const t of i._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,i=dt(e);for(const o of t){if(o._zod.def.when){if(ut(e))continue;if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,a=o._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new He;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(i||(i=dt(e,t)))});else{if(e.issues.length===t)continue;i||(i=dt(e,t))}}return r?r.then(()=>e):e},n=(n,i,o)=>{if(dt(n))return n.aborted=!0,n;const a=t(i,r,o);if(a instanceof Promise){if(!1===o.async)throw new He;return a.then(t=>e._zod.parse(t,o))}return e._zod.parse(a,o)};e._zod.run=(i,o)=>{if(o.skipChecks)return e._zod.parse(i,o);if("backward"===o.direction){const t=e._zod.parse({value:i.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,o)):n(t,i,o)}const a=e._zod.parse(i,o);if(a instanceof Promise){if(!1===o.async)throw new He;return a.then(e=>t(e,r,o))}return t(a,r,o)}}Ke(e,"~standard",()=>({validate:t=>{try{const n=_t(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return zt(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),In=/*@__PURE__*/De("$ZodString",(e,t)=>{var n;En.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Cn=/*@__PURE__*/De("$ZodStringFormat",(e,t)=>{gn.init(e,t),In.init(e,t)}),Tn=/*@__PURE__*/De("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Zt),Cn.init(e,t)}),An=/*@__PURE__*/De("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ft(e))}else t.pattern??(t.pattern=Ft());Cn.init(e,t)}),$n=/*@__PURE__*/De("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ut),Cn.init(e,t)}),Mn=/*@__PURE__*/De("$ZodURL",(e,t)=>{Cn.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===Kt.source&&!/^https?:\/\//i.test(r))return void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});const i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Nn=/*@__PURE__*/De("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Cn.init(e,t)}),On=/*@__PURE__*/De("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Dt),Cn.init(e,t)}),Pn=/*@__PURE__*/De("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ot),Cn.init(e,t)}),Rn=/*@__PURE__*/De("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Pt),Cn.init(e,t)}),Ln=/*@__PURE__*/De("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Rt),Cn.init(e,t)}),jn=/*@__PURE__*/De("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Lt),Cn.init(e,t)}),Dn=/*@__PURE__*/De("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=jt),Cn.init(e,t)}),Hn=/*@__PURE__*/De("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=en({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Xt}T(?:${r})$`)}(t)),Cn.init(e,t)}),Zn=/*@__PURE__*/De("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Qt),Cn.init(e,t)}),Fn=/*@__PURE__*/De("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${en(t)}$`)),Cn.init(e,t)}),Un=/*@__PURE__*/De("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ht),Cn.init(e,t)}),Bn=/*@__PURE__*/De("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Bt),Cn.init(e,t),e._zod.bag.format="ipv4"}),Wn=/*@__PURE__*/De("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Wt),Cn.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),qn=/*@__PURE__*/De("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=qt),Cn.init(e,t)}),Vn=/*@__PURE__*/De("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Vt),Cn.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Gn(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Jn=/*@__PURE__*/De("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Gt),Cn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Gn(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var Kn=/*@__PURE__*/De("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Jt),Cn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Jt.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Gn(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Yn=/*@__PURE__*/De("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Yt),Cn.init(e,t)});var Xn=/*@__PURE__*/De("$ZodJWT",(e,t)=>{Cn.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Qn=/*@__PURE__*/De("$ZodNumber",(e,t)=>{En.init(e,t),e._zod.pattern=e._zod.bag.pattern??nn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),er=/*@__PURE__*/De("$ZodNumberFormat",(e,t)=>{pn.init(e,t),Qn.init(e,t)}),tr=/*@__PURE__*/De("$ZodBoolean",(e,t)=>{En.init(e,t),e._zod.pattern=rn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),nr=/*@__PURE__*/De("$ZodUnknown",(e,t)=>{En.init(e,t),e._zod.parse=e=>e}),rr=/*@__PURE__*/De("$ZodNever",(e,t)=>{En.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),ir=/*@__PURE__*/De("$ZodDate",(e,t)=>{En.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(a){}const i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}});function or(e,t,n){e.issues.length&&t.issues.push(...pt(n,e.issues)),t.value[n]=e.value}var ar=/*@__PURE__*/De("$ZodArray",(e,t)=>{En.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const a=i[e],s=t.element._zod.run({value:a,issues:[]},r);s instanceof Promise?o.push(s.then(t=>or(t,n,e))):or(s,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function sr(e,t,n,r,i,o){const a=n in r;if(e.issues.length){if(i&&o&&!a)return;t.issues.push(...pt(n,e.issues))}a||i?void 0===e.value?a&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function cr(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function lr(e,t,n,r,i,o){const a=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,d="optional"===c.optin,u="optional"===c.optout;for(const p in t){if("__proto__"===p)continue;if(s.has(p))continue;if("never"===l){a.push(p);continue}const i=c.run({value:t[p],issues:[]},r);i instanceof Promise?e.push(i.then(e=>sr(e,n,p,t,d,u))):sr(i,n,p,t,d,u)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}var dr=/*@__PURE__*/De("$ZodObject",(e,t)=>{if(En.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const n=qe(()=>cr(t));Ke(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */new Set);for(const e of r.values)n[t].add(e)}}return n});const r=tt,i=t.catchall;let o;e._zod.parse=(t,a)=>{o??(o=n.value);const s=t.value;if(!r(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};const c=[],l=o.shape;for(const e of o.keys){const n=l[e],r="optional"===n._zod.optin,i="optional"===n._zod.optout,o=n._zod.run({value:s[e],issues:[]},a);o instanceof Promise?c.push(o.then(n=>sr(n,t,e,s,r,i))):sr(o,t,e,s,r,i)}return i?lr(c,s,t,a,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),ur=/*@__PURE__*/De("$ZodObjectJIT",(e,t)=>{dr.init(e,t);const n=e._zod.parse,r=qe(()=>cr(t));let i;const o=tt,a=!Fe.jitless,s=a&&nt.value,c=t.catchall;let l;e._zod.parse=(d,u)=>{l??(l=r.value);const p=d.value;return o(p)?a&&s&&!1===u?.async&&!0!==u.jitless?(i||(i=(e=>{const t=new Sn(["shape","payload","ctx"]),n=r.value,i=e=>{const t=Qe(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let a=0;for(const r of n.keys)o[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=o[r],a=Qe(r),s=e[r],c="optional"===s?._zod?.optin,l="optional"===s?._zod?.optout;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):c?t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n const ${n}_present = ${a} in input;\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${a}]\n });\n }\n\n if (${n}_present) {\n if (${n}.value === undefined) {\n newResult[${a}] = undefined;\n } else {\n newResult[${a}] = ${n}.value;\n }\n }\n\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const s=t.compile();return(t,n)=>s(e,t,n)})(t.shape)),d=i(d,u),c?lr([],p,d,u,l,e):d):n(d,u):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d)}});function pr(e,t,n,r){for(const o of e)if(0===o.issues.length)return t.value=o.value,t;const i=e.filter(e=>!dt(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>mt(e,r,Ue())))}),t)}var hr=/*@__PURE__*/De("$ZodUnion",(e,t)=>{En.init(e,t),Ke(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Ke(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Ke(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Ke(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>Ge(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)a.push(t),o=!0;else{if(0===t.issues.length)return t;a.push(t)}}return o?Promise.all(a).then(t=>pr(t,r,e,i)):pr(a,r,e,i)}}),mr=/*@__PURE__*/De("$ZodIntersection",(e,t)=>{En.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,n])=>gr(e,t,n)):gr(e,i,o)}});function fr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(rt(e)&&rt(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const o of r){const n=fr(e[o],t[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};i[o]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=fr(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function gr(e,t,n){const r=/* @__PURE__ */new Map;let i;for(const s of t.issues)if("unrecognized_keys"===s.code){i??(i=s);for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(s);for(const s of n.issues)if("unrecognized_keys"===s.code)for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(s);const o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&i&&e.issues.push({...i,keys:o}),dt(e))return e;const a=fr(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var wr=/*@__PURE__*/De("$ZodRecord",(e,t)=>{En.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!rt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const o=[],a=t.keyType._zod.values;if(a){n.value={};const s=/* @__PURE__ */new Set;for(const l of a)if("string"==typeof l||"number"==typeof l||"symbol"==typeof l){s.add("number"==typeof l?l.toString():l);const a=t.keyType._zod.run({value:l,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>mt(e,r,Ue())),input:l,path:[l],inst:e});continue}const c=a.value,d=t.valueType._zod.run({value:i[l],issues:[]},r);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&n.issues.push(...pt(l,e.issues)),n.value[c]=e.value})):(d.issues.length&&n.issues.push(...pt(l,d.issues)),n.value[c]=d.value)}let c;for(const e in i)s.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{n.value={};for(const a of Reflect.ownKeys(i)){if("__proto__"===a)continue;if(!Object.prototype.propertyIsEnumerable.call(i,a))continue;let s=t.keyType._zod.run({value:a,issues:[]},r);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&nn.test(a)&&s.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(s=e)}if(s.issues.length){"loose"===t.mode?n.value[a]=i[a]:n.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>mt(e,r,Ue())),input:a,path:[a],inst:e});continue}const c=t.valueType._zod.run({value:i[a],issues:[]},r);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...pt(a,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...pt(a,c.issues)),n.value[s.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),br=/*@__PURE__*/De("$ZodEnum",(e,t)=>{En.init(e,t);const n=Be(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>ot.has(typeof e)).map(e=>"string"==typeof e?at(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),yr=/*@__PURE__*/De("$ZodLiteral",(e,t)=>{if(En.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?at(e):e?at(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),vr=/*@__PURE__*/De("$ZodTransform",(e,t)=>{En.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Ze(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new He;return n.value=i,n.fallback=!0,n}});function xr(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var kr=/*@__PURE__*/De("$ZodOptional",(e,t)=>{En.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ke(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,void 0]):void 0),Ke(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Ge(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>xr(e,r)):xr(i,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),_r=/*@__PURE__*/De("$ZodExactOptional",(e,t)=>{kr.init(e,t),Ke(e._zod,"values",()=>t.innerType._zod.values),Ke(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Sr=/*@__PURE__*/De("$ZodNullable",(e,t)=>{En.init(e,t),Ke(e._zod,"optin",()=>t.innerType._zod.optin),Ke(e._zod,"optout",()=>t.innerType._zod.optout),Ke(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Ge(e.source)}|null)$`):void 0}),Ke(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),zr=/*@__PURE__*/De("$ZodDefault",(e,t)=>{En.init(e,t),e._zod.optin="optional",Ke(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Er(e,t)):Er(r,t)}});function Er(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var Ir=/*@__PURE__*/De("$ZodPrefault",(e,t)=>{En.init(e,t),e._zod.optin="optional",Ke(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Cr=/*@__PURE__*/De("$ZodNonOptional",(e,t)=>{En.init(e,t),Ke(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Tr(t,e)):Tr(i,e)}});function Tr(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Ar=/*@__PURE__*/De("$ZodCatch",(e,t)=>{En.init(e,t),e._zod.optin="optional",Ke(e._zod,"optout",()=>t.innerType._zod.optout),Ke(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>mt(e,n,Ue()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>mt(e,n,Ue()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),$r=/*@__PURE__*/De("$ZodPipe",(e,t)=>{En.init(e,t),Ke(e._zod,"values",()=>t.in._zod.values),Ke(e._zod,"optin",()=>t.in._zod.optin),Ke(e._zod,"optout",()=>t.out._zod.optout),Ke(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Mr(e,t.in,n)):Mr(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Mr(e,t.out,n)):Mr(r,t.out,n)}});function Mr(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Nr=/*@__PURE__*/De("$ZodReadonly",(e,t)=>{En.init(e,t),Ke(e._zod,"propValues",()=>t.innerType._zod.propValues),Ke(e._zod,"values",()=>t.innerType._zod.values),Ke(e._zod,"optin",()=>t.innerType?._zod?.optin),Ke(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Or):Or(r)}});function Or(e){return e.value=Object.freeze(e.value),e}var Pr,Rr=/*@__PURE__*/De("$ZodCustom",(e,t)=>{sn.init(e,t),En.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Lr(t,n,r,e));Lr(i,n,r,e)}});function Lr(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(gt(e))}}var jr=class{constructor(){this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};(Pr=globalThis).__zod_globalRegistry??(Pr.__zod_globalRegistry=new jr);var Dr=globalThis.__zod_globalRegistry;function Hr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ct(t)})}function Zr(e,t){return new ln({check:"less_than",...ct(t),value:e,inclusive:!1})}function Fr(e,t){return new ln({check:"less_than",...ct(t),value:e,inclusive:!0})}function Ur(e,t){return new dn({check:"greater_than",...ct(t),value:e,inclusive:!1})}function Br(e,t){return new dn({check:"greater_than",...ct(t),value:e,inclusive:!0})}function Wr(e,t){return new un({check:"multiple_of",...ct(t),value:e})}function qr(e,t){return new hn({check:"max_length",...ct(t),maximum:e})}function Vr(e,t){return new mn({check:"min_length",...ct(t),minimum:e})}function Gr(e,t){return new fn({check:"length_equals",...ct(t),length:e})}function Jr(e){return new _n({check:"overwrite",tx:e})}function Kr(e,t){const n=new sn({check:"custom",...ct(t)});return n._zod.check=e,n}function Yr(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Dr,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:/* @__PURE__ */new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Xr(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,o=t.processors[i.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(e,t,n,r)}const o=e._zod.parent;o&&(a.ref||(a.ref=o),Xr(o,t,r),t.seen.get(o).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),"input"===t.io&&ti(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&"_prefault"in a.schema&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Qr(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=/* @__PURE__ */new Map;for(const o of e.seen.entries()){const t=e.metadataRegistry.get(o[0])?.id;if(t){const e=r.get(t);if(e&&e!==o[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,o[0])}}const i=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:i,defId:o}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${i("__shared")}#/${r}/${o}`}}if(t[1]===n)return{ref:"#"};const i=`#/${r}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:i+o}})(t);r.def={...r.schema},o&&(r.defId=o);const a=r.schema;for(const e in a)delete a[e];a.$ref=i};if("throw"===e.cycles)for(const o of e.seen.entries()){const e=o[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const n=o[1];if(t!==o[0]){if(e.external){const n=e.external.registry.get(o[0])?.id;if(t!==o[0]&&n){i(o);continue}}(e.metadataRegistry.get(o[0])?.id||n.cycle||n.count>1&&"ref"===e.reused)&&i(o)}else i(o)}}function ei(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const i=n.def??n.schema,o={...i},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),s=n.schema;if(!s.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(i,s):(i.allOf=i.allOf??[],i.allOf.push(s)),Object.assign(i,o),t._zod.parent===a)for(const e in i)"$ref"!==e&&"allOf"!==e&&(e in o||delete i[e]);if(s.$ref&&n.def)for(const e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}const s=t._zod.parent;if(s&&s!==a){r(s);const t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(const e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(const c of[...e.seen.entries()].reverse())r(c[0]);const i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);const o=e.metadataRegistry.get(t)?.id;void 0!==o&&i.id===o&&delete i.id;const a=e.external?.defs??{};for(const c of e.seen.entries()){const e=c[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&("draft-2020-12"===e.target?i.$defs=a:i.definitions=a);try{const n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:ni(t,"input",e.processors),output:ni(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(s){throw new Error("Error converting schema to JSON.")}}function ti(e,t){const n=t??{seen:/* @__PURE__ */new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return ti(r.element,n);if("set"===r.type)return ti(r.valueType,n);if("lazy"===r.type)return ti(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return ti(r.innerType,n);if("intersection"===r.type)return ti(r.left,n)||ti(r.right,n);if("record"===r.type||"map"===r.type)return ti(r.keyType,n)||ti(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(ti(r.in,n)||ti(r.out,n));if("object"===r.type){for(const e in r.shape)if(ti(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(ti(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(ti(e,n))return!0;return!(!r.rest||!ti(r.rest,n))}return!1}var ni=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},a=Yr({...i??{},target:o,io:t,processors:n});return Xr(e,a),Qr(a,e),ei(a,e)},ri={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ii=(e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r);t.seen.get(e).ref=i.innerType},oi=/*@__PURE__*/De("ZodISODateTime",(e,t)=>{Hn.init(e,t),Ni.init(e,t)});function ai(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ct(t)})}(oi,e)}var si=/*@__PURE__*/De("ZodISODate",(e,t)=>{Zn.init(e,t),Ni.init(e,t)});function ci(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...ct(t)})}(si,e)}var li=/*@__PURE__*/De("ZodISOTime",(e,t)=>{Fn.init(e,t),Ni.init(e,t)});function di(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ct(t)})}(li,e)}var ui=/*@__PURE__*/De("ZodISODuration",(e,t)=>{Un.init(e,t),Ni.init(e,t)});function pi(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...ct(t)})}(ui,e)}var hi=(e,t)=>{bt.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,i=[])=>{for(const o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>r({issues:e},[...i,...o.path]));else if("invalid_key"===o.code)r({issues:o.issues},[...i,...o.path]);else if("invalid_element"===o.code)r({issues:o.issues},[...i,...o.path]);else{const e=[...i,...o.path];if(0===e.length)n._errors.push(t(o));else{let r=n,i=0;for(;i<e.length;){const n=e[i];i!==e.length-1?r[n]=r[n]||{_errors:[]}:(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(o))),r=r[n],i++}}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,We,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,We,2)}},isEmpty:{get:()=>0===e.issues.length}})},mi=/*@__PURE__*/De("ZodError",hi,{Parent:Error}),fi=/* @__PURE__ */vt(mi),gi=/* @__PURE__ */xt(mi),wi=/* @__PURE__ */kt(mi),bi=/* @__PURE__ */St(mi),yi=/* @__PURE__ */Et(mi),vi=/* @__PURE__ */It(mi),xi=/* @__PURE__ */Ct(mi),ki=/* @__PURE__ */Tt(mi),_i=/* @__PURE__ */At(mi),Si=/* @__PURE__ */$t(mi),zi=/* @__PURE__ */Mt(mi),Ei=/* @__PURE__ */Nt(mi),Ii=/* @__PURE__ */new WeakMap;function Ci(e,t,n){const r=Object.getPrototypeOf(e);let i=Ii.get(r);if(i||(i=/* @__PURE__ */new Set,Ii.set(r,i)),!i.has(t)){i.add(t);for(const e in n){const t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){const n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Ti=/*@__PURE__*/De("ZodType",(e,t)=>(En.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ni(e,"input"),output:ni(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Yr({...n,processors:t});return Xr(e,r),Qr(r,e),ei(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>fi(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>wi(e,t,n),e.parseAsync=async(t,n)=>gi(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>bi(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>yi(e,t,n),e.decode=(t,n)=>vi(e,t,n),e.encodeAsync=async(t,n)=>xi(e,t,n),e.decodeAsync=async(t,n)=>ki(e,t,n),e.safeEncode=(t,n)=>_i(e,t,n),e.safeDecode=(t,n)=>Si(e,t,n),e.safeEncodeAsync=async(t,n)=>zi(e,t,n),e.safeDecodeAsync=async(t,n)=>Ei(e,t,n),Ci(e,"ZodType",{check(...e){const t=this.def;return this.clone(Xe(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return st(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...ct(n)})}(Po,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return function(e,t){const n=/* @__PURE__ */Kr(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(gt(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(gt(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(Jr(e))},optional(){return So(this)},exactOptional(){return new zo({type:"optional",innerType:this})},nullable(){return Io(this)},nullish(){return So(Io(this))},nonoptional(e){return function(e,t){return new Ao({type:"nonoptional",innerType:e,...ct(t)})}(this,e)},array(){return po(this)},or(e){return new fo({type:"union",options:[this,e],...ct(t)});var t},and(e){return new go({type:"intersection",left:this,right:e})},transform(e){return No(this,new ko({type:"transform",transform:e}))},default(e){return t=e,new Co({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():it(t)}});var t},prefault(e){return t=e,new To({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():it(t)}});var t},catch(e){return new $o({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return No(this,e)},readonly(){return new Oo({type:"readonly",innerType:this})},describe(e){const t=this.clone();return Dr.add(t,{description:e}),t},meta(...e){if(0===e.length)return Dr.get(this);const t=this.clone();return Dr.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>Dr.get(e)?.description,configurable:!0}),e)),Ai=/*@__PURE__*/De("_ZodString",(e,t)=>{In.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:i,maximum:o,format:a,patterns:s,contentEncoding:c}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),a&&(r.format=ri[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),c&&(r.contentEncoding=c),s&&s.size>0){const e=[...s];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ci(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new wn({check:"string_format",format:"regex",...ct(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new vn({check:"string_format",format:"includes",...ct(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new xn({check:"string_format",format:"starts_with",...ct(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new kn({check:"string_format",format:"ends_with",...ct(t),suffix:e})}(...e))},min(...e){return this.check(Vr(...e))},max(...e){return this.check(qr(...e))},length(...e){return this.check(Gr(...e))},nonempty(...e){return this.check(Vr(1,...e))},lowercase(e){return this.check(function(e){return new bn({check:"string_format",format:"lowercase",...ct(e)})}(e))},uppercase(e){return this.check(function(e){return new yn({check:"string_format",format:"uppercase",...ct(e)})}(e))},trim(){return this.check(/* @__PURE__ */Jr(e=>e.trim()))},normalize(...e){return this.check(function(e){/* @__PURE__ */
|
|
2
|
-
return Jr(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(/* @__PURE__ */Jr(e=>e.toLowerCase()))},toUpperCase(){return this.check(/* @__PURE__ */Jr(e=>e.toUpperCase()))},slugify(){return this.check(/* @__PURE__ */Jr(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),$i=/*@__PURE__*/De("ZodString",(e,t)=>{In.init(e,t),Ai.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ct(t)})}(Oi,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ct(t)})}(Li,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ct(t)})}(Xi,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ct(t)})}(ji,t)),e.guid=t=>e.check(Hr(Pi,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ct(t)})}(Ri,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ct(t)})}(Ri,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ct(t)})}(Ri,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ct(t)})}(Ri,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ct(t)})}(Di,t)),e.guid=t=>e.check(Hr(Pi,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ct(t)})}(Hi,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ct(t)})}(Zi,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ct(t)})}(Fi,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ct(t)})}(Ji,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ct(t)})}(Ki,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ct(t)})}(Ui,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ct(t)})}(Bi,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ct(t)})}(Wi,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ct(t)})}(qi,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ct(t)})}(Vi,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ct(t)})}(Gi,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ct(t)})}(Yi,t)),e.datetime=t=>e.check(ai(t)),e.date=t=>e.check(ci(t)),e.time=t=>e.check(di(t)),e.duration=t=>e.check(pi(t))});function Mi(e){return function(e,t){return new e({type:"string",...ct(t)})}($i,e)}var Ni=/*@__PURE__*/De("ZodStringFormat",(e,t)=>{Cn.init(e,t),Ai.init(e,t)}),Oi=/*@__PURE__*/De("ZodEmail",(e,t)=>{$n.init(e,t),Ni.init(e,t)}),Pi=/*@__PURE__*/De("ZodGUID",(e,t)=>{Tn.init(e,t),Ni.init(e,t)}),Ri=/*@__PURE__*/De("ZodUUID",(e,t)=>{An.init(e,t),Ni.init(e,t)}),Li=/*@__PURE__*/De("ZodURL",(e,t)=>{Mn.init(e,t),Ni.init(e,t)}),ji=/*@__PURE__*/De("ZodEmoji",(e,t)=>{Nn.init(e,t),Ni.init(e,t)}),Di=/*@__PURE__*/De("ZodNanoID",(e,t)=>{On.init(e,t),Ni.init(e,t)}),Hi=/*@__PURE__*/De("ZodCUID",(e,t)=>{Pn.init(e,t),Ni.init(e,t)}),Zi=/*@__PURE__*/De("ZodCUID2",(e,t)=>{Rn.init(e,t),Ni.init(e,t)}),Fi=/*@__PURE__*/De("ZodULID",(e,t)=>{Ln.init(e,t),Ni.init(e,t)}),Ui=/*@__PURE__*/De("ZodXID",(e,t)=>{jn.init(e,t),Ni.init(e,t)}),Bi=/*@__PURE__*/De("ZodKSUID",(e,t)=>{Dn.init(e,t),Ni.init(e,t)}),Wi=/*@__PURE__*/De("ZodIPv4",(e,t)=>{Bn.init(e,t),Ni.init(e,t)}),qi=/*@__PURE__*/De("ZodIPv6",(e,t)=>{Wn.init(e,t),Ni.init(e,t)}),Vi=/*@__PURE__*/De("ZodCIDRv4",(e,t)=>{qn.init(e,t),Ni.init(e,t)}),Gi=/*@__PURE__*/De("ZodCIDRv6",(e,t)=>{Vn.init(e,t),Ni.init(e,t)}),Ji=/*@__PURE__*/De("ZodBase64",(e,t)=>{Jn.init(e,t),Ni.init(e,t)}),Ki=/*@__PURE__*/De("ZodBase64URL",(e,t)=>{Kn.init(e,t),Ni.init(e,t)}),Yi=/*@__PURE__*/De("ZodE164",(e,t)=>{Yn.init(e,t),Ni.init(e,t)}),Xi=/*@__PURE__*/De("ZodJWT",(e,t)=>{Xn.init(e,t),Ni.init(e,t)}),Qi=/*@__PURE__*/De("ZodNumber",(e,t)=>{Qn.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:i,maximum:o,format:a,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number";const d="number"==typeof l&&l>=(i??Number.NEGATIVE_INFINITY),u="number"==typeof c&&c<=(o??Number.POSITIVE_INFINITY),p="draft-04"===t.target||"openapi-3.0"===t.target;d?p?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof i&&(r.minimum=i),u?p?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c:"number"==typeof o&&(r.maximum=o),"number"==typeof s&&(r.multipleOf=s)})(e,t,n),Ci(e,"ZodNumber",{gt(e,t){return this.check(Ur(e,t))},gte(e,t){return this.check(Br(e,t))},min(e,t){return this.check(Br(e,t))},lt(e,t){return this.check(Zr(e,t))},lte(e,t){return this.check(Fr(e,t))},max(e,t){return this.check(Fr(e,t))},int(e){return this.check(no(e))},safe(e){return this.check(no(e))},positive(e){return this.check(Ur(0,e))},nonnegative(e){return this.check(Br(0,e))},negative(e){return this.check(Zr(0,e))},nonpositive(e){return this.check(Fr(0,e))},multipleOf(e,t){return this.check(Wr(e,t))},step(e,t){return this.check(Wr(e,t))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function eo(e){return function(e,t){return new e({type:"number",checks:[],...ct(t)})}(Qi,e)}var to=/*@__PURE__*/De("ZodNumberFormat",(e,t)=>{er.init(e,t),Qi.init(e,t)});function no(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ct(t)})}(to,e)}var ro=/*@__PURE__*/De("ZodBoolean",(e,t)=>{tr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function io(e){return function(e,t){return new e({type:"boolean",...ct(t)})}(ro,e)}var oo=/*@__PURE__*/De("ZodUnknown",(e,t)=>{nr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function ao(){return new oo({type:"unknown"})}var so=/*@__PURE__*/De("ZodNever",(e,t)=>{rr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function co(e){return function(e,t){return new e({type:"never",...ct(t)})}(so,e)}var lo=/*@__PURE__*/De("ZodDate",(e,t)=>{ir.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")})(0,e),e.min=(t,n)=>e.check(Br(t,n)),e.max=(t,n)=>e.check(Fr(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null}),uo=/*@__PURE__*/De("ZodArray",(e,t)=>{ar.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;"number"==typeof a&&(i.minItems=a),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=Xr(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,Ci(e,"ZodArray",{min(e,t){return this.check(Vr(e,t))},nonempty(e){return this.check(Vr(1,e))},max(e,t){return this.check(qr(e,t))},length(e,t){return this.check(Gr(e,t))},unwrap(){return this.element}})});function po(e,t){return function(e,t,n){return new e({type:"array",element:t,...ct(n)})}(uo,e,t)}var ho=/*@__PURE__*/De("ZodObject",(e,t)=>{ur.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const a=o.shape;for(const l in a)i.properties[l]=Xr(a[l],t,{...r,path:[...r.path,"properties",l]});const s=new Set(Object.keys(a)),c=new Set([...s].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(i.required=Array.from(c)),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Xr(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),Ke(e,"shape",()=>t.shape),Ci(e,"ZodObject",{keyof(){return vo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:ao()})},loose(){return this.clone({...this._zod.def,catchall:ao()})},strict(){return this.clone({...this._zod.def,catchall:co()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!rt(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return st(e,Xe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ye(this,"shape",n),n}}))}(this,e)},safeExtend(e){return function(e,t){if(!rt(t))throw new Error("Invalid input to safeExtend: expected a plain object");return st(e,Xe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ye(this,"shape",n),n}}))}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return st(e,Xe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Ye(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return st(e,Xe(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Ye(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return st(e,Xe(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Ye(this,"shape",r),r},checks:[]}))}(this,e)},partial(...e){return function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return st(t,Xe(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Ye(this,"shape",i),i},checks:[]}))}(_o,this,e[0])},required(...e){return t=Ao,n=this,r=e[0],st(n,Xe(n._zod.def,{get shape(){const e=n._zod.def.shape,i={...e};if(r)for(const n in r){if(!(n in i))throw new Error(`Unrecognized key: "${n}"`);r[n]&&(i[n]=new t({type:"nonoptional",innerType:e[n]}))}else for(const n in e)i[n]=new t({type:"nonoptional",innerType:e[n]});return Ye(this,"shape",i),i}}));var t,n,r}})});function mo(e,t){return new ho({type:"object",shape:e??{},...ct(t)})}var fo=/*@__PURE__*/De("ZodUnion",(e,t)=>{hr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=!1===i.inclusive,a=i.options.map((e,n)=>Xr(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options});var go=/*@__PURE__*/De("ZodIntersection",(e,t)=>{mr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Xr(i.left,t,{...r,path:[...r.path,"allOf",0]}),a=Xr(i.right,t,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length;n.allOf=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]]})(e,t,n,r)});var wo=/*@__PURE__*/De("ZodRecord",(e,t)=>{wr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const a=o.keyType,s=a._zod.bag?.patterns;if("loose"===o.mode&&s&&s.size>0){const e=Xr(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of s)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=Xr(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Xr(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=a._zod.values;if(c){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function bo(e,t,n){return t&&t._zod?new wo({type:"record",keyType:e,valueType:t,...ct(n)}):new wo({type:"record",keyType:Mi(),valueType:e,...ct(t)})}var yo=/*@__PURE__*/De("ZodEnum",(e,t)=>{br.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Be(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const o of e){if(!n.has(o))throw new Error(`Key ${o} not found in enum`);i[o]=t.entries[o]}return new yo({...t,checks:[],...ct(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new yo({...t,checks:[],...ct(r),entries:i})}});function vo(e,t){return new yo({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...ct(t)})}var xo=/*@__PURE__*/De("ZodLiteral",(e,t)=>{yr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(void 0===o){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof o){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});var ko=/*@__PURE__*/De("ZodTransform",(e,t)=>{vr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Ze(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(gt(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(gt(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});var _o=/*@__PURE__*/De("ZodOptional",(e,t)=>{kr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ii(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function So(e){return new _o({type:"optional",innerType:e})}var zo=/*@__PURE__*/De("ZodExactOptional",(e,t)=>{_r.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ii(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Eo=/*@__PURE__*/De("ZodNullable",(e,t)=>{Sr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Xr(i.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Eo({type:"nullable",innerType:e})}var Co=/*@__PURE__*/De("ZodDefault",(e,t)=>{zr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var To=/*@__PURE__*/De("ZodPrefault",(e,t)=>{Ir.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Ao=/*@__PURE__*/De("ZodNonOptional",(e,t)=>{Cr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var $o=/*@__PURE__*/De("ZodCatch",(e,t)=>{Ar.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let o;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var Mo=/*@__PURE__*/De("ZodPipe",(e,t)=>{$r.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),a="input"===t.io?o?i.out:i.in:i.out;Xr(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function No(e,t){return new Mo({type:"pipe",in:e,out:t})}var Oo=/*@__PURE__*/De("ZodReadonly",(e,t)=>{Nr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Po=/*@__PURE__*/De("ZodCustom",(e,t)=>{Rr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});function Ro(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...ct(t)})}(Qi,e)}function Lo(e){return function(e,t){return new e({type:"date",coerce:!0,...ct(t)})}(lo,e)}var jo,Do=vo(["created","active","suspended","pending_approval"]),Ho=mo({id:eo().optional(),created_at:Lo().optional(),updated_at:Lo().optional()}),Zo=(mo({id:Ro()}),mo({slug:Mi()}),mo({widget_id:Ro()}),mo({simulation_id:Ro()}),mo({application_id:Ro()}),mo({user_id:Ro()}),mo({limit:Ro().optional().default(50),offset:Ro().optional().default(0)}),mo({success:function(e,t){return new xo({type:"literal",values:Array.isArray(e)?e:[e],...ct(t)})}(!0)})),Fo=(Zo.extend({message:Mi()}),mo({name:Mi().min(1),params:bo(Mi(),ao()).default({}),result:bo(Mi(),ao()).default({})}),Mi().url().refine(e=>/^https:\/\/hooks\.slack\.com\//.test(e),{message:"Slack webhook URL must start with https://hooks.slack.com/"}),mo({start:Mi(),end:Mi(),action:Mi()}).passthrough()),Uo=mo({id:Mi(),label:Mi(),purpose:Mi(),elements:po(bo(Mi(),ao())).default([]),bbox:bo(Mi(),ao()).default({}),screenshot:Mi().default(""),embedding:po(eo()).nullish()}).passthrough(),Bo=mo({id:Mi(),title:Mi(),url:Mi(),summary:Mi().default(""),screenshot:Mi().default(""),sections:po(Uo).default([]),sequence_ids:po(eo()).default([]),embedding:po(eo()).nullish()}).passthrough(),Wo=(mo({nodes:po(Bo),edges:po(Fo)}),vo(["free","startup","growth","enterprise"])),qo=vo(["document","video"]),Vo=vo(["user","research"]),Go=vo(["queued","running","creating_knowledge","has_question","completed","failed","stopped"]),Jo=vo(["pending","generating","completed","failed"]),Ko=vo(["app","website"]),Yo=vo(["widget"]),Xo=(vo(["tell","show","do"]),vo(["password","oauth"])),Qo=(Ho.extend({is_super:io(),status:Do,email:Mi().email(),external_id:Mi().nullish(),first_name:Mi().nullish(),last_name:Mi().nullish(),password:Mi().nullish(),image_url:Mi().nullish(),last_login_at:Lo().nullish(),auth_method:Xo.nullish()}),Ho.extend({name:Mi(),slug:Mi(),status:Do,package:Wo,ending_date:Lo().nullish(),external_workspace_id:Mi().nullish(),slack_webhook_configured:io().optional(),notify_all_members_on_question:io().optional()}),Ho.extend({workspace_id:eo(),application_id:eo().optional(),file_name:Mi().min(1),file_size:Ro(),file_type:qo,file_url:Mi(),source_url:Mi().nullish(),source:Vo.default("user").optional()}),vo(["desktop","tablet","mobile"])),ea=vo(["positive","neutral","negative"]),ta=mo({step_index:eo(),screenshot_ref:Mi().nullable(),reaction:Mi(),sentiment:ea}),na=mo({id:eo(),run_id:eo().nullable(),persona_id:eo().nullable(),user_index:eo().nullable(),simulation_id:eo().nullable(),study_variant_id:eo().nullable(),journey_reaction:Mi().nullable(),journey_sentiment:ea.nullable(),status:vo(["pending","completed","failed"]),step_reactions:po(ta).default([]),question_answers:po(mo({study_question_id:eo(),answer:Mi()})).default([])}),ra=(Ho.extend({application_id:eo(),job_id:Mi(),browser_session_id:Mi().nullish(),status:Go,status_message:Mi(),path:Mi().nullish(),instructions:Mi(),name:Mi().nullish(),type:vo(["direct","uxr","survey","abtest","qa"]),pinned:io().optional(),source:vo(["direct","qa"]).optional(),graph_id:Mi().nullish(),source_metadata:bo(Mi(),ao()).nullish(),step_count:eo().int().nonnegative().nullish(),started_at:Lo().nullish(),completed_at:Lo().nullish(),graph_status:Jo.optional(),graph_steps_processed:eo().int().nonnegative().optional(),graph_steps_total:eo().int().nonnegative().optional(),graph_error:Mi().nullish(),created_by_user_id:eo().nullish(),has_question:io().optional(),participants:po(mo({persona_id:eo(),user_count:eo().int().positive()})).default([]),reactions:po(na).default([]),driver_persona_id:eo().nullable().default(null),viewport:Qo.default("desktop")}),Ho.extend({workspace_id:eo(),name:Mi(),slug:Mi(),type:Ko,url:Mi(),username:Mi().nullish(),password:Mi().nullish(),allowed_domains:po(Mi()).default([])}).omit({password:!0}),mo({chip_mode:vo(["show","tell","do"]),chip_text:Mi()})),ia=mo({widget_enabled:io(),widget_appearance:vo(["default","compact","full"]),widget_position:vo(["bottom_left","bottom_right","top_left","top_right"]),widget_device:vo(["desktop","mobile","desktop_mobile"]),widget_header:Mi(),widget_body:Mi(),widget_greeting:Mi(),widget_feature_tell:io(),widget_feature_show:io(),widget_feature_do:io(),widget_feature_human:io(),widget_background_color:Mi(),widget_text_color:Mi(),widget_border_color:Mi(),widget_accent_color:Mi(),widget_secondary_color:Mi(),widget_border_radius:Mi(),widget_font_size:Mi(),widget_width:Mi(),widget_height:Mi(),widget_shadow:Mi(),widget_animation_duration:Mi(),widget_fade_duration:Mi(),widget_bounce_effect:io(),widget_chips:po(ra)}),oa=(Ho.extend({application_id:eo(),type:Yo,settings:ia,status:Do,marketrix_id:Mi(),marketrix_key:Mi(),snippet:Mi().nullish()}),Ho.extend({widget_id:eo(),url_pattern:Mi(),message:po(Mi()),description:Mi().optional()}),vo(["running","finalizing","completed","failed","stopped"]),vo(["passed","failed","indecisive"]),vo(["passed","failed"]),vo(["user_login","url_visit","update_workspace","create_user","update_user","delete_user","create_application","update_application","delete_application","create_widget","update_widget","delete_widget","create_knowledge","update_knowledge","delete_knowledge","approve_user","deny_user","request_workspace","widget_question","qa_run_started","start_simulation","create_workflow","update_workflow","delete_workflow","toggle_workflow","slack_command"])),aa=mo({details:Mi().optional(),id:eo().optional(),type:Mi().optional(),name:Mi().optional(),target_user_id:eo().optional(),target_user_email:Mi().optional(),reason:Mi().optional(),assigned_role:Mi().optional(),new_role:Mi().optional(),previous_role:Mi().optional(),workspace_name:Mi().optional(),workspace_slug:Mi().optional(),ip_address:Mi().optional(),user_agent:Mi().optional(),widget_type:Mi().optional(),created_by:eo().optional()}).passthrough(),sa=(Ho.extend({workspace_id:eo(),user_id:eo().nullable(),type:oa,metadata:aa.optional()}).partial().extend({type:oa}),null),ca="";function la(e){return ge(new je({url:e,headers:()=>{const e={};return sa&&(e.Authorization=`Bearer ${sa}`),e}}))}jo=la("");var da=e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==ca&&(ca=e,jo=la(e))},ua={setAuthToken:e=>{sa=e},clearAuthToken:()=>{sa=null},getAuthToken:()=>sa,configure:da},pa=new Proxy({},{get:(e,t)=>t in ua?ua[t]:jo[t]}),ha="undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname&&!window.location.hostname.includes("localhost")?"error":"debug",ma={debug:0,info:1,warn:2,error:3};function fa(e){return ma[e]>=ma[ha]}var ga=[{id:"navigate",name:"Navigate",description:"Navigate to a URL",displayAction:"Navigating",category:"navigation",actionType:"navigate"},{id:"search",name:"Search",description:"Search the web using a search engine",displayAction:"Searching",category:"navigation",actionType:"search"},{id:"click_element",name:"Click Element",description:"Click on an element by index or coordinates",displayAction:"Clicking element",category:"interaction",actionType:"click_element"},{id:"type_text",name:"Type Text",description:"Type text into an input field",displayAction:"Typing text",category:"interaction",actionType:"type_text"},{id:"scroll",name:"Scroll",description:"Scroll the page up or down",displayAction:"Scrolling",category:"interaction",actionType:"scroll"},{id:"scroll_to_text",name:"Scroll to Text",description:"Scroll until text is visible",displayAction:"Scrolling to text",category:"interaction",actionType:"scroll_to_text"},{id:"send_keys",name:"Send Keys",description:"Send keyboard keys or shortcuts",displayAction:"Pressing key",category:"interaction",actionType:"send_keys"},{id:"extract",name:"Extract",description:"Extract content from the page",displayAction:"Extracting content",category:"extraction",actionType:"extract"},{id:"get_dropdown_options",name:"Get Dropdown Options",description:"Get available options from a dropdown",displayAction:"Reading dropdown options",category:"extraction",actionType:"get_dropdown_options"},{id:"select_dropdown_option",name:"Select Dropdown Option",description:"Select an option from a dropdown",displayAction:"Selecting option",category:"interaction",actionType:"select_dropdown_option"},{id:"upload_file",name:"Upload File",description:"Upload a file to an input field",displayAction:"Uploading file",category:"interaction",actionType:"upload_file"},{id:"go_back",name:"Go Back",description:"Browser back button",displayAction:"Going back",category:"navigation",actionType:"go_back"},{id:"wait",name:"Wait",description:"Wait for a specified duration",displayAction:"Waiting",category:"utility",actionType:"wait"},{id:"switch_tab",name:"Switch Tab",description:"Switch to a different browser tab",displayAction:"Switching tab",category:"utility",actionType:"switch_tab"},{id:"close_tab",name:"Close Tab",description:"Close the current browser tab",displayAction:"Closing tab",category:"utility",actionType:"close_tab"},{id:"done",name:"Done",description:"Mark task as complete",displayAction:"Done",category:"utility",actionType:"done"},{id:"get_html",name:"Get HTML",description:"Get full page HTML with data-id attributes",displayAction:"Viewed your screen",category:"extraction",actionType:"get_html"},{id:"get_interactable_elements",name:"Get Interactable Elements",description:"Get list of interactable elements",displayAction:"Scanning elements",category:"extraction",actionType:"get_interactable_elements"},{id:"get_screenshot",name:"Get Screenshot",description:"Capture a screenshot of the page",displayAction:"Taking screenshot",category:"extraction",actionType:"get_screenshot"}];function wa(e){return e.includes("__THINKING__")}function ba(e){return wa(e)?e:`${e}\n\n__THINKING__`}function ya(e,t,n,r,i){if("agent"!==e.sender||e.isSystemMessage||e.isScreenAccessRequest)return!1;if(i&&t&&("show"===n||"do"===n))if(e.isPlaceholder){if(void 0!==e.mode&&e.mode!==n)return!1}else if(e.mode!==n)return!1;if(r){const t=e.content.trim().length>0,n=e.parts&&e.parts.length>0;if(!t&&!n)return!1}return!0}function va(e){const{messages:t,isSimulationRunning:n,currentMode:r,requireContent:i}=e;let o=-1;if(n&&("show"===r||"do"===r)){const e=!0;for(let a=t.length-1;a>=0;a--){const s=t[a],c=ya(s,n,r,i,e),l=s.isPlaceholder,d=!i||s.content.trim().length>0||s.parts&&s.parts.length>0;if(c&&l&&d){o=a;break}}if(o<0&&!i)for(let a=t.length-1;a>=0;a--){const s=t[a],c=ya(s,n,r,i,e),l=s.isPlaceholder;if(c&&l){o=a;break}}if(o<0)for(let a=t.length-1;a>=0;a--){const s=t[a],c=ya(s,n,r,i,e),l=s.isPlaceholder;if(c&&!l){o=a;break}}}if(o<0){for(let e=t.length-1;e>=0;e--){const n=t[e],r="agent"===n.sender,a=n.isPlaceholder,s=!n.isSystemMessage,c=!n.isScreenAccessRequest,l=!i||n.content.trim().length>0||n.parts&&n.parts.length>0;if(r&&a&&s&&c&&l){o=e;break}}if(o<0&&!i)for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&n.isPlaceholder&&!n.isSystemMessage&&!n.isScreenAccessRequest){o=e;break}}if(o<0&&(o=function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("agent"===n.sender&&!n.isSystemMessage&&!n.isScreenAccessRequest&&!n.isPlaceholder)return t}return-1}(t)),o<0)for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&!n.isSystemMessage&&!n.isScreenAccessRequest){o=e;break}}}return o>=0?{index:o,message:t[o]}:null}function xa(e){const t={...e};if(!t.parts){t.parts=[];const e=t.content.replace(/\n\n__THINKING__$/,"").trim();e&&t.parts.push({type:"text",content:e})}return t}var ka=/* @__PURE__ */new Set(["click_element","type_text","send_keys","select_dropdown_option","upload_file","scroll"]),_a=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys","upload_file"]);function Sa(e){return e?e.replace(/\(Cancelled by cleanup\)/gi,"").replace(/\(cancelled by cleanup\)/gi,"").replace(/Cancelled by cleanup/gi,"").replace(/\s+/g," ").trim():e}function za(e,t,n,r=!1){const i=xa(e);if(!t||"show"!==n&&"do"!==n)return wa(i.content)?{...i,content:i.content.replace(/\n\n__THINKING__$/,"").replace(/__THINKING__/g,""),placeholderState:void 0}:i;const o=r?"waiting-for-user":"thinking";return wa(i.content)?i.placeholderState!==o?{...i,placeholderState:o}:i:{...i,content:ba(i.content),placeholderState:o}}var Ea=Object.fromEntries(ga.map(e=>[e.id,e.displayAction]));var Ia="marketrix_chat_context",Ca={chat_id:null,messages:[],isSimulationRunning:!1,activeSimulationId:null,currentMode:"tell",isOpen:!1,isMinimized:!1,isLoading:!1,config:null,timestamp:Date.now()},Ta=class e{static instance;context=null;constructor(){this.loadContext()}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadContext(){if("undefined"==typeof window)return this.context={...Ca},this.context;try{const e=localStorage.getItem(Ia);if(e){const t=JSON.parse(e);return Date.now()-t.timestamp>6048e5?(this.context={...Ca},this.saveContext(),this.context):(this.context=t,this.context)}}catch(e){}return this.context={...Ca},this.context}saveContext(){if("undefined"!=typeof window&&this.context)try{this.context.timestamp=Date.now(),localStorage.setItem(Ia,JSON.stringify(this.context))}catch(e){}}getContext(){return this.context?this.context:this.loadContext()}updateContext(e){this.context||this.loadContext();const t=this.context;this.context={...t,...e},this.saveContext()}isValidChatId(e){return"string"==typeof e&&""!==e.trim()}getChatId(){if("undefined"!=typeof window&&this.isValidChatId(window.name)){const e=window.name;return e!==this.getContext().chat_id&&this.updateContext({chat_id:e}),e}return this.getContext().chat_id}setChatId(e){this.updateContext({chat_id:e}),"undefined"!=typeof window&&e&&(window.name=e,window.dispatchEvent(new CustomEvent("marketrix:chatid",{detail:{chatId:e}})))}getMessages(){return this.getContext().messages}setMessages(e){this.updateContext({messages:e})}getChatState(){const e=this.getContext();return{isSimulationRunning:e.isSimulationRunning,activeSimulationId:e.activeSimulationId,currentMode:e.currentMode,isOpen:e.isOpen,isMinimized:e.isMinimized,isLoading:e.isLoading}}setChatState(e){this.updateContext(e)}getConfig(){return this.getContext().config}setConfig(e){this.updateContext({config:e})}clear(){this.context={...Ca},"undefined"!=typeof window&&localStorage.removeItem(Ia)}hasValidContext(){const e=this.getContext();return null!==e.chat_id&&e.chat_id.length>0}}.getInstance(),Aa=class e{static instance;chatId=null;initError=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.chatId=e}createInitialContext(e){try{if(Ta.hasValidContext())return;Ta.updateContext({chat_id:e,messages:[],isSimulationRunning:!1,activeSimulationId:null,currentMode:"tell",isOpen:!1,isMinimized:!1,isLoading:!1})}catch(t){this.initError=t instanceof Error?t:new Error(String(t))}}getInitError(){return this.initError}restore(){const e=Ta.getContext();return{messages:e.chat_id?e.messages.map(e=>{if(e.id.startsWith("screenshare-"))return{...e,content:"Screenshare ended",videoStream:void 0,isSystemMessage:!0,timestamp:new Date(e.timestamp),parts:[{type:"text",content:"Screenshare ended"}]};const t={...e,timestamp:new Date(e.timestamp),videoStream:void 0,placeholderState:e.placeholderState,simulationStatus:e.simulationStatus,parts:e.parts||[]};if(0===t.parts?.length&&t.content){const e=t.content.replace(/\n\n__THINKING__$/,"").trim();e&&t.parts&&t.parts.push({type:"text",content:e})}return t}):[],isSimulationRunning:e.isSimulationRunning,activeSimulationId:e.activeSimulationId,currentMode:e.currentMode,isOpen:e.isOpen,isMinimized:e.isMinimized,isLoading:e.isLoading??!1}}persist(e){if(this.chatId)try{const t=e.messages.filter(e=>!e.isPlaceholder||("thinking"===e.placeholderState||"waiting-for-user"===e.placeholderState||(e.parts||[]).length>0)).filter(e=>!(e.isSystemMessage&&"Chat context changed"===e.content)).map(e=>{return{id:e.id,content:(t=e.content,t.replace(/__THINKING__/g,"")),sender:e.sender,timestamp:e.timestamp.toISOString(),mode:e.mode,isScreenAccessRequest:e.isScreenAccessRequest,screenShareStatus:e.screenShareStatus,isSystemMessage:e.isSystemMessage,isPlaceholder:e.isPlaceholder,placeholderState:e.placeholderState,simulationStatus:e.simulationStatus,parts:e.parts};var t});Ta.updateContext({chat_id:this.chatId,messages:t,isSimulationRunning:e.isSimulationRunning,activeSimulationId:e.activeSimulationId,currentMode:e.currentMode,isOpen:e.isOpen,isMinimized:e.isMinimized,isLoading:e.isLoading})}catch(t){}}}.getInstance();function $a(e,t,n="user-message"){const r=[],i=e.trim();return i&&r.push({type:"text",content:i}),{id:`${n}-${Date.now()}`,content:i,sender:"user",timestamp:/* @__PURE__ */new Date,mode:t,parts:r}}function Ma(e,t,n,r="agent-message"){const i=[],o=e.trim();return o&&i.push({type:"text",content:o}),{id:n||`${r}-${Date.now()}`,content:e,sender:"agent",timestamp:/* @__PURE__ */new Date,mode:t,parts:i}}function Na(e,t,n="agent",r="system-message"){const i=[];return e&&i.push({type:"text",content:e}),{id:`${r}-${Date.now()}`,content:e,sender:n,timestamp:/* @__PURE__ */new Date,mode:t,isSystemMessage:!0,parts:i}}function Oa(e="show"){const t="Started screenshare";return{id:`started-screenshare-${Date.now()}`,content:t,sender:"user",timestamp:/* @__PURE__ */new Date,mode:e,isSystemMessage:!0,parts:[{type:"text",content:t}]}}function Pa(e,t="show"){return{id:`screenshare-${Date.now()}`,content:"",sender:"user",timestamp:/* @__PURE__ */new Date,mode:t,videoStream:e,parts:[]}}var Ra={debug:(e,...t)=>{fa("debug")},info:(e,...t)=>{fa("info")},warn:(e,...t)=>{fa("warn")},error:(e,...t)=>{fa("error")}},La=class e{static instance=null;chatId=null;initializationPromise=null;constructor(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.chatId=this.getStoredChatId(),this.chatId&&Ra.debug("Loaded existing chat ID from storage:",this.chatId))}static getInstance(){return"undefined"==typeof window||"undefined"==typeof document?(e.instance||(e.instance=Object.create(e.prototype),e.instance.chatId=null,e.instance.initializationPromise=null),e.instance):(e.instance||(e.instance=new e),e.instance)}getChatId(){return this.chatId}async getOrCreateChatId(){if(this.chatId)return Ra.debug("Returning existing chat ID:",this.chatId),this.chatId;if(this.initializationPromise)return Ra.debug("Chat ID initialization in progress, waiting..."),this.initializationPromise;const e=this.getStoredChatId();if(e)return this.chatId=e,Ra.debug("Found chat ID in storage:",this.chatId),this.chatId;this.initializationPromise=this.createChatId();try{return await this.initializationPromise}finally{this.initializationPromise=null}}async createChatId(){try{Ra.info("Creating new chat ID...");const e=await pa.chatCreate(void 0);if(!e)throw new Error("API returned empty chat ID");return this.chatId=e,this.storeChatId(e),Ra.info("Created and stored new chat ID:",this.chatId),Aa.createInitialContext(e),e}catch(e){throw Ra.error("Failed to create chat ID:",e),this.initializationPromise=null,e}}getStoredChatId(){return Ta.getChatId()}storeChatId(e){Ta.setChatId(e)}}.getInstance(),ja=class e{static instance=null;abortController=null;chatId=null;status="disconnected";callbacks=/* @__PURE__ */new Set;isIntentionallyDisconnected=!1;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;maxReconnectDelay=3e4;reconnectTimer=null;config;connectionId=0;tabId=globalThis.crypto.randomUUID();constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}addCallbacks(e){this.callbacks.add(e)}removeCallbacks(e){this.callbacks.delete(e)}getStatus(){return this.status}isConnected(){return"registered"===this.status}async connect(e,t){if(this.isIntentionallyDisconnected&&(this.isIntentionallyDisconnected=!1),this.chatId===e&&("connecting"===this.status||"connected"===this.status||"registered"===this.status))return;this.abortController&&(this.abortController.abort(),this.abortController=null),this.chatId=e,t&&(this.config=t),this.setStatus("connecting");const n=++this.connectionId;this.abortController=new AbortController;const r=this.abortController.signal;try{const t={chat_id:e,tab_id:this.tabId};this.config?.mtxId&&this.config?.mtxKey?(t.marketrix_id=this.config.mtxId,t.marketrix_key=this.config.mtxKey):this.config?.mtxApp&&(t.application_id=this.config.mtxApp);const i=await pa.widgetStream(t,{signal:r});this.setStatus("connected"),this.consumeEvents(i,n)}catch(i){r.aborted||(this.setStatus("error"),this.notifyError(/* @__PURE__ */new Error("Stream connection failed")),this.scheduleReconnect())}}async consumeEvents(e,t){let n=!1;try{for await(const r of e){if(this.connectionId!==t){n=!0;break}this.handleMessage(r)}}catch(r){this.connectionId!==t?n=!0:this.isIntentionallyDisconnected||this.setStatus("error")}finally{n||this.connectionId!==t||this.isIntentionallyDisconnected||(this.setStatus("disconnected"),this.scheduleReconnect())}}disconnect(){this.isIntentionallyDisconnected=!0,this.clearReconnectTimer(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.setStatus("disconnected"),this.chatId=null}send(e){return this.chatId?pa.widgetMessage({chat_id:this.chatId,tab_id:this.tabId,command:e}).then(()=>{}).catch(e=>{throw this.notifyError(/* @__PURE__ */new Error(`Failed to send message: ${String(e)}`)),e}):Promise.reject(/* @__PURE__ */new Error("No active chat"))}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(t=>t.onStatusChange?.(e)))}notifyError(e){this.callbacks.forEach(t=>t.onError?.(e))}handleMessage(e){this.isIntentionallyDisconnected||"heartbeat"!==e.type&&("registered"===e.type&&e.chat_id===this.chatId&&(this.setStatus("registered"),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.callbacks.forEach(t=>t.onRegistered?.(e.application_id))),"chat/error"===e.type&&"auth"===e.request_id&&(this.isIntentionallyDisconnected=!0),this.callbacks.forEach(t=>t.onMessage?.(e)))}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.notifyError(/* @__PURE__ */new Error("Max reconnect attempts reached"));this.clearReconnectTimer(),this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);this.reconnectTimer=setTimeout(()=>{!this.isIntentionallyDisconnected&&this.chatId&&this.connect(this.chatId,this.config).catch(console.error)},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},Da=class{config;constructor(e){this.config=e}getChatId(){return La.getChatId()}getUserId(){if(this.config.userId&&"number"==typeof this.config.userId)return this.config.userId;try{const e=localStorage.getItem("marketrix_user_id");if(e){const t=Number(e);if(!isNaN(t))return t}}catch(e){}try{const e=sessionStorage.getItem("marketrix_user_id");if(e){const t=Number(e);if(!isNaN(t))return t}}catch(e){}return null}async logWidgetQuestion(e,t){try{const n=this.getUserId(),r={question:e,mode:t,chat_id:this.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString()};null!==n&&(r.user_id=n),this.config.mtxApp&&(r.application_id=this.config.mtxApp),this.config.mtxId&&this.config.mtxKey&&(r.marketrix_id=this.config.mtxId,r.marketrix_key=this.config.mtxKey),pa.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>{})}catch(n){}}async messageDispatch(e){if(!(await La.getOrCreateChatId()))throw new Error("Failed to initialize chat session");const t=e.mode||"tell";if(e.message&&await this.logWidgetQuestion(e.message,t),!(this.config.mtxId&&this.config.mtxKey||this.config.mtxApp))throw new Error("Either mtxId + mtxKey or mtxApp is required");const n=e.requestId||`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r={type:`chat/${t}`,request_id:n,content:e.message||""};return ja.getInstance().send(r),{messageId:n,response:"",mode:t,timestamp:/* @__PURE__ */new Date}}updateConfig(e){this.config={...this.config,...e}}};function Ha(e){if(!(e&&e instanceof Element))return!1;try{const n=e.tagName.toLowerCase(),r="button"===n;if(!(r||"input"===n||"textarea"===n||"select"===n||"a"===n&&e.hasAttribute("href")||"button"===e.getAttribute("role")||"link"===e.getAttribute("role")||"textbox"===e.getAttribute("role")||"checkbox"===e.getAttribute("role")||"radio"===e.getAttribute("role")||"switch"===e.getAttribute("role")||"tab"===e.getAttribute("role")||"menuitem"===e.getAttribute("role")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||e.hasAttribute("tabindex")&&parseInt(e.getAttribute("tabindex")||"-1",10)>=0))return!1;const i=(t,n)=>{if(r){e.tagName,e.id,e.className}};if(!0===e.disabled)return i("disabled","button is disabled"),!1;if("true"===e.getAttribute("aria-disabled"))return i("aria-disabled","aria-disabled is true"),!1;try{let t=e;for(;t;){if(t instanceof HTMLElement&&t.inert)return i("inert","ancestor is inert"),!1;const e=t instanceof Element?t.getRootNode():null;t=t instanceof Element?t.parentElement||(e instanceof ShadowRoot?e.host:null):null}}catch(t){}const o=e.hasAttribute("onclick");if(r&&o)return!0;let a,s;try{a=window.getComputedStyle(e)}catch(t){return i("computed-style","failed to get computed style"),!1}if("none"===a.display)return i("display","display is none"),!1;if("none"===a.pointerEvents)return i("pointer-events","pointer-events is none"),!1;try{s=e.getBoundingClientRect()}catch(t){return i("bounding-rect","failed to get bounding rect"),!1}if(s.width<=0||s.height<=0)return i("dimensions",`width=${s.width}, height=${s.height}`),!1;try{let t=e;for(;t&&t!==document.body;){const e=t.getRootNode(),n=t.parentElement||(e instanceof ShadowRoot?e.host:null);if(!n)break;let o,a;try{o=window.getComputedStyle(n),a=n.getBoundingClientRect()}catch{t=n;continue}if("hidden"===o.overflow||"clip"===o.overflow){const e=s.right<a.left||s.left>a.right||s.bottom<a.top||s.top>a.bottom;if(r){if(e)return i("overflow-clipping","completely outside parent bounds"),!1}else if(e)return!1}t=n}}catch(t){}try{let t=e.getRootNode();for(;t instanceof ShadowRoot;){const e=t.host;let n;try{n=e.getBoundingClientRect()}catch{break}if(n.width<=0||n.height<=0)return!1;t=e.getRootNode()}}catch(t){}return!0}catch(t){return!1}}var Za=class e{static instance;elementMap=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;selectorMap=/* @__PURE__ */new Map;fingerprintMap=/* @__PURE__ */new Map;indexingInProgress=!1;indexVersion=0;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}generateSelector(e){if(e.id&&1===document.querySelectorAll(`#${CSS.escape(e.id)}`).length)return`#${CSS.escape(e.id)}`;const t=[];let n=e;for(;n&&n!==document.body&&n.parentElement;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${CSS.escape(n.id)}`,t.unshift(e);break}{const t=n.parentElement;if(!t)break;const r=n.tagName,i=Array.from(t.children).filter(e=>e.tagName===r);if(i.length>1){e+=`:nth-of-type(${i.indexOf(n)+1})`}}t.unshift(e),n=n.parentElement}return t.join(" > ")}generateFingerprint(e,t){return{tagName:e.tagName,id:e.id||null,textContent:((e,t=100)=>{if(!e)return null;const n=e.trim().replace(/\s+/g," ");return n.length>t?n.slice(0,t):n})(e.textContent),type:e.getAttribute("type"),role:e.getAttribute("role"),ariaLabel:e.getAttribute("aria-label"),name:e.getAttribute("name"),href:e.getAttribute("href"),selector:t,indexVersion:this.indexVersion}}matchesFingerprint(e,t){return e.tagName===t.tagName&&(!(!t.id||e.id!==t.id)||(!t.type||e.getAttribute("type")===t.type)&&((!t.ariaLabel||e.getAttribute("aria-label")===t.ariaLabel)&&((!t.role||e.getAttribute("role")===t.role)&&((!t.href||"A"!==t.tagName||e.getAttribute("href")===t.href)&&(!t.name||e.getAttribute("name")===t.name)))))}validateElementAtIndex(e){const t=this.fingerprintMap.get(e);if(!t)return{isValid:!0};const n=this.elementMap.get(e);return n&&document.contains(n)?n instanceof HTMLElement&&!this.matchesFingerprint(n,t)?{isValid:!1,mismatchReason:"element_changed"}:{isValid:!0}:{isValid:!1,mismatchReason:"element_removed"}}indexInteractableElements(){if(this.indexingInProgress)return[];try{this.indexingInProgress=!0,this.clearIndex();const e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{if(e instanceof HTMLElement&&null===e.offsetParent&&"BODY"!==e.tagName){const t=window.getComputedStyle(e),n="fixed"===t.position||"sticky"===t.position;if("none"===t.display)return NodeFilter.FILTER_REJECT;if(!n){let t=e.parentElement,n=!1;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if("fixed"===e.position||"sticky"===e.position){n=!0;break}t=t.parentElement}if(!n)return NodeFilter.FILTER_REJECT}}return NodeFilter.FILTER_ACCEPT}});let t=e.nextNode(),n=0;const r=[];for(;t;){if(t instanceof HTMLElement){const e=t.matches('a[href], button, input, textarea, select, [role="button"]'),i=t.classList.contains("cursor-pointer")||t.classList.contains("clickable"),o="onclick"in t&&"function"==typeof t.onclick;if(e||i||o||Ha(t)){this.elementMap.set(n,t),this.elementToSequence.set(t,n);const e=this.generateSelector(t);this.selectorMap.set(n,e);const i=this.generateFingerprint(t,e);this.fingerprintMap.set(n,i),r.push([n,t]),n++}}t=e.nextNode()}return this.indexVersion++,r}finally{this.indexingInProgress=!1}}getElementCoordinates(e){const t=e.getBoundingClientRect(),n=this.calculateGlobalZOrder(e);return{x:Math.round(t.left),y:Math.round(t.top),w:Math.round(t.width),h:Math.round(t.height),z:n}}isStackingContext(e){const t=window.getComputedStyle(e),n=t.position;if(("fixed"===n||"absolute"===n||"relative"===n||"sticky"===n)&&"auto"!==t.zIndex)return!0;if("auto"!==t.zIndex&&e.parentElement){const t=window.getComputedStyle(e.parentElement).display;if("flex"===t||"inline-flex"===t||"grid"===t||"inline-grid"===t)return!0}const r=parseFloat(t.opacity);if(!isNaN(r)&&r<1)return!0;if(t.transform&&"none"!==t.transform)return!0;if(t.filter&&"none"!==t.filter)return!0;const i=t.willChange;if(i&&(i.includes("transform")||i.includes("opacity")))return!0;if("isolate"===t.isolation)return!0;const o=t.contain;return!(!o||!(o.includes("layout")||o.includes("style")||o.includes("paint")))}calculateGlobalZOrder(e){let t=e;const n=[];for(;t&&t!==document.body&&t.parentElement;){const e=window.getComputedStyle(t);if(this.isStackingContext(t)){let r=0;if("auto"!==e.zIndex){const t=parseInt(e.zIndex,10);isNaN(t)||(r=t)}let i=0;t.parentElement&&(i=Array.from(t.parentElement.children).indexOf(t)),n.push({element:t,zIndex:r,domOrder:i})}t=t.parentElement}let r=1e6;for(let i=n.length-1;i>=0;i--){const e=n[i];r+=1e4*e.zIndex+e.domOrder}if(e.parentElement){r+=Array.from(e.parentElement.children).indexOf(e)}return r}getSnapshotHtml(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,r]of this.elementMap.entries())if(r instanceof HTMLElement){const i=this.selectorMap.get(n);if(i)try{const t=(e.querySelector("body")||e).querySelector(i);if(t)if(t.setAttribute("data-id",n.toString()),"none"===window.getComputedStyle(r).display)t.setAttribute("data-x","0"),t.setAttribute("data-y","0"),t.setAttribute("data-w","0"),t.setAttribute("data-h","0"),t.setAttribute("data-z","0");else{const e=this.getElementCoordinates(r);t.setAttribute("data-x",e.x.toString()),t.setAttribute("data-y",e.y.toString()),t.setAttribute("data-w",e.w.toString()),t.setAttribute("data-h",e.h.toString()),t.setAttribute("data-z",e.z.toString())}}catch(t){}}return e.outerHTML}getInteractableElements(){this.indexInteractableElements();const e=[];for(const[t,n]of this.elementMap.entries())if(n instanceof HTMLElement){const r=this.fingerprintMap.get(t);r&&e.push({index:t,fingerprint:r,coords:this.getElementCoordinates(n),cssClasses:Array.from(n.classList)})}return e}getSequenceForElement(e){return this.elementToSequence.get(e)}clearIndex(){this.elementMap.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap,this.fingerprintMap.clear()}checkInteractability(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=window.getComputedStyle(e);if("none"===n.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===n.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(n.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const r=e.getBoundingClientRect();if(0===r.width||0===r.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;if(r.bottom<0||r.top>window.innerHeight||r.right<0||r.left>window.innerWidth)return`ELEMENT_NOT_INTERACTABLE: Element ${t} is off-screen`;const i=r.left+r.width/2,o=r.top+r.height/2,a=document.elementFromPoint(i,o);if(a&&a!==e&&!e.contains(a)&&!(a.closest("#marketrix-show-highlight")||a.closest("#marketrix-show-popup")||a.closest("[data-marketrix-widget]"))){const e=a.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${a.className?`${e}.${a.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}checkElementInteractable(e,t){return this.checkInteractability(e,t)}getElementByIndex(e){let t=null;if(this.elementMap.has(e)){const n=this.elementMap.get(e);n&&n instanceof HTMLElement&&(t=n)}if(!t&&this.selectorMap.has(e)){const n=this.selectorMap.get(e);if(n)try{const e=document.querySelector(n);e&&e instanceof HTMLElement&&(t=e)}catch(r){}}if(!t)return{element:null,error:`Element ${e} not found`};const n=this.checkInteractability(t,e);return n?{element:null,error:n}:{element:t}}getValidatedElement(e){const t=this.validateElementAtIndex(e);if(!t.isValid)return{element:null,validation:t,error:`DOM_CHANGED: Element at index ${e} ${"element_removed"===t.mismatchReason?"no longer exists":"has changed"}. Call get_html to get updated indices.`};const n=this.elementMap.get(e);if(!n)return{element:null,validation:t,error:`Element ${e} not found`};const r=this.checkInteractability(n,e);return r?{element:null,validation:t,error:r}:{element:n,validation:t}}}.getInstance(),Fa=null;async function Ua(){if(Fa?.active){const e=Fa.getVideoTracks();if(e.length>0&&"live"===e[0].readyState)return Fa}const e=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!e||0===e.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return Fa=e,e.getVideoTracks()[0].addEventListener("ended",()=>{Fa=null}),e}function Ba(){return null!==function(){if(Fa?.active){const e=Fa.getVideoTracks();if(e.length>0&&"live"===e[0].readyState)return Fa}return Fa=null,null}()}var Wa=class e{static instance;currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;updateHighlightPosition=null;rafId=null;mutationObserver=null;visibilityCheckInterval=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:i}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===i&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.createHighlight(t),this.createPopup(n,r),this.setupPositionUpdates(),this.setupElementMonitoring(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t}).finally(()=>{this.cleanup()})),this.currentPromise}cleanup(){this.rejectPromise&&(this.rejectPromise("Cancelled by cleanup"),this.rejectPromise=null),this.resolvePromise=null,this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler&&(window.removeEventListener("scroll",this.scrollHandler,{capture:!0}),window.removeEventListener("resize",this.scrollHandler),window.removeEventListener("touchmove",this.scrollHandler),window.removeEventListener("wheel",this.scrollHandler),this.scrollHandler=null),null!==this.rafId&&(window.cancelAnimationFrame(this.rafId),this.rafId=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.updateHighlightPosition=null,this.currentPopup&&(this.currentPopup.remove(),this.currentPopup=null),this.currentHighlight&&(this.currentHighlight.remove(),this.currentHighlight=null);const e=document.getElementById("marketrix-show-popup");e&&e.remove();const t=document.getElementById("marketrix-show-highlight");t&&t.remove(),this.currentElement=null,this.currentOptions=null,this.currentPromise=null,this.resolvePromise=null,this.rejectPromise=null}createHighlight(e){const t=e.getBoundingClientRect(),n=document.createElement("div");n.id="marketrix-show-highlight",n.style.cssText=`\n position: fixed;\n top: ${t.top}px;\n left: ${t.left}px;\n width: ${t.width}px;\n height: ${t.height}px;\n border: 3px solid #3b82f6;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2), 0 0 20px rgba(59, 130, 246, 0.4);\n z-index: 2147483645;\n pointer-events: none;\n transition: none;\n `,document.body.appendChild(n),this.currentHighlight=n}createPopup(e,t){const n=document.createElement("div");n.id="marketrix-show-popup",n.innerHTML=t?`<div style="font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>`:`<div style="margin-bottom: 12px; font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>\n <div style="display: flex; gap: 8px; justify-content: flex-end;">\n <button id="marketrix-show-continue" style="\n background: #3b82f6; color: white; border: none; border-radius: 6px;\n padding: 8px 16px; font-size: 12px; font-weight: 500; cursor: pointer;\n ">Continue</button>\n </div>`,document.body.appendChild(n),this.currentPopup=n,t||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.updateHighlightPosition=()=>{if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();this.currentHighlight.style.top=`${e.top}px`,this.currentHighlight.style.left=`${e.left}px`,this.currentHighlight.style.width=`${e.width}px`,this.currentHighlight.style.height=`${e.height}px`,this.updatePopupPosition()},this.scrollHandler=()=>{null!==this.rafId&&window.cancelAnimationFrame(this.rafId),this.updateHighlightPosition?.()},window.addEventListener("scroll",this.scrollHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.scrollHandler,{passive:!0}),window.addEventListener("touchmove",this.scrollHandler,{passive:!0}),window.addEventListener("wheel",this.scrollHandler,{passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=320,n=120,r=10,i=e.left+e.width/2,o=e.top+e.height/2,a=[{left:e.right+20,top:o-60},{left:e.left-t-20,top:o-60},{left:i-160,top:e.top-n-20},{left:i-160,top:e.bottom+20}];let s=a[0];for(const d of a)if(d.left>=r&&d.left+t<=window.innerWidth-r&&d.top>=r&&d.top+n<=window.innerHeight-r){s=d;break}const c=Math.max(r,Math.min(s.left,window.innerWidth-t-r)),l=Math.max(r,Math.min(s.top,window.innerHeight-n-r));this.currentPopup.style.cssText+=`\n position: fixed;\n top: ${l}px;\n left: ${c}px;\n width: 320px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n z-index: 2147483646;\n padding: 16px;\n `}setupClickHandler(){this.clickHandler=e=>{if(this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)){e.preventDefault(),e.stopPropagation();const t=this.resolvePromise;this.resolvePromise=null,this.rejectPromise=null,t(!0)}},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{const t=e.querySelector("#marketrix-show-continue");t&&t.addEventListener("click",e=>{if(e.stopPropagation(),this.resolvePromise){const e=this.resolvePromise;this.resolvePromise=null,this.rejectPromise=null,e(!0)}})})}setupElementMonitoring(){this.currentElement&&(this.mutationObserver=new MutationObserver(()=>{this.currentElement&&!document.body.contains(this.currentElement)&&this.failWithElementGone("Element was removed from DOM")}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{if(!this.currentElement)return;const e=Za.getSequenceForElement(this.currentElement)??-1,t=Za.checkElementInteractable(this.currentElement,e);t&&this.failWithElementGone(t)},200)}failWithElementGone(e){if(this.rejectPromise){const t=this.rejectPromise;this.rejectPromise=null,this.resolvePromise=null,t(/* @__PURE__ */new Error(`ELEMENT_GONE: ${e}`))}this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}.getInstance(),qa=class e{static instance;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}async executeTool(e,t,n="do",r=""){try{if("show"===n&&this.requiresHighlight(e)){const n=t.index;if(void 0!==n){const{element:t,error:i}=Za.getElementByIndex(n);if(!t)return{success:!1,data:{text:""},error:i||`Element ${n} not found`};if(!(await Wa.showToolAction({element:t,explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e})))return{success:!1,data:{text:""},error:"User cancelled action"}}}switch(e){case"navigate":return this.navigate(t);case"search":return this.search(t);case"click_element":return await this.clickElement(t);case"type_text":return this.typeText(t);case"scroll":return this.scroll(t);case"scroll_to_text":return this.scrollToText(t);case"extract":return this.extract(t);case"go_back":return this.goBack();case"wait":return await this.wait(t);case"select_dropdown_option":return this.selectDropdownOption(t);case"get_dropdown_options":return this.getDropdownOptions(t);case"send_keys":return this.sendKeys(t);case"upload_file":return this.uploadFile(t);case"close_tab":return this.closeTab();case"switch_tab":return this.switchTab(t);case"done":return this.done(t);case"get_html":return this.getHtml();case"get_interactable_elements":return this.getInteractableElements();case"get_screenshot":return await this.getScreenshot();default:return{success:!1,data:{text:""},error:`Unknown tool: ${e}`}}}catch(i){return Wa.cleanup(),{success:!1,data:{text:""},error:i instanceof Error?i.message:String(i)}}}requiresHighlight(e){return _a.has(e)}navigate(e){return e.url?e.new_tab?(window.open(e.url,"_blank"),{success:!0,data:{text:`Opened ${e.url} in new tab`}}):(window.location.href=e.url,{success:!0,data:{text:`Navigating to ${e.url}`}}):{success:!1,data:{text:""},error:"URL is required"}}search(e){if(!e.query)return{success:!1,data:{text:""},error:"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}`),window.location.href=r,{success:!0,data:{text:`Searching for "${e.query}" on ${t}`}}}async clickElement(e){if(void 0===e.index)return{success:!1,data:{text:""},error:"Index required"};const{element:t,error:n}=Za.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),setTimeout(()=>{try{t.click()}catch(e){try{t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}))}catch(n){}}},50),{success:!0,data:{text:`Clicked element ${e.index}`}}):{success:!1,data:{text:""},error:n||`Element ${e.index} not found`}}typeText(e){if(void 0===e.index||void 0===e.text)return{success:!1,data:{text:""},error:"Index and text required"};const t=!1!==e.clear,{element:n,error:r}=Za.getValidatedElement(e.index);if(!n)return{success:!1,data:{text:""},error:r||`Element ${e.index} not found`};if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n.isContentEditable){const r=n;try{r.focus()}catch(i){}const o=t?e.text:r.value+e.text;let a=!1,s=null;if(!a)try{const e="TEXTAREA"===r.tagName.toUpperCase()?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,t=Object.getOwnPropertyDescriptor(e,"value");t?.set&&(t.set.call(r,o),a=!0)}catch(i){s=i}if(!a)try{r.value=o,a=!0}catch(i){s=i}if(!a)try{r.focus(),t&&r.select(),document.execCommand("insertText",!1,e.text)&&(a=!0)}catch(i){s=i}if(!a)try{r.focus(),t&&(r.value="");for(const t of e.text)r.dispatchEvent(new KeyboardEvent("keydown",{key:t,bubbles:!0,cancelable:!0})),r.value+=t,r.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t})),r.dispatchEvent(new KeyboardEvent("keyup",{key:t,bubbles:!0,cancelable:!0}));a=!0}catch(i){s=i}if(!a)return{success:!1,data:{text:""},error:`Failed to set value: ${s instanceof Error?s.message:String(s)}`};try{const t=new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text});r.dispatchEvent(t),r.dispatchEvent(new Event("change",{bubbles:!0})),r.dispatchEvent(new Event("blur",{bubbles:!0}))}catch(i){}}else if("value"in n)try{n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}catch(i){return{success:!1,data:{text:""},error:`Failed to set value on element: ${i instanceof Error?i.message:String(i)}`}}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(i){return{success:!1,data:{text:""},error:`Failed to set textContent: ${i instanceof Error?i.message:String(i)}`}}return{success:!0,data:{text:`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{success:!1,data:{text:""},error:"Invalid direction"}}return{success:!0,data:{text:`Scrolled ${e.direction}`}}}scrollToText(e){if(!e.text)return{success:!1,data:{text:""},error:"Text required"};const t=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let n;for(;n=t.nextNode();)if(n.textContent?.includes(e.text)&&n.parentElement)return n.parentElement.scrollIntoView({behavior:"smooth",block:"center"}),{success:!0,data:{text:`Scrolled to "${e.text}"`}};return{success:!1,data:{text:""},error:`Text "${e.text}" not found`}}extract(e){const t=e.start_from_char??0,n=!1!==e.extract_links,r=document.body.innerText;return{success:!0,data:{title:document.title,url:window.location.href,text:r.slice(t,t+1e4),links:n?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]}}}goBack(){return window.history.length>1?(window.history.back(),{success:!0,data:{text:"Navigated back"}}):{success:!1,data:{text:""},error:"No history"}}async wait(e){return void 0===e.seconds?{success:!1,data:{text:""},error:"Seconds required"}:(await new Promise(t=>setTimeout(t,1e3*e.seconds)),{success:!0,data:{text:`Waited ${e.seconds}s`}})}selectDropdownOption(e){if(void 0===e.index||!e.option)return{success:!1,data:{text:""},error:"Index/Option required"};const{element:t,error:n}=Za.getValidatedElement(e.index);if(!t)return{success:!1,data:{text:""},error:n||`Select ${e.index} not found`};if(!(t instanceof HTMLSelectElement))return{success:!1,data:{text:""},error:`Element ${e.index} is not a select element`};const r=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return r?(t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,data:{text:`Selected ${e.option}`}}):{success:!1,data:{text:""},error:`Option ${e.option} not found`}}getDropdownOptions(e){const t=e.index,{element:n,error:r}=Za.getValidatedElement(t);return n?n instanceof HTMLSelectElement?{success:!0,data:{options:Array.from(n.options).map(e=>({value:e.value,text:e.text}))}}:{success:!1,data:{options:[]},error:`Element ${t} is not a select element`}:{success:!1,data:{options:[]},error:r||`Select ${t} not found`}}sendKeys(e){if(void 0===e.index||!e.keys)return{success:!1,data:{text:""},error:"Index/Keys required"};const{element:t,error:n}=Za.getValidatedElement(e.index);return t?(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})),{success:!0,data:{text:this.simulateKeyAction(t,e.keys)||`Sent keys ${e.keys}`}}):{success:!1,data:{text:""},error:n||`Element ${e.index} not found`}}simulateKeyAction(e,t){switch(t){case"Tab":{const t=Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent),n=t.indexOf(e);if(-1!==n&&n<t.length-1){const e=t[n+1];return e.focus(),`Tab: moved focus to ${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""}`}return"Tab: no next focusable element"}case"Shift+Tab":{const t=Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent),n=t.indexOf(e);if(n>0){const e=t[n-1];return e.focus(),`Shift+Tab: moved focus to ${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""}`}return"Shift+Tab: no previous focusable element"}case"Enter":if(e instanceof HTMLButtonElement||"button"===e.getAttribute("role"))return e.click(),"Enter: clicked button";if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){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}`):e instanceof HTMLButtonElement||"button"===e.getAttribute("role")?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t<e.options.length-1?(e.selectedIndex=t+1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowDown: selected "${e.options[e.selectedIndex].text}"`):"ArrowDown: already at last option"}return"ArrowDown: dispatched event";case"ArrowUp":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t>0?(e.selectedIndex=t-1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowUp: selected "${e.options[e.selectedIndex].text}"`):"ArrowUp: already at first option"}return"ArrowUp: dispatched event";case"Home":return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value;if(!t||0===t.length)return"Backspace: input is empty, nothing to delete";let n,r,i=e.selectionStart??t.length,o=e.selectionEnd??t.length;if(0===i&&0===o&&(i=t.length,o=t.length),i===o&&i>0)n=t.slice(0,i-1)+t.slice(o),r=i-1;else{if(i===o)return"Backspace: cursor at start, nothing to delete";n=t.slice(0,i)+t.slice(o),r=i}const a=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;return a?a.call(e,n):e.value=n,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(r,r),`Backspace: deleted character, value is now "${n}"`}return"Backspace: dispatched event";case"Delete":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.selectionStart||0,n=e.selectionEnd||0,r=e.value;let i;if(t===n&&t<r.length)i=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";i=r.slice(0,t)+r.slice(n)}const o=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;return o?o.call(e,i):e.value=i,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(t,t),`Delete: deleted character, value is now "${i}"`}return"Delete: dispatched event";default:return null}}uploadFile(e){return{success:!1,data:{text:""},error:"File upload not supported via script"}}closeTab(){return window.close(),{success:!0,data:{text:"Attempted close"}}}switchTab(e){return e.tab_id?{success:!1,data:{text:""},error:"Tab switching not supported"}:{success:!1,data:{text:""},error:"tab_id is required"}}done(e){return void 0===e.success?{success:!1,data:{text:""},error:"success parameter is required"}:{success:!0,data:{text:e.message||(e.success?"Task completed":"Task failed")}}}getHtml(){try{return{success:!0,data:{text:Za.getSnapshotHtml()}}}catch(e){return{success:!1,data:{text:""},error:String(e)}}}getInteractableElements(){try{return{success:!0,data:{elements:Za.getInteractableElements()}}}catch(e){return{success:!1,data:{elements:[]},error:String(e)}}}async getScreenshot(){try{const e=await Ua();if(!e)return{success:!1,data:{text:""},error:"Failed to get stream"};const t=document.createElement("video");t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),await new Promise(e=>{t.onloadeddata=()=>e()});const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight,n.getContext("2d")?.drawImage(t,0,0);const r=n.toDataURL("image/jpeg",.75);return t.remove(),{success:!0,data:{text:r}}}catch(e){return{success:!1,data:{text:""},error:String(e)}}}}.getInstance(),Va=class e{static instance;config=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadConfig(){const e=Ta.getConfig();return e?(this.config=e,e):(this.config={},this.config)}saveConfig(e){Ta.setConfig(e),this.config=e}updateConfig(e){this.config||(this.config={}),this.config={...this.config,...e},this.saveConfig(this.config)}getConfig(){return this.config}shouldShowWidget(){return!!this.config&&(this.config.widget_enabled??!1)}}.getInstance();function Ga(e,t={}){return{...t,...e}}var Ja=e=>({state:e,effects:[]});function Ka(e,t,n,r,i,o,a){const s=function(e){return Ea[e]?Ea[e]:e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}(r),c=va({messages:e,isSimulationRunning:t,currentMode:n,requireContent:"failed"===o});if(!c)return e;let l=c.message;const d=t&&"show"===n&&_a.has(r),u="done"===r,p="show"===n||"do"===n;"in_progress"===o?(u||(l=function(e,t,n){const r=xa(e),i=r.parts||[],o=[...i],a=i.findIndex(e=>"progress"===e.type&&e.browserToolName===t&&"in_progress"===e.status),s=!ka.has(t),c="default",l=Sa(n);return a>=0?o[a]={...o[a],content:l,hideIcon:s,textStyle:c}:o.push({type:"progress",content:l,status:"in_progress",browserToolName:t,hideIcon:s,textStyle:c}),{...r,parts:o}}(l,s,i||s)),t&&p&&(l=za(l,t,n,d))):"completed"===o?(u||(l=function(e,t){const n=xa(e),r=n.parts||[],i=[...r];let o=-1;if(t)o=r.map(e=>"progress"===e.type?e.browserToolName:"").lastIndexOf(t);else for(let a=r.length-1;a>=0;a--)if("progress"===r[a].type&&"in_progress"===r[a].status){o=a;break}return o>=0&&(i[o]={...i[o],status:"completed"}),{...n,parts:i}}(l)),t&&p&&(l=za(l,t,n,!1))):(l=function(e,t,n){const r=xa(e),i=r.parts||[],o=n.toLowerCase().includes("cancelled by cleanup"),a=[...i];let s=i.map(e=>"progress"===e.type?e.browserToolName:"").lastIndexOf(t);if(-1===s)for(let c=i.length-1;c>=0;c--)if("progress"===i[c].type&&"in_progress"===i[c].status){s=c;break}if(s>=0)if(o){const e=Sa(a[s].content);a[s]={...a[s],status:"completed",content:e}}else{const e=Sa(n),t=Sa(a[s].content);a[s]={...a[s],status:"failed",content:e?`${t} (${e})`:t}}return{...r,parts:a}}(l,s,a||""),t&&p&&(l=za(l,t,n,!1)));const h=[...e];return h[c.index]=l,h}function Ya(e,t,n,r,i,o){return{...e,messages:Ka(e.messages,e.task.isSimulationRunning,i,t,n,r,o)}}var Xa=n(void 0),Qa={activeSimulationId:null,isSimulationRunning:!1},es=({children:e,previewMode:t=!1,currentMode:n,uiActions:r,initialMessages:i,initialTask:a})=>{const[c,l]=p(()=>({messages:i??[],task:a??Qa})),h=u(c),m=u(n);m.current=n;const g=u(0),w=u(/* @__PURE__ */new Set),b=u({}),y=o(e=>{const t=h.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(h.current=n,l(n))},[]),v=o(e=>{y(t=>({...t,messages:[...t.messages,e]}))},[y]),x=o((e,t)=>{y(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[y]),k=o(e=>{y(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[y]),_=o(e=>{y(t=>({...t,messages:e}))},[y]),S=o(()=>{y(e=>({...e,messages:[]}))},[y]),z=o(e=>{y(t=>({...t,task:{activeSimulationId:e.activeSimulationId,isSimulationRunning:e.isSimulationRunning}}))},[y]),E=o(async(e,n,i,o,a)=>{const s=n??m.current;if(t)return a||v($a(e,s)),void v(Ma("This is a preview. In production, I'll respond to your messages here."));let c=Va.getConfig();if(c||(c=Va.loadConfig()),!c||!c.mtxId&&!c.mtxKey&&!c.mtxApp)return void v(Ma("Configuration error: Missing API credentials. Please check your widget settings."));a||v($a(e,s));const l=`temp-${globalThis.crypto.randomUUID()}`;v({id:l,content:ba(""),sender:"agent",timestamp:/* @__PURE__ */new Date,mode:s,isPlaceholder:!0,placeholderState:"thinking",parts:[]}),r.setLoading(!0);const d=new Da(c);try{i&&d.updateConfig({mtxApp:i});const t=d.getChatId();if(t){const e=ja.getInstance();if(!e.isConnected()){const n=Va.getConfig();try{await e.connect(t,n?{mtxId:n.mtxId,mtxKey:n.mtxKey,mtxApp:n.mtxApp}:void 0)}catch(u){}}}await d.messageDispatch({message:e,mode:s,question:o,requestId:l})}catch(p){y(e=>{const t="I'm sorry, I encountered an error processing your request. Please try again.",n=e.messages.map(e=>{if(e.id!==l)return e;const n=[...e.parts??[],{type:"text",content:t}];return{...e,isPlaceholder:!1,parts:n,content:t}});return{...e,messages:n}})}finally{r.setLoading(!1)}},[t,v,y,r]),I=o(e=>{if(w.current.add(e),w.current.size>1e3){const e=Array.from(w.current);w.current=new Set(e.slice(-500))}},[]),C=o(()=>{const e=b.current;if(e.apiTaskId&&e.agentRunning){const t=e.apiTaskId;b.current={},y(e=>({...e,task:{isSimulationRunning:!0,activeSimulationId:t}}))}},[y]);s(()=>{if(t)return;const e=ja.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:i,mode:o,explanation:a}=t,s=await qa.executeTool(r,i,o,a);if(s.success)try{g.current++,e.send({type:"tool/response",tool_call_id:n,success:!0,data:"string"==typeof s.data?s.data:JSON.stringify(s.data),state_version:g.current}).catch(e=>{}),y(e=>Ya(e,r,a,"completed",m.current)),"done"===r&&(b.current={},y(e=>function(e,t){const n=va({messages:e.messages,isSimulationRunning:e.task.isSimulationRunning,currentMode:t,requireContent:!1}),r=[...e.messages];if(n){const e=(n.message.parts??[]).filter(e=>!("progress"===e.type&&"done"===e.browserToolName));r[n.index]={...n.message,simulationStatus:"done",parts:e}}return{messages:r,task:{isSimulationRunning:!1,activeSimulationId:null}}}(e,m.current)))}catch(c){y(e=>Ya(e,r,a,"failed",m.current,"Connection error"))}else y(e=>Ya(e,r,a,"failed",m.current,s.error||"Tool execution failed")),g.current++,e.send({type:"tool/response",tool_call_id:n,success:!1,data:"string"==typeof s.data?s.data:JSON.stringify(s.data),error:s.error??void 0,state_version:g.current}).catch(e=>{})},i={onStatusChange:e=>{r.setAgentAvailable("registered"===e)},onMessage:async t=>{if("tool/call"===t.type){const n=t.tool_call_id;if(w.current.has(n))return;if(I(n),!ga.map(e=>e.id).includes(t.browser_tool))return void e.send({type:"tool/response",tool_call_id:n,success:!1,error:`Unknown tool: ${t.browser_tool}`,state_version:g.current}).catch(e=>{});h.current.task.isSimulationRunning,void 0!==t.state_version&&t.state_version>g.current&&(g.current=t.state_version)}else if("task/status"!==t.type||"completed"!==t.status&&"failed"!==t.status&&"stopped"!==t.status){if("task/status"===t.type&&"has_question"===t.status)b.current={};else if("task/status"===t.type&&"running"===t.status)return b.current={...b.current,agentRunning:!0,apiTaskId:b.current.apiTaskId||t.task_id||void 0},void C()}else w.current.clear(),b.current={};let i=[];y(e=>{const n=function(e,t,n){switch(t.type){case"tool/call":{const r=e.task.isSimulationRunning?e.task:{...e.task,isSimulationRunning:!0},i=r.isSimulationRunning,o=t.mode||n||"do",a=t.explanation||"";return{state:{messages:Ka(e.messages,i,n,t.browser_tool,a,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:o,explanation:a}]}}case"task/status":{const r=t.message||"";if("running"===t.status)return Ja(e);if("has_question"===t.status){const t=va({messages:e.messages,isSimulationRunning:e.task.isSimulationRunning,currentMode:n,requireContent:!1}),i=[...e.messages];if(t){const e=za(t.message,!1,n);i[t.index]={...e,placeholderState:"waiting-for-user",...r&&{content:r}}}return{state:{messages:i,task:{isSimulationRunning:!1,activeSimulationId:null}},effects:[]}}const i=va({messages:e.messages,isSimulationRunning:e.task.isSimulationRunning,currentMode:n,requireContent:!1}),o=[...e.messages];if(i){let e="done";"failed"===t.status?e="failed":"stopped"===t.status&&(e="stopped"),o[i.index]={...i.message,simulationStatus:e,...r&&{content:r}}}return{state:{messages:o,task:{isSimulationRunning:!1,activeSimulationId:null}},effects:[]}}case"chat/delta":{const n=e.messages.map(e=>{if(e.id!==t.request_id)return e;const n=[...e.parts??[]],r=n[n.length-1];"text"===r?.type&&r.streaming?n[n.length-1]={...r,content:r.content+t.text}:n.push({type:"text",content:t.text,streaming:!0});const i=n[n.length-1].content;return{...e,content:i,isPlaceholder:!1,placeholderState:void 0,parts:n}});return{state:{...e,messages:n},effects:[]}}case"chat/response":{const n=e.messages.map(e=>{if(e.id!==t.request_id)return e;const n=[...e.parts??[]],r=n[n.length-1];return"text"===r?.type&&r.streaming?n[n.length-1]={type:"text",content:t.text}:n.push({type:"text",content:t.text}),{...e,content:t.text,isPlaceholder:!1,placeholderState:void 0,parts:n}}),r=[{type:"setLoading",value:!1}];return{state:{...e,messages:n},effects:r}}case"chat/error":{const n=e.messages.map(e=>{if(e.id!==t.request_id)return e;const n=`Error: ${t.error}`,r=[...e.parts??[],{type:"text",content:n}];return{...e,content:n,isPlaceholder:!1,placeholderState:void 0,parts:r}});return{state:{...e,messages:n},effects:[{type:"setLoading",value:!1}]}}default:return Ja(e)}}(e,t,m.current);return i=n.effects,n.state}),(e=>{for(const t of e)"setLoading"===t.type&&r.setLoading(t.value)})(i);const o=i.find(e=>"executeTool"===e.type);"executeTool"===o?.type&&await n(o)},onError:e=>{r.setError(e.message)}};return e.addCallbacks(i),()=>{e.removeCallbacks(i)}},[t,y,C,I,r]);const T=o(async()=>{const e=h.current.task.activeSimulationId??void 0;y(e=>function(e,t){const n=va({messages:e.messages,isSimulationRunning:e.task.isSimulationRunning,currentMode:t,requireContent:!1}),r=[...e.messages];return n&&(r[n.index]={...n.message,simulationStatus:"stopped"}),{messages:r,task:{isSimulationRunning:!1,activeSimulationId:null}}}(e,m.current)),t||ja.getInstance().send({type:"chat/stop",...e&&{task_id:e}}).catch(e=>{})},[t,y]),A=d(()=>({addMessage:v,updateMessage:x,removeMessage:k,setMessages:_,clearMessages:S,messageDispatch:E}),[v,x,k,_,S,E]),$=d(()=>({setTaskState:z,stopTask:T}),[z,T]),M=d(()=>({messages:c.messages}),[c.messages]);/* @__PURE__ */
|
|
2
|
+
return Jr(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(/* @__PURE__ */Jr(e=>e.toLowerCase()))},toUpperCase(){return this.check(/* @__PURE__ */Jr(e=>e.toUpperCase()))},slugify(){return this.check(/* @__PURE__ */Jr(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),$i=/*@__PURE__*/De("ZodString",(e,t)=>{In.init(e,t),Ai.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ct(t)})}(Oi,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ct(t)})}(Li,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ct(t)})}(Xi,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ct(t)})}(ji,t)),e.guid=t=>e.check(Hr(Pi,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ct(t)})}(Ri,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ct(t)})}(Ri,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ct(t)})}(Ri,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ct(t)})}(Ri,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ct(t)})}(Di,t)),e.guid=t=>e.check(Hr(Pi,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ct(t)})}(Hi,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ct(t)})}(Zi,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ct(t)})}(Fi,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ct(t)})}(Ji,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ct(t)})}(Ki,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ct(t)})}(Ui,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ct(t)})}(Bi,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ct(t)})}(Wi,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ct(t)})}(qi,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ct(t)})}(Vi,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ct(t)})}(Gi,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ct(t)})}(Yi,t)),e.datetime=t=>e.check(ai(t)),e.date=t=>e.check(ci(t)),e.time=t=>e.check(di(t)),e.duration=t=>e.check(pi(t))});function Mi(e){return function(e,t){return new e({type:"string",...ct(t)})}($i,e)}var Ni=/*@__PURE__*/De("ZodStringFormat",(e,t)=>{Cn.init(e,t),Ai.init(e,t)}),Oi=/*@__PURE__*/De("ZodEmail",(e,t)=>{$n.init(e,t),Ni.init(e,t)}),Pi=/*@__PURE__*/De("ZodGUID",(e,t)=>{Tn.init(e,t),Ni.init(e,t)}),Ri=/*@__PURE__*/De("ZodUUID",(e,t)=>{An.init(e,t),Ni.init(e,t)}),Li=/*@__PURE__*/De("ZodURL",(e,t)=>{Mn.init(e,t),Ni.init(e,t)}),ji=/*@__PURE__*/De("ZodEmoji",(e,t)=>{Nn.init(e,t),Ni.init(e,t)}),Di=/*@__PURE__*/De("ZodNanoID",(e,t)=>{On.init(e,t),Ni.init(e,t)}),Hi=/*@__PURE__*/De("ZodCUID",(e,t)=>{Pn.init(e,t),Ni.init(e,t)}),Zi=/*@__PURE__*/De("ZodCUID2",(e,t)=>{Rn.init(e,t),Ni.init(e,t)}),Fi=/*@__PURE__*/De("ZodULID",(e,t)=>{Ln.init(e,t),Ni.init(e,t)}),Ui=/*@__PURE__*/De("ZodXID",(e,t)=>{jn.init(e,t),Ni.init(e,t)}),Bi=/*@__PURE__*/De("ZodKSUID",(e,t)=>{Dn.init(e,t),Ni.init(e,t)}),Wi=/*@__PURE__*/De("ZodIPv4",(e,t)=>{Bn.init(e,t),Ni.init(e,t)}),qi=/*@__PURE__*/De("ZodIPv6",(e,t)=>{Wn.init(e,t),Ni.init(e,t)}),Vi=/*@__PURE__*/De("ZodCIDRv4",(e,t)=>{qn.init(e,t),Ni.init(e,t)}),Gi=/*@__PURE__*/De("ZodCIDRv6",(e,t)=>{Vn.init(e,t),Ni.init(e,t)}),Ji=/*@__PURE__*/De("ZodBase64",(e,t)=>{Jn.init(e,t),Ni.init(e,t)}),Ki=/*@__PURE__*/De("ZodBase64URL",(e,t)=>{Kn.init(e,t),Ni.init(e,t)}),Yi=/*@__PURE__*/De("ZodE164",(e,t)=>{Yn.init(e,t),Ni.init(e,t)}),Xi=/*@__PURE__*/De("ZodJWT",(e,t)=>{Xn.init(e,t),Ni.init(e,t)}),Qi=/*@__PURE__*/De("ZodNumber",(e,t)=>{Qn.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:i,maximum:o,format:a,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number";const d="number"==typeof l&&l>=(i??Number.NEGATIVE_INFINITY),u="number"==typeof c&&c<=(o??Number.POSITIVE_INFINITY),p="draft-04"===t.target||"openapi-3.0"===t.target;d?p?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof i&&(r.minimum=i),u?p?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c:"number"==typeof o&&(r.maximum=o),"number"==typeof s&&(r.multipleOf=s)})(e,t,n),Ci(e,"ZodNumber",{gt(e,t){return this.check(Ur(e,t))},gte(e,t){return this.check(Br(e,t))},min(e,t){return this.check(Br(e,t))},lt(e,t){return this.check(Zr(e,t))},lte(e,t){return this.check(Fr(e,t))},max(e,t){return this.check(Fr(e,t))},int(e){return this.check(no(e))},safe(e){return this.check(no(e))},positive(e){return this.check(Ur(0,e))},nonnegative(e){return this.check(Br(0,e))},negative(e){return this.check(Zr(0,e))},nonpositive(e){return this.check(Fr(0,e))},multipleOf(e,t){return this.check(Wr(e,t))},step(e,t){return this.check(Wr(e,t))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function eo(e){return function(e,t){return new e({type:"number",checks:[],...ct(t)})}(Qi,e)}var to=/*@__PURE__*/De("ZodNumberFormat",(e,t)=>{er.init(e,t),Qi.init(e,t)});function no(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ct(t)})}(to,e)}var ro=/*@__PURE__*/De("ZodBoolean",(e,t)=>{tr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function io(e){return function(e,t){return new e({type:"boolean",...ct(t)})}(ro,e)}var oo=/*@__PURE__*/De("ZodUnknown",(e,t)=>{nr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function ao(){return new oo({type:"unknown"})}var so=/*@__PURE__*/De("ZodNever",(e,t)=>{rr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function co(e){return function(e,t){return new e({type:"never",...ct(t)})}(so,e)}var lo=/*@__PURE__*/De("ZodDate",(e,t)=>{ir.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")})(0,e),e.min=(t,n)=>e.check(Br(t,n)),e.max=(t,n)=>e.check(Fr(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null}),uo=/*@__PURE__*/De("ZodArray",(e,t)=>{ar.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;"number"==typeof a&&(i.minItems=a),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=Xr(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,Ci(e,"ZodArray",{min(e,t){return this.check(Vr(e,t))},nonempty(e){return this.check(Vr(1,e))},max(e,t){return this.check(qr(e,t))},length(e,t){return this.check(Gr(e,t))},unwrap(){return this.element}})});function po(e,t){return function(e,t,n){return new e({type:"array",element:t,...ct(n)})}(uo,e,t)}var ho=/*@__PURE__*/De("ZodObject",(e,t)=>{ur.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const a=o.shape;for(const l in a)i.properties[l]=Xr(a[l],t,{...r,path:[...r.path,"properties",l]});const s=new Set(Object.keys(a)),c=new Set([...s].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(i.required=Array.from(c)),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Xr(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),Ke(e,"shape",()=>t.shape),Ci(e,"ZodObject",{keyof(){return vo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:ao()})},loose(){return this.clone({...this._zod.def,catchall:ao()})},strict(){return this.clone({...this._zod.def,catchall:co()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!rt(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return st(e,Xe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ye(this,"shape",n),n}}))}(this,e)},safeExtend(e){return function(e,t){if(!rt(t))throw new Error("Invalid input to safeExtend: expected a plain object");return st(e,Xe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ye(this,"shape",n),n}}))}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return st(e,Xe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Ye(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return st(e,Xe(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Ye(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return st(e,Xe(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Ye(this,"shape",r),r},checks:[]}))}(this,e)},partial(...e){return function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return st(t,Xe(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Ye(this,"shape",i),i},checks:[]}))}(_o,this,e[0])},required(...e){return t=Ao,n=this,r=e[0],st(n,Xe(n._zod.def,{get shape(){const e=n._zod.def.shape,i={...e};if(r)for(const n in r){if(!(n in i))throw new Error(`Unrecognized key: "${n}"`);r[n]&&(i[n]=new t({type:"nonoptional",innerType:e[n]}))}else for(const n in e)i[n]=new t({type:"nonoptional",innerType:e[n]});return Ye(this,"shape",i),i}}));var t,n,r}})});function mo(e,t){return new ho({type:"object",shape:e??{},...ct(t)})}var fo=/*@__PURE__*/De("ZodUnion",(e,t)=>{hr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=!1===i.inclusive,a=i.options.map((e,n)=>Xr(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options});var go=/*@__PURE__*/De("ZodIntersection",(e,t)=>{mr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Xr(i.left,t,{...r,path:[...r.path,"allOf",0]}),a=Xr(i.right,t,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length;n.allOf=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]]})(e,t,n,r)});var wo=/*@__PURE__*/De("ZodRecord",(e,t)=>{wr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const a=o.keyType,s=a._zod.bag?.patterns;if("loose"===o.mode&&s&&s.size>0){const e=Xr(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of s)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=Xr(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Xr(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=a._zod.values;if(c){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function bo(e,t,n){return t&&t._zod?new wo({type:"record",keyType:e,valueType:t,...ct(n)}):new wo({type:"record",keyType:Mi(),valueType:e,...ct(t)})}var yo=/*@__PURE__*/De("ZodEnum",(e,t)=>{br.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Be(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const o of e){if(!n.has(o))throw new Error(`Key ${o} not found in enum`);i[o]=t.entries[o]}return new yo({...t,checks:[],...ct(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new yo({...t,checks:[],...ct(r),entries:i})}});function vo(e,t){return new yo({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...ct(t)})}var xo=/*@__PURE__*/De("ZodLiteral",(e,t)=>{yr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(void 0===o){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof o){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});var ko=/*@__PURE__*/De("ZodTransform",(e,t)=>{vr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Ze(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(gt(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(gt(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});var _o=/*@__PURE__*/De("ZodOptional",(e,t)=>{kr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ii(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function So(e){return new _o({type:"optional",innerType:e})}var zo=/*@__PURE__*/De("ZodExactOptional",(e,t)=>{_r.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ii(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Eo=/*@__PURE__*/De("ZodNullable",(e,t)=>{Sr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Xr(i.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Eo({type:"nullable",innerType:e})}var Co=/*@__PURE__*/De("ZodDefault",(e,t)=>{zr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var To=/*@__PURE__*/De("ZodPrefault",(e,t)=>{Ir.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Ao=/*@__PURE__*/De("ZodNonOptional",(e,t)=>{Cr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var $o=/*@__PURE__*/De("ZodCatch",(e,t)=>{Ar.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let o;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var Mo=/*@__PURE__*/De("ZodPipe",(e,t)=>{$r.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),a="input"===t.io?o?i.out:i.in:i.out;Xr(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function No(e,t){return new Mo({type:"pipe",in:e,out:t})}var Oo=/*@__PURE__*/De("ZodReadonly",(e,t)=>{Nr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Po=/*@__PURE__*/De("ZodCustom",(e,t)=>{Rr.init(e,t),Ti.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});function Ro(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...ct(t)})}(Qi,e)}function Lo(e){return function(e,t){return new e({type:"date",coerce:!0,...ct(t)})}(lo,e)}var jo,Do=vo(["created","active","suspended","pending_approval"]),Ho=mo({id:eo().optional(),created_at:Lo().optional(),updated_at:Lo().optional()}),Zo=(mo({id:Ro()}),mo({slug:Mi()}),mo({widget_id:Ro()}),mo({simulation_id:Ro()}),mo({application_id:Ro()}),mo({user_id:Ro()}),mo({limit:Ro().optional().default(50),offset:Ro().optional().default(0)}),mo({success:function(e,t){return new xo({type:"literal",values:Array.isArray(e)?e:[e],...ct(t)})}(!0)})),Fo=(Zo.extend({message:Mi()}),mo({name:Mi().min(1),params:bo(Mi(),ao()).default({}),result:bo(Mi(),ao()).default({})}),Mi().url().refine(e=>/^https:\/\/hooks\.slack\.com\//.test(e),{message:"Slack webhook URL must start with https://hooks.slack.com/"}),mo({start:Mi(),end:Mi(),action:Mi()}).passthrough()),Uo=mo({id:Mi(),label:Mi(),purpose:Mi(),elements:po(bo(Mi(),ao())).default([]),bbox:bo(Mi(),ao()).default({}),screenshot:Mi().default(""),embedding:po(eo()).nullish()}).passthrough(),Bo=mo({id:Mi(),title:Mi(),url:Mi(),summary:Mi().default(""),screenshot:Mi().default(""),sections:po(Uo).default([]),sequence_ids:po(eo()).default([]),embedding:po(eo()).nullish()}).passthrough(),Wo=(mo({nodes:po(Bo),edges:po(Fo)}),vo(["free","startup","growth","enterprise"])),qo=vo(["document","video"]),Vo=vo(["user","research"]),Go=vo(["queued","running","creating_knowledge","has_question","completed","failed","stopped"]),Jo=vo(["pending","generating","completed","failed"]),Ko=vo(["app","website"]),Yo=vo(["widget"]),Xo=(vo(["tell","show","do"]),vo(["password","oauth"])),Qo=(Ho.extend({is_super:io(),status:Do,email:Mi().email(),external_id:Mi().nullish(),first_name:Mi().nullish(),last_name:Mi().nullish(),password:Mi().nullish(),image_url:Mi().nullish(),last_login_at:Lo().nullish(),auth_method:Xo.nullish()}),Ho.extend({name:Mi(),slug:Mi(),status:Do,package:Wo,ending_date:Lo().nullish(),external_workspace_id:Mi().nullish(),slack_webhook_configured:io().optional(),notify_all_members_on_question:io().optional()}),Ho.extend({workspace_id:eo(),application_id:eo().optional(),file_name:Mi().min(1),file_size:Ro(),file_type:qo,file_url:Mi(),source_url:Mi().nullish(),source:Vo.default("user").optional()}),vo(["desktop","tablet","mobile"])),ea=vo(["positive","neutral","negative"]),ta=mo({step_index:eo(),screenshot_ref:Mi().nullable(),reaction:Mi(),sentiment:ea}),na=mo({id:eo(),run_id:eo().nullable(),persona_id:eo().nullable(),user_index:eo().nullable(),simulation_id:eo().nullable(),study_variant_id:eo().nullable(),study_task_id:eo().nullable(),journey_reaction:Mi().nullable(),journey_sentiment:ea.nullable(),status:vo(["pending","completed","failed"]),step_reactions:po(ta).default([]),question_answers:po(mo({study_question_id:eo(),answer:Mi()})).default([])}),ra=(Ho.extend({application_id:eo(),job_id:Mi(),browser_session_id:Mi().nullish(),status:Go,status_message:Mi(),path:Mi().nullish(),instructions:Mi(),name:Mi().nullish(),type:vo(["direct","uxr","survey","abtest","qa"]),pinned:io().optional(),source:vo(["direct","qa"]).optional(),graph_id:Mi().nullish(),source_metadata:bo(Mi(),ao()).nullish(),step_count:eo().int().nonnegative().nullish(),started_at:Lo().nullish(),completed_at:Lo().nullish(),output_persisted_at:Lo().nullish(),graph_status:Jo.optional(),graph_steps_processed:eo().int().nonnegative().optional(),graph_steps_total:eo().int().nonnegative().optional(),graph_error:Mi().nullish(),created_by_user_id:eo().nullish(),has_question:io().optional(),participants:po(mo({persona_id:eo(),user_count:eo().int().positive()})).default([]),reactions:po(na).default([]),driver_persona_id:eo().nullable().default(null),viewport:Qo.default("desktop")}),Ho.extend({workspace_id:eo(),name:Mi(),slug:Mi(),type:Ko,url:Mi(),username:Mi().nullish(),password:Mi().nullish(),allowed_domains:po(Mi()).default([])}).omit({password:!0}),mo({chip_mode:vo(["show","tell","do"]),chip_text:Mi()})),ia=mo({widget_enabled:io(),widget_appearance:vo(["default","compact","full"]),widget_position:vo(["bottom_left","bottom_right","top_left","top_right"]),widget_device:vo(["desktop","mobile","desktop_mobile"]),widget_header:Mi(),widget_body:Mi(),widget_greeting:Mi(),widget_feature_tell:io(),widget_feature_show:io(),widget_feature_do:io(),widget_feature_human:io(),widget_background_color:Mi(),widget_text_color:Mi(),widget_border_color:Mi(),widget_accent_color:Mi(),widget_secondary_color:Mi(),widget_border_radius:Mi(),widget_font_size:Mi(),widget_width:Mi(),widget_height:Mi(),widget_shadow:Mi(),widget_animation_duration:Mi(),widget_fade_duration:Mi(),widget_bounce_effect:io(),widget_chips:po(ra)}),oa=(Ho.extend({application_id:eo(),type:Yo,settings:ia,status:Do,marketrix_id:Mi(),marketrix_key:Mi(),snippet:Mi().nullish()}),Ho.extend({widget_id:eo(),url_pattern:Mi(),message:po(Mi()),description:Mi().optional()}),vo(["running","finalizing","completed","failed","stopped"]),vo(["passed","failed","indecisive"]),vo(["passed","failed"]),vo(["user_login","url_visit","update_workspace","create_user","update_user","delete_user","create_application","update_application","delete_application","create_widget","update_widget","delete_widget","create_knowledge","update_knowledge","delete_knowledge","approve_user","deny_user","request_workspace","widget_question","qa_run_started","start_simulation","create_workflow","update_workflow","delete_workflow","toggle_workflow","slack_command"])),aa=mo({details:Mi().optional(),id:eo().optional(),type:Mi().optional(),name:Mi().optional(),target_user_id:eo().optional(),target_user_email:Mi().optional(),reason:Mi().optional(),assigned_role:Mi().optional(),new_role:Mi().optional(),previous_role:Mi().optional(),workspace_name:Mi().optional(),workspace_slug:Mi().optional(),ip_address:Mi().optional(),user_agent:Mi().optional(),widget_type:Mi().optional(),created_by:eo().optional()}).passthrough(),sa=(Ho.extend({workspace_id:eo(),user_id:eo().nullable(),type:oa,metadata:aa.optional()}).partial().extend({type:oa}),null),ca="";function la(e){return ge(new je({url:e,headers:()=>{const e={};return sa&&(e.Authorization=`Bearer ${sa}`),e}}))}jo=la("");var da=e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==ca&&(ca=e,jo=la(e))},ua={setAuthToken:e=>{sa=e},clearAuthToken:()=>{sa=null},getAuthToken:()=>sa,configure:da},pa=new Proxy({},{get:(e,t)=>t in ua?ua[t]:jo[t]}),ha="undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname&&!window.location.hostname.includes("localhost")?"error":"debug",ma={debug:0,info:1,warn:2,error:3};function fa(e){return ma[e]>=ma[ha]}var ga=[{id:"navigate",name:"Navigate",description:"Navigate to a URL",displayAction:"Navigating",category:"navigation",actionType:"navigate"},{id:"search",name:"Search",description:"Search the web using a search engine",displayAction:"Searching",category:"navigation",actionType:"search"},{id:"click_element",name:"Click Element",description:"Click on an element by index or coordinates",displayAction:"Clicking element",category:"interaction",actionType:"click_element"},{id:"type_text",name:"Type Text",description:"Type text into an input field",displayAction:"Typing text",category:"interaction",actionType:"type_text"},{id:"scroll",name:"Scroll",description:"Scroll the page up or down",displayAction:"Scrolling",category:"interaction",actionType:"scroll"},{id:"scroll_to_text",name:"Scroll to Text",description:"Scroll until text is visible",displayAction:"Scrolling to text",category:"interaction",actionType:"scroll_to_text"},{id:"send_keys",name:"Send Keys",description:"Send keyboard keys or shortcuts",displayAction:"Pressing key",category:"interaction",actionType:"send_keys"},{id:"extract",name:"Extract",description:"Extract content from the page",displayAction:"Extracting content",category:"extraction",actionType:"extract"},{id:"get_dropdown_options",name:"Get Dropdown Options",description:"Get available options from a dropdown",displayAction:"Reading dropdown options",category:"extraction",actionType:"get_dropdown_options"},{id:"select_dropdown_option",name:"Select Dropdown Option",description:"Select an option from a dropdown",displayAction:"Selecting option",category:"interaction",actionType:"select_dropdown_option"},{id:"upload_file",name:"Upload File",description:"Upload a file to an input field",displayAction:"Uploading file",category:"interaction",actionType:"upload_file"},{id:"go_back",name:"Go Back",description:"Browser back button",displayAction:"Going back",category:"navigation",actionType:"go_back"},{id:"wait",name:"Wait",description:"Wait for a specified duration",displayAction:"Waiting",category:"utility",actionType:"wait"},{id:"switch_tab",name:"Switch Tab",description:"Switch to a different browser tab",displayAction:"Switching tab",category:"utility",actionType:"switch_tab"},{id:"close_tab",name:"Close Tab",description:"Close the current browser tab",displayAction:"Closing tab",category:"utility",actionType:"close_tab"},{id:"done",name:"Done",description:"Mark task as complete",displayAction:"Done",category:"utility",actionType:"done"},{id:"get_html",name:"Get HTML",description:"Get full page HTML with data-id attributes",displayAction:"Viewed your screen",category:"extraction",actionType:"get_html"},{id:"get_interactable_elements",name:"Get Interactable Elements",description:"Get list of interactable elements",displayAction:"Scanning elements",category:"extraction",actionType:"get_interactable_elements"},{id:"get_screenshot",name:"Get Screenshot",description:"Capture a screenshot of the page",displayAction:"Taking screenshot",category:"extraction",actionType:"get_screenshot"}];function wa(e){return e.includes("__THINKING__")}function ba(e){return wa(e)?e:`${e}\n\n__THINKING__`}function ya(e,t,n,r,i){if("agent"!==e.sender||e.isSystemMessage||e.isScreenAccessRequest)return!1;if(i&&t&&("show"===n||"do"===n))if(e.isPlaceholder){if(void 0!==e.mode&&e.mode!==n)return!1}else if(e.mode!==n)return!1;if(r){const t=e.content.trim().length>0,n=e.parts&&e.parts.length>0;if(!t&&!n)return!1}return!0}function va(e){const{messages:t,isSimulationRunning:n,currentMode:r,requireContent:i}=e;let o=-1;if(n&&("show"===r||"do"===r)){const e=!0;for(let a=t.length-1;a>=0;a--){const s=t[a],c=ya(s,n,r,i,e),l=s.isPlaceholder,d=!i||s.content.trim().length>0||s.parts&&s.parts.length>0;if(c&&l&&d){o=a;break}}if(o<0&&!i)for(let a=t.length-1;a>=0;a--){const s=t[a],c=ya(s,n,r,i,e),l=s.isPlaceholder;if(c&&l){o=a;break}}if(o<0)for(let a=t.length-1;a>=0;a--){const s=t[a],c=ya(s,n,r,i,e),l=s.isPlaceholder;if(c&&!l){o=a;break}}}if(o<0){for(let e=t.length-1;e>=0;e--){const n=t[e],r="agent"===n.sender,a=n.isPlaceholder,s=!n.isSystemMessage,c=!n.isScreenAccessRequest,l=!i||n.content.trim().length>0||n.parts&&n.parts.length>0;if(r&&a&&s&&c&&l){o=e;break}}if(o<0&&!i)for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&n.isPlaceholder&&!n.isSystemMessage&&!n.isScreenAccessRequest){o=e;break}}if(o<0&&(o=function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("agent"===n.sender&&!n.isSystemMessage&&!n.isScreenAccessRequest&&!n.isPlaceholder)return t}return-1}(t)),o<0)for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&!n.isSystemMessage&&!n.isScreenAccessRequest){o=e;break}}}return o>=0?{index:o,message:t[o]}:null}function xa(e){const t={...e};if(!t.parts){t.parts=[];const e=t.content.replace(/\n\n__THINKING__$/,"").trim();e&&t.parts.push({type:"text",content:e})}return t}var ka=/* @__PURE__ */new Set(["click_element","type_text","send_keys","select_dropdown_option","upload_file","scroll"]),_a=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys","upload_file"]);function Sa(e){return e?e.replace(/\(Cancelled by cleanup\)/gi,"").replace(/\(cancelled by cleanup\)/gi,"").replace(/Cancelled by cleanup/gi,"").replace(/\s+/g," ").trim():e}function za(e,t,n,r=!1){const i=xa(e);if(!t||"show"!==n&&"do"!==n)return wa(i.content)?{...i,content:i.content.replace(/\n\n__THINKING__$/,"").replace(/__THINKING__/g,""),placeholderState:void 0}:i;const o=r?"waiting-for-user":"thinking";return wa(i.content)?i.placeholderState!==o?{...i,placeholderState:o}:i:{...i,content:ba(i.content),placeholderState:o}}var Ea=Object.fromEntries(ga.map(e=>[e.id,e.displayAction]));var Ia="marketrix_chat_context",Ca={chat_id:null,messages:[],isSimulationRunning:!1,activeSimulationId:null,currentMode:"tell",isOpen:!1,isMinimized:!1,isLoading:!1,config:null,timestamp:Date.now()},Ta=class e{static instance;context=null;constructor(){this.loadContext()}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadContext(){if("undefined"==typeof window)return this.context={...Ca},this.context;try{const e=localStorage.getItem(Ia);if(e){const t=JSON.parse(e);return Date.now()-t.timestamp>6048e5?(this.context={...Ca},this.saveContext(),this.context):(this.context=t,this.context)}}catch(e){}return this.context={...Ca},this.context}saveContext(){if("undefined"!=typeof window&&this.context)try{this.context.timestamp=Date.now(),localStorage.setItem(Ia,JSON.stringify(this.context))}catch(e){}}getContext(){return this.context?this.context:this.loadContext()}updateContext(e){this.context||this.loadContext();const t=this.context;this.context={...t,...e},this.saveContext()}isValidChatId(e){return"string"==typeof e&&""!==e.trim()}getChatId(){if("undefined"!=typeof window&&this.isValidChatId(window.name)){const e=window.name;return e!==this.getContext().chat_id&&this.updateContext({chat_id:e}),e}return this.getContext().chat_id}setChatId(e){this.updateContext({chat_id:e}),"undefined"!=typeof window&&e&&(window.name=e,window.dispatchEvent(new CustomEvent("marketrix:chatid",{detail:{chatId:e}})))}getMessages(){return this.getContext().messages}setMessages(e){this.updateContext({messages:e})}getChatState(){const e=this.getContext();return{isSimulationRunning:e.isSimulationRunning,activeSimulationId:e.activeSimulationId,currentMode:e.currentMode,isOpen:e.isOpen,isMinimized:e.isMinimized,isLoading:e.isLoading}}setChatState(e){this.updateContext(e)}getConfig(){return this.getContext().config}setConfig(e){this.updateContext({config:e})}clear(){this.context={...Ca},"undefined"!=typeof window&&localStorage.removeItem(Ia)}hasValidContext(){const e=this.getContext();return null!==e.chat_id&&e.chat_id.length>0}}.getInstance(),Aa=class e{static instance;chatId=null;initError=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.chatId=e}createInitialContext(e){try{if(Ta.hasValidContext())return;Ta.updateContext({chat_id:e,messages:[],isSimulationRunning:!1,activeSimulationId:null,currentMode:"tell",isOpen:!1,isMinimized:!1,isLoading:!1})}catch(t){this.initError=t instanceof Error?t:new Error(String(t))}}getInitError(){return this.initError}restore(){const e=Ta.getContext();return{messages:e.chat_id?e.messages.map(e=>{if(e.id.startsWith("screenshare-"))return{...e,content:"Screenshare ended",videoStream:void 0,isSystemMessage:!0,timestamp:new Date(e.timestamp),parts:[{type:"text",content:"Screenshare ended"}]};const t={...e,timestamp:new Date(e.timestamp),videoStream:void 0,placeholderState:e.placeholderState,simulationStatus:e.simulationStatus,parts:e.parts||[]};if(0===t.parts?.length&&t.content){const e=t.content.replace(/\n\n__THINKING__$/,"").trim();e&&t.parts&&t.parts.push({type:"text",content:e})}return t}):[],isSimulationRunning:e.isSimulationRunning,activeSimulationId:e.activeSimulationId,currentMode:e.currentMode,isOpen:e.isOpen,isMinimized:e.isMinimized,isLoading:e.isLoading??!1}}persist(e){if(this.chatId)try{const t=e.messages.filter(e=>!e.isPlaceholder||("thinking"===e.placeholderState||"waiting-for-user"===e.placeholderState||(e.parts||[]).length>0)).filter(e=>!(e.isSystemMessage&&"Chat context changed"===e.content)).map(e=>{return{id:e.id,content:(t=e.content,t.replace(/__THINKING__/g,"")),sender:e.sender,timestamp:e.timestamp.toISOString(),mode:e.mode,isScreenAccessRequest:e.isScreenAccessRequest,screenShareStatus:e.screenShareStatus,isSystemMessage:e.isSystemMessage,isPlaceholder:e.isPlaceholder,placeholderState:e.placeholderState,simulationStatus:e.simulationStatus,parts:e.parts};var t});Ta.updateContext({chat_id:this.chatId,messages:t,isSimulationRunning:e.isSimulationRunning,activeSimulationId:e.activeSimulationId,currentMode:e.currentMode,isOpen:e.isOpen,isMinimized:e.isMinimized,isLoading:e.isLoading})}catch(t){}}}.getInstance();function $a(e,t,n="user-message"){const r=[],i=e.trim();return i&&r.push({type:"text",content:i}),{id:`${n}-${Date.now()}`,content:i,sender:"user",timestamp:/* @__PURE__ */new Date,mode:t,parts:r}}function Ma(e,t,n,r="agent-message"){const i=[],o=e.trim();return o&&i.push({type:"text",content:o}),{id:n||`${r}-${Date.now()}`,content:e,sender:"agent",timestamp:/* @__PURE__ */new Date,mode:t,parts:i}}function Na(e,t,n="agent",r="system-message"){const i=[];return e&&i.push({type:"text",content:e}),{id:`${r}-${Date.now()}`,content:e,sender:n,timestamp:/* @__PURE__ */new Date,mode:t,isSystemMessage:!0,parts:i}}function Oa(e="show"){const t="Started screenshare";return{id:`started-screenshare-${Date.now()}`,content:t,sender:"user",timestamp:/* @__PURE__ */new Date,mode:e,isSystemMessage:!0,parts:[{type:"text",content:t}]}}function Pa(e,t="show"){return{id:`screenshare-${Date.now()}`,content:"",sender:"user",timestamp:/* @__PURE__ */new Date,mode:t,videoStream:e,parts:[]}}var Ra={debug:(e,...t)=>{fa("debug")},info:(e,...t)=>{fa("info")},warn:(e,...t)=>{fa("warn")},error:(e,...t)=>{fa("error")}},La=class e{static instance=null;chatId=null;initializationPromise=null;constructor(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.chatId=this.getStoredChatId(),this.chatId&&Ra.debug("Loaded existing chat ID from storage:",this.chatId))}static getInstance(){return"undefined"==typeof window||"undefined"==typeof document?(e.instance||(e.instance=Object.create(e.prototype),e.instance.chatId=null,e.instance.initializationPromise=null),e.instance):(e.instance||(e.instance=new e),e.instance)}getChatId(){return this.chatId}async getOrCreateChatId(){if(this.chatId)return Ra.debug("Returning existing chat ID:",this.chatId),this.chatId;if(this.initializationPromise)return Ra.debug("Chat ID initialization in progress, waiting..."),this.initializationPromise;const e=this.getStoredChatId();if(e)return this.chatId=e,Ra.debug("Found chat ID in storage:",this.chatId),this.chatId;this.initializationPromise=this.createChatId();try{return await this.initializationPromise}finally{this.initializationPromise=null}}async createChatId(){try{Ra.info("Creating new chat ID...");const e=await pa.chatCreate(void 0);if(!e)throw new Error("API returned empty chat ID");return this.chatId=e,this.storeChatId(e),Ra.info("Created and stored new chat ID:",this.chatId),Aa.createInitialContext(e),e}catch(e){throw Ra.error("Failed to create chat ID:",e),this.initializationPromise=null,e}}getStoredChatId(){return Ta.getChatId()}storeChatId(e){Ta.setChatId(e)}}.getInstance(),ja=class e{static instance=null;abortController=null;chatId=null;status="disconnected";callbacks=/* @__PURE__ */new Set;isIntentionallyDisconnected=!1;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;maxReconnectDelay=3e4;reconnectTimer=null;config;connectionId=0;tabId=globalThis.crypto.randomUUID();constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}addCallbacks(e){this.callbacks.add(e)}removeCallbacks(e){this.callbacks.delete(e)}getStatus(){return this.status}isConnected(){return"registered"===this.status}async connect(e,t){if(this.isIntentionallyDisconnected&&(this.isIntentionallyDisconnected=!1),this.chatId===e&&("connecting"===this.status||"connected"===this.status||"registered"===this.status))return;this.abortController&&(this.abortController.abort(),this.abortController=null),this.chatId=e,t&&(this.config=t),this.setStatus("connecting");const n=++this.connectionId;this.abortController=new AbortController;const r=this.abortController.signal;try{const t={chat_id:e,tab_id:this.tabId};this.config?.mtxId&&this.config?.mtxKey?(t.marketrix_id=this.config.mtxId,t.marketrix_key=this.config.mtxKey):this.config?.mtxApp&&(t.application_id=this.config.mtxApp);const i=await pa.widgetStream(t,{signal:r});this.setStatus("connected"),this.consumeEvents(i,n)}catch(i){r.aborted||(this.setStatus("error"),this.notifyError(/* @__PURE__ */new Error("Stream connection failed")),this.scheduleReconnect())}}async consumeEvents(e,t){let n=!1;try{for await(const r of e){if(this.connectionId!==t){n=!0;break}this.handleMessage(r)}}catch(r){this.connectionId!==t?n=!0:this.isIntentionallyDisconnected||this.setStatus("error")}finally{n||this.connectionId!==t||this.isIntentionallyDisconnected||(this.setStatus("disconnected"),this.scheduleReconnect())}}disconnect(){this.isIntentionallyDisconnected=!0,this.clearReconnectTimer(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.setStatus("disconnected"),this.chatId=null}send(e){return this.chatId?pa.widgetMessage({chat_id:this.chatId,tab_id:this.tabId,command:e}).then(()=>{}).catch(e=>{throw this.notifyError(/* @__PURE__ */new Error(`Failed to send message: ${String(e)}`)),e}):Promise.reject(/* @__PURE__ */new Error("No active chat"))}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(t=>t.onStatusChange?.(e)))}notifyError(e){this.callbacks.forEach(t=>t.onError?.(e))}handleMessage(e){this.isIntentionallyDisconnected||"heartbeat"!==e.type&&("registered"===e.type&&e.chat_id===this.chatId&&(this.setStatus("registered"),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.callbacks.forEach(t=>t.onRegistered?.(e.application_id))),"chat/error"===e.type&&"auth"===e.request_id&&(this.isIntentionallyDisconnected=!0),this.callbacks.forEach(t=>t.onMessage?.(e)))}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.notifyError(/* @__PURE__ */new Error("Max reconnect attempts reached"));this.clearReconnectTimer(),this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);this.reconnectTimer=setTimeout(()=>{!this.isIntentionallyDisconnected&&this.chatId&&this.connect(this.chatId,this.config).catch(console.error)},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},Da=class{config;constructor(e){this.config=e}getChatId(){return La.getChatId()}getUserId(){if(this.config.userId&&"number"==typeof this.config.userId)return this.config.userId;try{const e=localStorage.getItem("marketrix_user_id");if(e){const t=Number(e);if(!isNaN(t))return t}}catch(e){}try{const e=sessionStorage.getItem("marketrix_user_id");if(e){const t=Number(e);if(!isNaN(t))return t}}catch(e){}return null}async logWidgetQuestion(e,t){try{const n=this.getUserId(),r={question:e,mode:t,chat_id:this.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString()};null!==n&&(r.user_id=n),this.config.mtxApp&&(r.application_id=this.config.mtxApp),this.config.mtxId&&this.config.mtxKey&&(r.marketrix_id=this.config.mtxId,r.marketrix_key=this.config.mtxKey),pa.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>{})}catch(n){}}async messageDispatch(e){if(!(await La.getOrCreateChatId()))throw new Error("Failed to initialize chat session");const t=e.mode||"tell";if(e.message&&await this.logWidgetQuestion(e.message,t),!(this.config.mtxId&&this.config.mtxKey||this.config.mtxApp))throw new Error("Either mtxId + mtxKey or mtxApp is required");const n=e.requestId||`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r={type:`chat/${t}`,request_id:n,content:e.message||""};return ja.getInstance().send(r),{messageId:n,response:"",mode:t,timestamp:/* @__PURE__ */new Date}}updateConfig(e){this.config={...this.config,...e}}};function Ha(e){if(!(e&&e instanceof Element))return!1;try{const n=e.tagName.toLowerCase(),r="button"===n;if(!(r||"input"===n||"textarea"===n||"select"===n||"a"===n&&e.hasAttribute("href")||"button"===e.getAttribute("role")||"link"===e.getAttribute("role")||"textbox"===e.getAttribute("role")||"checkbox"===e.getAttribute("role")||"radio"===e.getAttribute("role")||"switch"===e.getAttribute("role")||"tab"===e.getAttribute("role")||"menuitem"===e.getAttribute("role")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||e.hasAttribute("tabindex")&&parseInt(e.getAttribute("tabindex")||"-1",10)>=0))return!1;const i=(t,n)=>{if(r){e.tagName,e.id,e.className}};if(!0===e.disabled)return i("disabled","button is disabled"),!1;if("true"===e.getAttribute("aria-disabled"))return i("aria-disabled","aria-disabled is true"),!1;try{let t=e;for(;t;){if(t instanceof HTMLElement&&t.inert)return i("inert","ancestor is inert"),!1;const e=t instanceof Element?t.getRootNode():null;t=t instanceof Element?t.parentElement||(e instanceof ShadowRoot?e.host:null):null}}catch(t){}const o=e.hasAttribute("onclick");if(r&&o)return!0;let a,s;try{a=window.getComputedStyle(e)}catch(t){return i("computed-style","failed to get computed style"),!1}if("none"===a.display)return i("display","display is none"),!1;if("none"===a.pointerEvents)return i("pointer-events","pointer-events is none"),!1;try{s=e.getBoundingClientRect()}catch(t){return i("bounding-rect","failed to get bounding rect"),!1}if(s.width<=0||s.height<=0)return i("dimensions",`width=${s.width}, height=${s.height}`),!1;try{let t=e;for(;t&&t!==document.body;){const e=t.getRootNode(),n=t.parentElement||(e instanceof ShadowRoot?e.host:null);if(!n)break;let o,a;try{o=window.getComputedStyle(n),a=n.getBoundingClientRect()}catch{t=n;continue}if("hidden"===o.overflow||"clip"===o.overflow){const e=s.right<a.left||s.left>a.right||s.bottom<a.top||s.top>a.bottom;if(r){if(e)return i("overflow-clipping","completely outside parent bounds"),!1}else if(e)return!1}t=n}}catch(t){}try{let t=e.getRootNode();for(;t instanceof ShadowRoot;){const e=t.host;let n;try{n=e.getBoundingClientRect()}catch{break}if(n.width<=0||n.height<=0)return!1;t=e.getRootNode()}}catch(t){}return!0}catch(t){return!1}}var Za=class e{static instance;elementMap=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;selectorMap=/* @__PURE__ */new Map;fingerprintMap=/* @__PURE__ */new Map;indexingInProgress=!1;indexVersion=0;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}generateSelector(e){if(e.id&&1===document.querySelectorAll(`#${CSS.escape(e.id)}`).length)return`#${CSS.escape(e.id)}`;const t=[];let n=e;for(;n&&n!==document.body&&n.parentElement;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${CSS.escape(n.id)}`,t.unshift(e);break}{const t=n.parentElement;if(!t)break;const r=n.tagName,i=Array.from(t.children).filter(e=>e.tagName===r);if(i.length>1){e+=`:nth-of-type(${i.indexOf(n)+1})`}}t.unshift(e),n=n.parentElement}return t.join(" > ")}generateFingerprint(e,t){return{tagName:e.tagName,id:e.id||null,textContent:((e,t=100)=>{if(!e)return null;const n=e.trim().replace(/\s+/g," ");return n.length>t?n.slice(0,t):n})(e.textContent),type:e.getAttribute("type"),role:e.getAttribute("role"),ariaLabel:e.getAttribute("aria-label"),name:e.getAttribute("name"),href:e.getAttribute("href"),selector:t,indexVersion:this.indexVersion}}matchesFingerprint(e,t){return e.tagName===t.tagName&&(!(!t.id||e.id!==t.id)||(!t.type||e.getAttribute("type")===t.type)&&((!t.ariaLabel||e.getAttribute("aria-label")===t.ariaLabel)&&((!t.role||e.getAttribute("role")===t.role)&&((!t.href||"A"!==t.tagName||e.getAttribute("href")===t.href)&&(!t.name||e.getAttribute("name")===t.name)))))}validateElementAtIndex(e){const t=this.fingerprintMap.get(e);if(!t)return{isValid:!0};const n=this.elementMap.get(e);return n&&document.contains(n)?n instanceof HTMLElement&&!this.matchesFingerprint(n,t)?{isValid:!1,mismatchReason:"element_changed"}:{isValid:!0}:{isValid:!1,mismatchReason:"element_removed"}}indexInteractableElements(){if(this.indexingInProgress)return[];try{this.indexingInProgress=!0,this.clearIndex();const e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{if(e instanceof HTMLElement&&null===e.offsetParent&&"BODY"!==e.tagName){const t=window.getComputedStyle(e),n="fixed"===t.position||"sticky"===t.position;if("none"===t.display)return NodeFilter.FILTER_REJECT;if(!n){let t=e.parentElement,n=!1;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if("fixed"===e.position||"sticky"===e.position){n=!0;break}t=t.parentElement}if(!n)return NodeFilter.FILTER_REJECT}}return NodeFilter.FILTER_ACCEPT}});let t=e.nextNode(),n=0;const r=[];for(;t;){if(t instanceof HTMLElement){const e=t.matches('a[href], button, input, textarea, select, [role="button"]'),i=t.classList.contains("cursor-pointer")||t.classList.contains("clickable"),o="onclick"in t&&"function"==typeof t.onclick;if(e||i||o||Ha(t)){this.elementMap.set(n,t),this.elementToSequence.set(t,n);const e=this.generateSelector(t);this.selectorMap.set(n,e);const i=this.generateFingerprint(t,e);this.fingerprintMap.set(n,i),r.push([n,t]),n++}}t=e.nextNode()}return this.indexVersion++,r}finally{this.indexingInProgress=!1}}getElementCoordinates(e){const t=e.getBoundingClientRect(),n=this.calculateGlobalZOrder(e);return{x:Math.round(t.left),y:Math.round(t.top),w:Math.round(t.width),h:Math.round(t.height),z:n}}isStackingContext(e){const t=window.getComputedStyle(e),n=t.position;if(("fixed"===n||"absolute"===n||"relative"===n||"sticky"===n)&&"auto"!==t.zIndex)return!0;if("auto"!==t.zIndex&&e.parentElement){const t=window.getComputedStyle(e.parentElement).display;if("flex"===t||"inline-flex"===t||"grid"===t||"inline-grid"===t)return!0}const r=parseFloat(t.opacity);if(!isNaN(r)&&r<1)return!0;if(t.transform&&"none"!==t.transform)return!0;if(t.filter&&"none"!==t.filter)return!0;const i=t.willChange;if(i&&(i.includes("transform")||i.includes("opacity")))return!0;if("isolate"===t.isolation)return!0;const o=t.contain;return!(!o||!(o.includes("layout")||o.includes("style")||o.includes("paint")))}calculateGlobalZOrder(e){let t=e;const n=[];for(;t&&t!==document.body&&t.parentElement;){const e=window.getComputedStyle(t);if(this.isStackingContext(t)){let r=0;if("auto"!==e.zIndex){const t=parseInt(e.zIndex,10);isNaN(t)||(r=t)}let i=0;t.parentElement&&(i=Array.from(t.parentElement.children).indexOf(t)),n.push({element:t,zIndex:r,domOrder:i})}t=t.parentElement}let r=1e6;for(let i=n.length-1;i>=0;i--){const e=n[i];r+=1e4*e.zIndex+e.domOrder}if(e.parentElement){r+=Array.from(e.parentElement.children).indexOf(e)}return r}getSnapshotHtml(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,r]of this.elementMap.entries())if(r instanceof HTMLElement){const i=this.selectorMap.get(n);if(i)try{const t=(e.querySelector("body")||e).querySelector(i);if(t)if(t.setAttribute("data-id",n.toString()),"none"===window.getComputedStyle(r).display)t.setAttribute("data-x","0"),t.setAttribute("data-y","0"),t.setAttribute("data-w","0"),t.setAttribute("data-h","0"),t.setAttribute("data-z","0");else{const e=this.getElementCoordinates(r);t.setAttribute("data-x",e.x.toString()),t.setAttribute("data-y",e.y.toString()),t.setAttribute("data-w",e.w.toString()),t.setAttribute("data-h",e.h.toString()),t.setAttribute("data-z",e.z.toString())}}catch(t){}}return e.outerHTML}getInteractableElements(){this.indexInteractableElements();const e=[];for(const[t,n]of this.elementMap.entries())if(n instanceof HTMLElement){const r=this.fingerprintMap.get(t);r&&e.push({index:t,fingerprint:r,coords:this.getElementCoordinates(n),cssClasses:Array.from(n.classList)})}return e}getSequenceForElement(e){return this.elementToSequence.get(e)}clearIndex(){this.elementMap.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap,this.fingerprintMap.clear()}checkInteractability(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=window.getComputedStyle(e);if("none"===n.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===n.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(n.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const r=e.getBoundingClientRect();if(0===r.width||0===r.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;if(r.bottom<0||r.top>window.innerHeight||r.right<0||r.left>window.innerWidth)return`ELEMENT_NOT_INTERACTABLE: Element ${t} is off-screen`;const i=r.left+r.width/2,o=r.top+r.height/2,a=document.elementFromPoint(i,o);if(a&&a!==e&&!e.contains(a)&&!(a.closest("#marketrix-show-highlight")||a.closest("#marketrix-show-popup")||a.closest("[data-marketrix-widget]"))){const e=a.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${a.className?`${e}.${a.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}checkElementInteractable(e,t){return this.checkInteractability(e,t)}getElementByIndex(e){let t=null;if(this.elementMap.has(e)){const n=this.elementMap.get(e);n&&n instanceof HTMLElement&&(t=n)}if(!t&&this.selectorMap.has(e)){const n=this.selectorMap.get(e);if(n)try{const e=document.querySelector(n);e&&e instanceof HTMLElement&&(t=e)}catch(r){}}if(!t)return{element:null,error:`Element ${e} not found`};const n=this.checkInteractability(t,e);return n?{element:null,error:n}:{element:t}}getValidatedElement(e){const t=this.validateElementAtIndex(e);if(!t.isValid)return{element:null,validation:t,error:`DOM_CHANGED: Element at index ${e} ${"element_removed"===t.mismatchReason?"no longer exists":"has changed"}. Call get_html to get updated indices.`};const n=this.elementMap.get(e);if(!n)return{element:null,validation:t,error:`Element ${e} not found`};const r=this.checkInteractability(n,e);return r?{element:null,validation:t,error:r}:{element:n,validation:t}}}.getInstance(),Fa=null;async function Ua(){if(Fa?.active){const e=Fa.getVideoTracks();if(e.length>0&&"live"===e[0].readyState)return Fa}const e=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!e||0===e.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return Fa=e,e.getVideoTracks()[0].addEventListener("ended",()=>{Fa=null}),e}function Ba(){return null!==function(){if(Fa?.active){const e=Fa.getVideoTracks();if(e.length>0&&"live"===e[0].readyState)return Fa}return Fa=null,null}()}var Wa=class e{static instance;currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;updateHighlightPosition=null;rafId=null;mutationObserver=null;visibilityCheckInterval=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:i}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===i&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.createHighlight(t),this.createPopup(n,r),this.setupPositionUpdates(),this.setupElementMonitoring(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t}).finally(()=>{this.cleanup()})),this.currentPromise}cleanup(){this.rejectPromise&&(this.rejectPromise("Cancelled by cleanup"),this.rejectPromise=null),this.resolvePromise=null,this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler&&(window.removeEventListener("scroll",this.scrollHandler,{capture:!0}),window.removeEventListener("resize",this.scrollHandler),window.removeEventListener("touchmove",this.scrollHandler),window.removeEventListener("wheel",this.scrollHandler),this.scrollHandler=null),null!==this.rafId&&(window.cancelAnimationFrame(this.rafId),this.rafId=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.updateHighlightPosition=null,this.currentPopup&&(this.currentPopup.remove(),this.currentPopup=null),this.currentHighlight&&(this.currentHighlight.remove(),this.currentHighlight=null);const e=document.getElementById("marketrix-show-popup");e&&e.remove();const t=document.getElementById("marketrix-show-highlight");t&&t.remove(),this.currentElement=null,this.currentOptions=null,this.currentPromise=null,this.resolvePromise=null,this.rejectPromise=null}createHighlight(e){const t=e.getBoundingClientRect(),n=document.createElement("div");n.id="marketrix-show-highlight",n.style.cssText=`\n position: fixed;\n top: ${t.top}px;\n left: ${t.left}px;\n width: ${t.width}px;\n height: ${t.height}px;\n border: 3px solid #3b82f6;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2), 0 0 20px rgba(59, 130, 246, 0.4);\n z-index: 2147483645;\n pointer-events: none;\n transition: none;\n `,document.body.appendChild(n),this.currentHighlight=n}createPopup(e,t){const n=document.createElement("div");n.id="marketrix-show-popup",n.innerHTML=t?`<div style="font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>`:`<div style="margin-bottom: 12px; font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>\n <div style="display: flex; gap: 8px; justify-content: flex-end;">\n <button id="marketrix-show-continue" style="\n background: #3b82f6; color: white; border: none; border-radius: 6px;\n padding: 8px 16px; font-size: 12px; font-weight: 500; cursor: pointer;\n ">Continue</button>\n </div>`,document.body.appendChild(n),this.currentPopup=n,t||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.updateHighlightPosition=()=>{if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();this.currentHighlight.style.top=`${e.top}px`,this.currentHighlight.style.left=`${e.left}px`,this.currentHighlight.style.width=`${e.width}px`,this.currentHighlight.style.height=`${e.height}px`,this.updatePopupPosition()},this.scrollHandler=()=>{null!==this.rafId&&window.cancelAnimationFrame(this.rafId),this.updateHighlightPosition?.()},window.addEventListener("scroll",this.scrollHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.scrollHandler,{passive:!0}),window.addEventListener("touchmove",this.scrollHandler,{passive:!0}),window.addEventListener("wheel",this.scrollHandler,{passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=320,n=120,r=10,i=e.left+e.width/2,o=e.top+e.height/2,a=[{left:e.right+20,top:o-60},{left:e.left-t-20,top:o-60},{left:i-160,top:e.top-n-20},{left:i-160,top:e.bottom+20}];let s=a[0];for(const d of a)if(d.left>=r&&d.left+t<=window.innerWidth-r&&d.top>=r&&d.top+n<=window.innerHeight-r){s=d;break}const c=Math.max(r,Math.min(s.left,window.innerWidth-t-r)),l=Math.max(r,Math.min(s.top,window.innerHeight-n-r));this.currentPopup.style.cssText+=`\n position: fixed;\n top: ${l}px;\n left: ${c}px;\n width: 320px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n z-index: 2147483646;\n padding: 16px;\n `}setupClickHandler(){this.clickHandler=e=>{if(this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)){e.preventDefault(),e.stopPropagation();const t=this.resolvePromise;this.resolvePromise=null,this.rejectPromise=null,t(!0)}},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{const t=e.querySelector("#marketrix-show-continue");t&&t.addEventListener("click",e=>{if(e.stopPropagation(),this.resolvePromise){const e=this.resolvePromise;this.resolvePromise=null,this.rejectPromise=null,e(!0)}})})}setupElementMonitoring(){this.currentElement&&(this.mutationObserver=new MutationObserver(()=>{this.currentElement&&!document.body.contains(this.currentElement)&&this.failWithElementGone("Element was removed from DOM")}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{if(!this.currentElement)return;const e=Za.getSequenceForElement(this.currentElement)??-1,t=Za.checkElementInteractable(this.currentElement,e);t&&this.failWithElementGone(t)},200)}failWithElementGone(e){if(this.rejectPromise){const t=this.rejectPromise;this.rejectPromise=null,this.resolvePromise=null,t(/* @__PURE__ */new Error(`ELEMENT_GONE: ${e}`))}this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}.getInstance(),qa=class e{static instance;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}async executeTool(e,t,n="do",r=""){try{if("show"===n&&this.requiresHighlight(e)){const n=t.index;if(void 0!==n){const{element:t,error:i}=Za.getElementByIndex(n);if(!t)return{success:!1,data:{text:""},error:i||`Element ${n} not found`};if(!(await Wa.showToolAction({element:t,explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e})))return{success:!1,data:{text:""},error:"User cancelled action"}}}switch(e){case"navigate":return this.navigate(t);case"search":return this.search(t);case"click_element":return await this.clickElement(t);case"type_text":return this.typeText(t);case"scroll":return this.scroll(t);case"scroll_to_text":return this.scrollToText(t);case"extract":return this.extract(t);case"go_back":return this.goBack();case"wait":return await this.wait(t);case"select_dropdown_option":return this.selectDropdownOption(t);case"get_dropdown_options":return this.getDropdownOptions(t);case"send_keys":return this.sendKeys(t);case"upload_file":return this.uploadFile(t);case"close_tab":return this.closeTab();case"switch_tab":return this.switchTab(t);case"done":return this.done(t);case"get_html":return this.getHtml();case"get_interactable_elements":return this.getInteractableElements();case"get_screenshot":return await this.getScreenshot();default:return{success:!1,data:{text:""},error:`Unknown tool: ${e}`}}}catch(i){return Wa.cleanup(),{success:!1,data:{text:""},error:i instanceof Error?i.message:String(i)}}}requiresHighlight(e){return _a.has(e)}navigate(e){return e.url?e.new_tab?(window.open(e.url,"_blank"),{success:!0,data:{text:`Opened ${e.url} in new tab`}}):(window.location.href=e.url,{success:!0,data:{text:`Navigating to ${e.url}`}}):{success:!1,data:{text:""},error:"URL is required"}}search(e){if(!e.query)return{success:!1,data:{text:""},error:"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}`),window.location.href=r,{success:!0,data:{text:`Searching for "${e.query}" on ${t}`}}}async clickElement(e){if(void 0===e.index)return{success:!1,data:{text:""},error:"Index required"};const{element:t,error:n}=Za.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),setTimeout(()=>{try{t.click()}catch(e){try{t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}))}catch(n){}}},50),{success:!0,data:{text:`Clicked element ${e.index}`}}):{success:!1,data:{text:""},error:n||`Element ${e.index} not found`}}typeText(e){if(void 0===e.index||void 0===e.text)return{success:!1,data:{text:""},error:"Index and text required"};const t=!1!==e.clear,{element:n,error:r}=Za.getValidatedElement(e.index);if(!n)return{success:!1,data:{text:""},error:r||`Element ${e.index} not found`};if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n.isContentEditable){const r=n;try{r.focus()}catch(i){}const o=t?e.text:r.value+e.text;let a=!1,s=null;if(!a)try{const e="TEXTAREA"===r.tagName.toUpperCase()?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,t=Object.getOwnPropertyDescriptor(e,"value");t?.set&&(t.set.call(r,o),a=!0)}catch(i){s=i}if(!a)try{r.value=o,a=!0}catch(i){s=i}if(!a)try{r.focus(),t&&r.select(),document.execCommand("insertText",!1,e.text)&&(a=!0)}catch(i){s=i}if(!a)try{r.focus(),t&&(r.value="");for(const t of e.text)r.dispatchEvent(new KeyboardEvent("keydown",{key:t,bubbles:!0,cancelable:!0})),r.value+=t,r.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t})),r.dispatchEvent(new KeyboardEvent("keyup",{key:t,bubbles:!0,cancelable:!0}));a=!0}catch(i){s=i}if(!a)return{success:!1,data:{text:""},error:`Failed to set value: ${s instanceof Error?s.message:String(s)}`};try{const t=new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text});r.dispatchEvent(t),r.dispatchEvent(new Event("change",{bubbles:!0})),r.dispatchEvent(new Event("blur",{bubbles:!0}))}catch(i){}}else if("value"in n)try{n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}catch(i){return{success:!1,data:{text:""},error:`Failed to set value on element: ${i instanceof Error?i.message:String(i)}`}}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(i){return{success:!1,data:{text:""},error:`Failed to set textContent: ${i instanceof Error?i.message:String(i)}`}}return{success:!0,data:{text:`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{success:!1,data:{text:""},error:"Invalid direction"}}return{success:!0,data:{text:`Scrolled ${e.direction}`}}}scrollToText(e){if(!e.text)return{success:!1,data:{text:""},error:"Text required"};const t=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let n;for(;n=t.nextNode();)if(n.textContent?.includes(e.text)&&n.parentElement)return n.parentElement.scrollIntoView({behavior:"smooth",block:"center"}),{success:!0,data:{text:`Scrolled to "${e.text}"`}};return{success:!1,data:{text:""},error:`Text "${e.text}" not found`}}extract(e){const t=e.start_from_char??0,n=!1!==e.extract_links,r=document.body.innerText;return{success:!0,data:{title:document.title,url:window.location.href,text:r.slice(t,t+1e4),links:n?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]}}}goBack(){return window.history.length>1?(window.history.back(),{success:!0,data:{text:"Navigated back"}}):{success:!1,data:{text:""},error:"No history"}}async wait(e){return void 0===e.seconds?{success:!1,data:{text:""},error:"Seconds required"}:(await new Promise(t=>setTimeout(t,1e3*e.seconds)),{success:!0,data:{text:`Waited ${e.seconds}s`}})}selectDropdownOption(e){if(void 0===e.index||!e.option)return{success:!1,data:{text:""},error:"Index/Option required"};const{element:t,error:n}=Za.getValidatedElement(e.index);if(!t)return{success:!1,data:{text:""},error:n||`Select ${e.index} not found`};if(!(t instanceof HTMLSelectElement))return{success:!1,data:{text:""},error:`Element ${e.index} is not a select element`};const r=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return r?(t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,data:{text:`Selected ${e.option}`}}):{success:!1,data:{text:""},error:`Option ${e.option} not found`}}getDropdownOptions(e){const t=e.index,{element:n,error:r}=Za.getValidatedElement(t);return n?n instanceof HTMLSelectElement?{success:!0,data:{options:Array.from(n.options).map(e=>({value:e.value,text:e.text}))}}:{success:!1,data:{options:[]},error:`Element ${t} is not a select element`}:{success:!1,data:{options:[]},error:r||`Select ${t} not found`}}sendKeys(e){if(void 0===e.index||!e.keys)return{success:!1,data:{text:""},error:"Index/Keys required"};const{element:t,error:n}=Za.getValidatedElement(e.index);return t?(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})),{success:!0,data:{text:this.simulateKeyAction(t,e.keys)||`Sent keys ${e.keys}`}}):{success:!1,data:{text:""},error:n||`Element ${e.index} not found`}}simulateKeyAction(e,t){switch(t){case"Tab":{const t=Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent),n=t.indexOf(e);if(-1!==n&&n<t.length-1){const e=t[n+1];return e.focus(),`Tab: moved focus to ${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""}`}return"Tab: no next focusable element"}case"Shift+Tab":{const t=Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent),n=t.indexOf(e);if(n>0){const e=t[n-1];return e.focus(),`Shift+Tab: moved focus to ${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""}`}return"Shift+Tab: no previous focusable element"}case"Enter":if(e instanceof HTMLButtonElement||"button"===e.getAttribute("role"))return e.click(),"Enter: clicked button";if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){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}`):e instanceof HTMLButtonElement||"button"===e.getAttribute("role")?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t<e.options.length-1?(e.selectedIndex=t+1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowDown: selected "${e.options[e.selectedIndex].text}"`):"ArrowDown: already at last option"}return"ArrowDown: dispatched event";case"ArrowUp":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t>0?(e.selectedIndex=t-1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowUp: selected "${e.options[e.selectedIndex].text}"`):"ArrowUp: already at first option"}return"ArrowUp: dispatched event";case"Home":return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value;if(!t||0===t.length)return"Backspace: input is empty, nothing to delete";let n,r,i=e.selectionStart??t.length,o=e.selectionEnd??t.length;if(0===i&&0===o&&(i=t.length,o=t.length),i===o&&i>0)n=t.slice(0,i-1)+t.slice(o),r=i-1;else{if(i===o)return"Backspace: cursor at start, nothing to delete";n=t.slice(0,i)+t.slice(o),r=i}const a=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;return a?a.call(e,n):e.value=n,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(r,r),`Backspace: deleted character, value is now "${n}"`}return"Backspace: dispatched event";case"Delete":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.selectionStart||0,n=e.selectionEnd||0,r=e.value;let i;if(t===n&&t<r.length)i=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";i=r.slice(0,t)+r.slice(n)}const o=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;return o?o.call(e,i):e.value=i,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(t,t),`Delete: deleted character, value is now "${i}"`}return"Delete: dispatched event";default:return null}}uploadFile(e){return{success:!1,data:{text:""},error:"File upload not supported via script"}}closeTab(){return window.close(),{success:!0,data:{text:"Attempted close"}}}switchTab(e){return e.tab_id?{success:!1,data:{text:""},error:"Tab switching not supported"}:{success:!1,data:{text:""},error:"tab_id is required"}}done(e){return void 0===e.success?{success:!1,data:{text:""},error:"success parameter is required"}:{success:!0,data:{text:e.message||(e.success?"Task completed":"Task failed")}}}getHtml(){try{return{success:!0,data:{text:Za.getSnapshotHtml()}}}catch(e){return{success:!1,data:{text:""},error:String(e)}}}getInteractableElements(){try{return{success:!0,data:{elements:Za.getInteractableElements()}}}catch(e){return{success:!1,data:{elements:[]},error:String(e)}}}async getScreenshot(){try{const e=await Ua();if(!e)return{success:!1,data:{text:""},error:"Failed to get stream"};const t=document.createElement("video");t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),await new Promise(e=>{t.onloadeddata=()=>e()});const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight,n.getContext("2d")?.drawImage(t,0,0);const r=n.toDataURL("image/jpeg",.75);return t.remove(),{success:!0,data:{text:r}}}catch(e){return{success:!1,data:{text:""},error:String(e)}}}}.getInstance(),Va=class e{static instance;config=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadConfig(){const e=Ta.getConfig();return e?(this.config=e,e):(this.config={},this.config)}saveConfig(e){Ta.setConfig(e),this.config=e}updateConfig(e){this.config||(this.config={}),this.config={...this.config,...e},this.saveConfig(this.config)}getConfig(){return this.config}shouldShowWidget(){return!!this.config&&(this.config.widget_enabled??!1)}}.getInstance();function Ga(e,t={}){return{...t,...e}}var Ja=e=>({state:e,effects:[]});function Ka(e,t,n,r,i,o,a){const s=function(e){return Ea[e]?Ea[e]:e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}(r),c=va({messages:e,isSimulationRunning:t,currentMode:n,requireContent:"failed"===o});if(!c)return e;let l=c.message;const d=t&&"show"===n&&_a.has(r),u="done"===r,p="show"===n||"do"===n;"in_progress"===o?(u||(l=function(e,t,n){const r=xa(e),i=r.parts||[],o=[...i],a=i.findIndex(e=>"progress"===e.type&&e.browserToolName===t&&"in_progress"===e.status),s=!ka.has(t),c="default",l=Sa(n);return a>=0?o[a]={...o[a],content:l,hideIcon:s,textStyle:c}:o.push({type:"progress",content:l,status:"in_progress",browserToolName:t,hideIcon:s,textStyle:c}),{...r,parts:o}}(l,s,i||s)),t&&p&&(l=za(l,t,n,d))):"completed"===o?(u||(l=function(e,t){const n=xa(e),r=n.parts||[],i=[...r];let o=-1;if(t)o=r.map(e=>"progress"===e.type?e.browserToolName:"").lastIndexOf(t);else for(let a=r.length-1;a>=0;a--)if("progress"===r[a].type&&"in_progress"===r[a].status){o=a;break}return o>=0&&(i[o]={...i[o],status:"completed"}),{...n,parts:i}}(l)),t&&p&&(l=za(l,t,n,!1))):(l=function(e,t,n){const r=xa(e),i=r.parts||[],o=n.toLowerCase().includes("cancelled by cleanup"),a=[...i];let s=i.map(e=>"progress"===e.type?e.browserToolName:"").lastIndexOf(t);if(-1===s)for(let c=i.length-1;c>=0;c--)if("progress"===i[c].type&&"in_progress"===i[c].status){s=c;break}if(s>=0)if(o){const e=Sa(a[s].content);a[s]={...a[s],status:"completed",content:e}}else{const e=Sa(n),t=Sa(a[s].content);a[s]={...a[s],status:"failed",content:e?`${t} (${e})`:t}}return{...r,parts:a}}(l,s,a||""),t&&p&&(l=za(l,t,n,!1)));const h=[...e];return h[c.index]=l,h}function Ya(e,t,n,r,i,o){return{...e,messages:Ka(e.messages,e.task.isSimulationRunning,i,t,n,r,o)}}var Xa=n(void 0),Qa={activeSimulationId:null,isSimulationRunning:!1},es=({children:e,previewMode:t=!1,currentMode:n,uiActions:r,initialMessages:i,initialTask:a})=>{const[c,l]=p(()=>({messages:i??[],task:a??Qa})),h=u(c),m=u(n);m.current=n;const g=u(0),w=u(/* @__PURE__ */new Set),b=u({}),y=o(e=>{const t=h.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(h.current=n,l(n))},[]),v=o(e=>{y(t=>({...t,messages:[...t.messages,e]}))},[y]),x=o((e,t)=>{y(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[y]),k=o(e=>{y(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[y]),_=o(e=>{y(t=>({...t,messages:e}))},[y]),S=o(()=>{y(e=>({...e,messages:[]}))},[y]),z=o(e=>{y(t=>({...t,task:{activeSimulationId:e.activeSimulationId,isSimulationRunning:e.isSimulationRunning}}))},[y]),E=o(async(e,n,i,o,a)=>{const s=n??m.current;if(t)return a||v($a(e,s)),void v(Ma("This is a preview. In production, I'll respond to your messages here."));let c=Va.getConfig();if(c||(c=Va.loadConfig()),!c||!c.mtxId&&!c.mtxKey&&!c.mtxApp)return void v(Ma("Configuration error: Missing API credentials. Please check your widget settings."));a||v($a(e,s));const l=`temp-${globalThis.crypto.randomUUID()}`;v({id:l,content:ba(""),sender:"agent",timestamp:/* @__PURE__ */new Date,mode:s,isPlaceholder:!0,placeholderState:"thinking",parts:[]}),r.setLoading(!0);const d=new Da(c);try{i&&d.updateConfig({mtxApp:i});const t=d.getChatId();if(t){const e=ja.getInstance();if(!e.isConnected()){const n=Va.getConfig();try{await e.connect(t,n?{mtxId:n.mtxId,mtxKey:n.mtxKey,mtxApp:n.mtxApp}:void 0)}catch(u){}}}await d.messageDispatch({message:e,mode:s,question:o,requestId:l})}catch(p){y(e=>{const t="I'm sorry, I encountered an error processing your request. Please try again.",n=e.messages.map(e=>{if(e.id!==l)return e;const n=[...e.parts??[],{type:"text",content:t}];return{...e,isPlaceholder:!1,parts:n,content:t}});return{...e,messages:n}})}finally{r.setLoading(!1)}},[t,v,y,r]),I=o(e=>{if(w.current.add(e),w.current.size>1e3){const e=Array.from(w.current);w.current=new Set(e.slice(-500))}},[]),C=o(()=>{const e=b.current;if(e.apiTaskId&&e.agentRunning){const t=e.apiTaskId;b.current={},y(e=>({...e,task:{isSimulationRunning:!0,activeSimulationId:t}}))}},[y]);s(()=>{if(t)return;const e=ja.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:i,mode:o,explanation:a}=t,s=await qa.executeTool(r,i,o,a);if(s.success)try{g.current++,e.send({type:"tool/response",tool_call_id:n,success:!0,data:"string"==typeof s.data?s.data:JSON.stringify(s.data),state_version:g.current}).catch(e=>{}),y(e=>Ya(e,r,a,"completed",m.current)),"done"===r&&(b.current={},y(e=>function(e,t){const n=va({messages:e.messages,isSimulationRunning:e.task.isSimulationRunning,currentMode:t,requireContent:!1}),r=[...e.messages];if(n){const e=(n.message.parts??[]).filter(e=>!("progress"===e.type&&"done"===e.browserToolName));r[n.index]={...n.message,simulationStatus:"done",parts:e}}return{messages:r,task:{isSimulationRunning:!1,activeSimulationId:null}}}(e,m.current)))}catch(c){y(e=>Ya(e,r,a,"failed",m.current,"Connection error"))}else y(e=>Ya(e,r,a,"failed",m.current,s.error||"Tool execution failed")),g.current++,e.send({type:"tool/response",tool_call_id:n,success:!1,data:"string"==typeof s.data?s.data:JSON.stringify(s.data),error:s.error??void 0,state_version:g.current}).catch(e=>{})},i={onStatusChange:e=>{r.setAgentAvailable("registered"===e)},onMessage:async t=>{if("tool/call"===t.type){const n=t.tool_call_id;if(w.current.has(n))return;if(I(n),!ga.map(e=>e.id).includes(t.browser_tool))return void e.send({type:"tool/response",tool_call_id:n,success:!1,error:`Unknown tool: ${t.browser_tool}`,state_version:g.current}).catch(e=>{});h.current.task.isSimulationRunning,void 0!==t.state_version&&t.state_version>g.current&&(g.current=t.state_version)}else if("task/status"!==t.type||"completed"!==t.status&&"failed"!==t.status&&"stopped"!==t.status){if("task/status"===t.type&&"has_question"===t.status)b.current={};else if("task/status"===t.type&&"running"===t.status)return b.current={...b.current,agentRunning:!0,apiTaskId:b.current.apiTaskId||t.task_id||void 0},void C()}else w.current.clear(),b.current={};let i=[];y(e=>{const n=function(e,t,n){switch(t.type){case"tool/call":{const r=e.task.isSimulationRunning?e.task:{...e.task,isSimulationRunning:!0},i=r.isSimulationRunning,o=t.mode||n||"do",a=t.explanation||"";return{state:{messages:Ka(e.messages,i,n,t.browser_tool,a,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:o,explanation:a}]}}case"task/status":{const r=t.message||"";if("running"===t.status)return Ja(e);if("has_question"===t.status){const t=va({messages:e.messages,isSimulationRunning:e.task.isSimulationRunning,currentMode:n,requireContent:!1}),i=[...e.messages];if(t){const e=za(t.message,!1,n);i[t.index]={...e,placeholderState:"waiting-for-user",...r&&{content:r}}}return{state:{messages:i,task:{isSimulationRunning:!1,activeSimulationId:null}},effects:[]}}const i=va({messages:e.messages,isSimulationRunning:e.task.isSimulationRunning,currentMode:n,requireContent:!1}),o=[...e.messages];if(i){let e="done";"failed"===t.status?e="failed":"stopped"===t.status&&(e="stopped"),o[i.index]={...i.message,simulationStatus:e,...r&&{content:r}}}return{state:{messages:o,task:{isSimulationRunning:!1,activeSimulationId:null}},effects:[]}}case"chat/delta":{const n=e.messages.map(e=>{if(e.id!==t.request_id)return e;const n=[...e.parts??[]],r=n[n.length-1];"text"===r?.type&&r.streaming?n[n.length-1]={...r,content:r.content+t.text}:n.push({type:"text",content:t.text,streaming:!0});const i=n[n.length-1].content;return{...e,content:i,isPlaceholder:!1,placeholderState:void 0,parts:n}});return{state:{...e,messages:n},effects:[]}}case"chat/response":{const n=e.messages.map(e=>{if(e.id!==t.request_id)return e;const n=[...e.parts??[]],r=n[n.length-1];return"text"===r?.type&&r.streaming?n[n.length-1]={type:"text",content:t.text}:n.push({type:"text",content:t.text}),{...e,content:t.text,isPlaceholder:!1,placeholderState:void 0,parts:n}}),r=[{type:"setLoading",value:!1}];return{state:{...e,messages:n},effects:r}}case"chat/error":{const n=e.messages.map(e=>{if(e.id!==t.request_id)return e;const n=`Error: ${t.error}`,r=[...e.parts??[],{type:"text",content:n}];return{...e,content:n,isPlaceholder:!1,placeholderState:void 0,parts:r}});return{state:{...e,messages:n},effects:[{type:"setLoading",value:!1}]}}default:return Ja(e)}}(e,t,m.current);return i=n.effects,n.state}),(e=>{for(const t of e)"setLoading"===t.type&&r.setLoading(t.value)})(i);const o=i.find(e=>"executeTool"===e.type);"executeTool"===o?.type&&await n(o)},onError:e=>{r.setError(e.message)}};return e.addCallbacks(i),()=>{e.removeCallbacks(i)}},[t,y,C,I,r]);const T=o(async()=>{const e=h.current.task.activeSimulationId??void 0;y(e=>function(e,t){const n=va({messages:e.messages,isSimulationRunning:e.task.isSimulationRunning,currentMode:t,requireContent:!1}),r=[...e.messages];return n&&(r[n.index]={...n.message,simulationStatus:"stopped"}),{messages:r,task:{isSimulationRunning:!1,activeSimulationId:null}}}(e,m.current)),t||ja.getInstance().send({type:"chat/stop",...e&&{task_id:e}}).catch(e=>{})},[t,y]),A=d(()=>({addMessage:v,updateMessage:x,removeMessage:k,setMessages:_,clearMessages:S,messageDispatch:E}),[v,x,k,_,S,E]),$=d(()=>({setTaskState:z,stopTask:T}),[z,T]),M=d(()=>({messages:c.messages}),[c.messages]);/* @__PURE__ */
|
|
3
3
|
return f(Xa.Provider,{value:{chatState:M,chatActions:A,taskState:c.task,taskActions:$},children:e})},ts=()=>{const e=a(Xa);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},ns=n(void 0),rs=({children:e,initialMode:t="tell",initialIsOpen:n=!1,initialIsMinimized:r=!1})=>{const[i,o]=p({isOpen:n,isMinimized:r,activeView:"home",currentMode:t,agentAvailable:!1,isLoading:!1}),a=d(()=>({setActiveView:e=>o(t=>({...t,activeView:e})),toggleWidget:()=>o(e=>({...e,isOpen:!e.isOpen,isMinimized:!!e.isOpen})),closeWidget:()=>o(e=>({...e,isOpen:!1,isMinimized:!0})),setMode:e=>o(t=>({...t,currentMode:e})),setLoading:e=>o(t=>({...t,isLoading:e})),setAgentAvailable:e=>o(t=>({...t,agentAvailable:e})),setError:e=>o(t=>({...t,error:e})),clearError:()=>o(e=>({...e,error:void 0})),applyState:e=>o(t=>({...t,...e}))}),[]);/* @__PURE__ */
|
|
4
4
|
return f(ns.Provider,{value:{uiState:i,uiActions:a},children:e})},is=()=>{const e=a(ns);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e};var os=({config:e}={})=>{const{uiState:t,uiActions:n}=is(),{chatState:r,chatActions:i,taskState:a,taskActions:c}=ts(),l=d(()=>({isOpen:t.isOpen,isMinimized:t.isMinimized,isLoading:t.isLoading,currentMode:t.currentMode,agentAvailable:t.agentAvailable,error:t.error,activeView:t.activeView,messages:r.messages,activeSimulationId:a.activeSimulationId,isSimulationRunning:a.isSimulationRunning}),[t,r,a]),u=o(()=>{i.clearMessages(),c.setTaskState({activeSimulationId:null,isSimulationRunning:!1}),n.setError(void 0)},[i,c,n]),p=d(()=>({setActiveView:n.setActiveView,toggleWidget:n.toggleWidget,closeWidget:n.closeWidget,setMode:n.setMode,setLoading:n.setLoading,setAgentAvailable:n.setAgentAvailable,setError:n.setError,clearError:n.clearError,setTaskState:c.setTaskState,stopTask:c.stopTask,addMessage:i.addMessage,updateMessage:i.updateMessage,removeMessage:i.removeMessage,setMessages:i.setMessages,messageDispatch:i.messageDispatch,clearChatHistory:u}),[n,c,i,u]),h=d(()=>e||Va.getConfig()||{},[e]),m=function(e){return Object.keys(ia.shape).every(t=>void 0!==e[t])}(h);s(()=>{m&&Va.saveConfig(h)},[h,m]);const f=h.isPreviewMode??!1;return{state:l,actions:p,config:h,shouldShow:m&&!0===h.widget_enabled,isPreviewMode:f,configValid:m}},as=(e=/* @__PURE__ */new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),ss="-",cs=[],ls=e=>{const t=ps(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith("[")&&e.endsWith("]"))return us(e);const n=e.split(ss);return ds(n,""===n[0]&&n.length>1?1:0,t)},getConflictingClassGroupIds:(e,t)=>{if(t){const t=r[e],i=n[e];return t?i?((e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r<e.length;r++)n[r]=e[r];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n})(i,t):t:i||cs}return n[e]||cs}}},ds=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],i=n.nextPart.get(r);if(i){const n=ds(e,t+1,i);if(n)return n}const o=n.validators;if(null===o)return;const a=0===t?e.join(ss):e.slice(t).join(ss),s=o.length;for(let c=0;c<s;c++){const e=o[c];if(e.validator(a))return e.classGroupId}},us=e=>-1===e.slice(1,-1).indexOf(":")?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?"arbitrary.."+r:void 0})(),ps=e=>{const{theme:t,classGroups:n}=e;return hs(n,t)},hs=(e,t)=>{const n=as();for(const r in e){const i=e[r];ms(i,n,r,t)}return n},ms=(e,t,n,r)=>{const i=e.length;for(let o=0;o<i;o++){const i=e[o];fs(i,t,n,r)}},fs=(e,t,n,r)=>{"string"!=typeof e?"function"!=typeof e?bs(e,t,n,r):ws(e,t,n,r):gs(e,t,n)},gs=(e,t,n)=>{(""===e?t:ys(t,e)).classGroupId=n},ws=(e,t,n,r)=>{vs(e)?ms(e(r),t,n,r):(null===t.validators&&(t.validators=[]),t.validators.push(((e,t)=>({classGroupId:e,validator:t}))(n,e)))},bs=(e,t,n,r)=>{const i=Object.entries(e),o=i.length;for(let a=0;a<o;a++){const[e,o]=i[a];ms(o,ys(t,e),n,r)}},ys=(e,t)=>{let n=e;const r=t.split(ss),i=r.length;for(let o=0;o<i;o++){const e=r[o];let t=n.nextPart.get(e);t||(t=as(),n.nextPart.set(e,t)),n=t}return n},vs=e=>"isThemeGetter"in e&&!0===e.isThemeGetter,xs=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(i,o)=>{n[i]=o,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];return void 0!==t?t:void 0!==(t=r[e])?(i(e,t),t):void 0},set(e,t){e in n?n[e]=t:i(e,t)}}},ks=[],_s=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Ss=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=e=>{const t=[];let n,r=0,i=0,o=0;const a=e.length;for(let d=0;d<a;d++){const a=e[d];if(0===r&&0===i){if(":"===a){t.push(e.slice(o,d)),o=d+1;continue}if("/"===a){n=d;continue}}"["===a?r++:"]"===a?r--:"("===a?i++:")"===a&&i--}const s=0===t.length?e:e.slice(o);let c=s,l=!1;s.endsWith("!")?(c=s.slice(0,-1),l=!0):s.startsWith("!")&&(c=s.slice(1),l=!0);return _s(t,l,c,n&&n>o?n-o:void 0)};if(t){const e=t+":",n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):_s(ks,!1,t,void 0,!0)}if(n){const e=r;r=t=>n({className:t,parseClassName:e})}return r},zs=e=>{const t=/* @__PURE__ */new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{const n=[];let r=[];for(let i=0;i<e.length;i++){const o=e[i],a="["===o[0],s=t.has(o);a||s?(r.length>0&&(r.sort(),n.push(...r),r=[]),n.push(o)):r.push(o)}return r.length>0&&(r.sort(),n.push(...r)),n}},Es=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r<n.length;r++)t[n[r]]=!0;return t},Is=/\s+/,Cs=e=>{if("string"==typeof e)return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Cs(e[r]))&&(n&&(n+=" "),n+=t);return n},Ts=(e,...t)=>{let n,r,i,o;const a=e=>{const t=r(e);if(t)return t;const o=((e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:o,postfixLookupClassGroupIds:a}=t,s=[],c=e.trim().split(Is);let l="";for(let d=c.length-1;d>=0;d-=1){const e=c[d],{isExternal:t,modifiers:u,hasImportantModifier:p,baseClassName:h,maybePostfixModifierPosition:m}=n(e);if(t){l=e+(l.length>0?" "+l:l);continue}let f,g=!!m;if(g){f=r(h.substring(0,m));const e=f&&a[f]?r(h):void 0;e&&e!==f&&(f=e,g=!1)}else f=r(h);if(!f){if(!g){l=e+(l.length>0?" "+l:l);continue}if(f=r(h),!f){l=e+(l.length>0?" "+l:l);continue}g=!1}const w=0===u.length?"":1===u.length?u[0]:o(u).join(":"),b=p?w+"!":w,y=b+f;if(s.indexOf(y)>-1)continue;s.push(y);const v=i(f,g);for(let n=0;n<v.length;++n){const e=v[n];s.push(b+e)}l=e+(l.length>0?" "+l:l)}return l})(e,n);return i(e,o),o};return o=s=>(n=(e=>({cache:xs(e.cacheSize),parseClassName:Ss(e),sortModifiers:zs(e),postfixLookupClassGroupIds:Es(e),...ls(e)}))(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,o=a,a(s)),(...e)=>o(((...e)=>{let t,n,r=0,i="";for(;r<e.length;)(t=e[r++])&&(n=Cs(t))&&(i&&(i+=" "),i+=n);return i})(...e))},As=[],$s=e=>{const t=t=>t[e]||As;return t.isThemeGetter=!0,t},Ms=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ns=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Os=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Ps=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Rs=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Ls=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,js=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Ds=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Hs=e=>Os.test(e),Zs=e=>!!e&&!Number.isNaN(Number(e)),Fs=e=>!!e&&Number.isInteger(Number(e)),Us=e=>e.endsWith("%")&&Zs(e.slice(0,-1)),Bs=e=>Ps.test(e),Ws=()=>!0,qs=e=>Rs.test(e)&&!Ls.test(e),Vs=()=>!1,Gs=e=>js.test(e),Js=e=>Ds.test(e),Ks=e=>!Qs(e)&&!sc(e),Ys=e=>e.startsWith("@container")&&("/"===e[10]&&void 0!==e[11]||"s"===e[11]&&void 0!==e[16]&&e.startsWith("-size/",10)||"n"===e[11]&&void 0!==e[18]&&e.startsWith("-normal/",10)),Xs=e=>fc(e,yc,Vs),Qs=e=>Ms.test(e),ec=e=>fc(e,vc,qs),tc=e=>fc(e,xc,Zs),nc=e=>fc(e,_c,Ws),rc=e=>fc(e,kc,Vs),ic=e=>fc(e,wc,Vs),oc=e=>fc(e,bc,Js),ac=e=>fc(e,Sc,Gs),sc=e=>Ns.test(e),cc=e=>gc(e,vc),lc=e=>gc(e,kc),dc=e=>gc(e,wc),uc=e=>gc(e,yc),pc=e=>gc(e,bc),hc=e=>gc(e,Sc,!0),mc=e=>gc(e,_c,!0),fc=(e,t,n)=>{const r=Ms.exec(e);return!!r&&(r[1]?t(r[1]):n(r[2]))},gc=(e,t,n=!1)=>{const r=Ns.exec(e);return!!r&&(r[1]?t(r[1]):n)},wc=e=>"position"===e||"percentage"===e,bc=e=>"image"===e||"url"===e,yc=e=>"length"===e||"size"===e||"bg-size"===e,vc=e=>"length"===e,xc=e=>"number"===e,kc=e=>"family-name"===e,_c=e=>"number"===e||"weight"===e,Sc=e=>"shadow"===e,zc=/*#__PURE__*/Ts(()=>{const e=$s("color"),t=$s("font"),n=$s("text"),r=$s("font-weight"),i=$s("tracking"),o=$s("leading"),a=$s("breakpoint"),s=$s("container"),c=$s("spacing"),l=$s("radius"),d=$s("shadow"),u=$s("inset-shadow"),p=$s("text-shadow"),h=$s("drop-shadow"),m=$s("blur"),f=$s("perspective"),g=$s("aspect"),w=$s("ease"),b=$s("animate"),y=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",sc,Qs],v=()=>[sc,Qs,c],x=()=>[Hs,"full","auto",...v()],k=()=>[Fs,"none","subgrid",sc,Qs],_=()=>["auto",{span:["full",Fs,sc,Qs]},Fs,sc,Qs],S=()=>[Fs,"auto",sc,Qs],z=()=>["auto","min","max","fr",sc,Qs],E=()=>["auto",...v()],I=()=>[Hs,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],C=()=>[Hs,"screen","full","dvw","lvw","svw","min","max","fit",...v()],T=()=>[Hs,"screen","full","lh","dvh","lvh","svh","min","max","fit",...v()],A=()=>[e,sc,Qs],$=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",dc,ic,{position:[sc,Qs]}],M=()=>["auto","cover","contain",uc,Xs,{size:[sc,Qs]}],N=()=>[Us,cc,ec],O=()=>["","none","full",l,sc,Qs],P=()=>["",Zs,cc,ec],R=()=>[Zs,Us,dc,ic],L=()=>["","none",m,sc,Qs],j=()=>["none",Zs,sc,Qs],D=()=>["none",Zs,sc,Qs],H=()=>[Zs,sc,Qs],Z=()=>[Hs,"full",...v()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Bs],breakpoint:[Bs],color:[Ws],container:[Bs],"drop-shadow":[Bs],ease:["in","out","in-out"],font:[Ks],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Bs],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Bs],shadow:[Bs],spacing:["px",Zs],text:[Bs],"text-shadow":[Bs],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Hs,Qs,sc,g]}],container:["container"],"container-type":[{"@container":["","normal","size",sc,Qs]}],"container-named":[Ys],columns:[{columns:[Zs,Qs,sc,s]}],"break-after":[{"break-after":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-before":[{"break-before":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:y()}],overflow:[{overflow:["auto","hidden","clip","visible","scroll"]}],"overflow-x":[{"overflow-x":["auto","hidden","clip","visible","scroll"]}],"overflow-y":[{"overflow-y":["auto","hidden","clip","visible","scroll"]}],overscroll:[{overscroll:["auto","contain","none"]}],"overscroll-x":[{"overscroll-x":["auto","contain","none"]}],"overscroll-y":[{"overscroll-y":["auto","contain","none"]}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:x()}],"inset-x":[{"inset-x":x()}],"inset-y":[{"inset-y":x()}],start:[{"inset-s":x(),start:x()}],end:[{"inset-e":x(),end:x()}],"inset-bs":[{"inset-bs":x()}],"inset-be":[{"inset-be":x()}],top:[{top:x()}],right:[{right:x()}],bottom:[{bottom:x()}],left:[{left:x()}],visibility:["visible","invisible","collapse"],z:[{z:[Fs,"auto",sc,Qs]}],basis:[{basis:[Hs,"full","auto",s,...v()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Zs,Hs,"auto","initial","none",Qs]}],grow:[{grow:["",Zs,sc,Qs]}],shrink:[{shrink:["",Zs,sc,Qs]}],order:[{order:[Fs,"first","last","none",sc,Qs]}],"grid-cols":[{"grid-cols":k()}],"col-start-end":[{col:_()}],"col-start":[{"col-start":S()}],"col-end":[{"col-end":S()}],"grid-rows":[{"grid-rows":k()}],"row-start-end":[{row:_()}],"row-start":[{"row-start":S()}],"row-end":[{"row-end":S()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":z()}],"auto-rows":[{"auto-rows":z()}],gap:[{gap:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"justify-content":[{justify:["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe","normal"]}],"justify-items":[{"justify-items":["start","end","center","stretch","center-safe","end-safe","normal"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],"align-content":[{content:["normal","start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"align-items":[{items:["start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"align-self":[{self:["auto","start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"place-content":[{"place-content":["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"place-items":[{"place-items":["start","end","center","stretch","center-safe","end-safe","baseline"]}],"place-self":[{"place-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],p:[{p:v()}],px:[{px:v()}],py:[{py:v()}],ps:[{ps:v()}],pe:[{pe:v()}],pbs:[{pbs:v()}],pbe:[{pbe:v()}],pt:[{pt:v()}],pr:[{pr:v()}],pb:[{pb:v()}],pl:[{pl:v()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mbs:[{mbs:E()}],mbe:[{mbe:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"space-y-reverse":["space-y-reverse"],size:[{size:I()}],"inline-size":[{inline:["auto",...C()]}],"min-inline-size":[{"min-inline":["auto",...C()]}],"max-inline-size":[{"max-inline":["none",...C()]}],"block-size":[{block:["auto",...T()]}],"min-block-size":[{"min-block":["auto",...T()]}],"max-block-size":[{"max-block":["none",...T()]}],w:[{w:[s,"screen",...I()]}],"min-w":[{"min-w":[s,"screen","none",...I()]}],"max-w":[{"max-w":[s,"screen","none","prose",{screen:[a]},...I()]}],h:[{h:["screen","lh",...I()]}],"min-h":[{"min-h":["screen","lh","none",...I()]}],"max-h":[{"max-h":["screen","lh",...I()]}],"font-size":[{text:["base",n,cc,ec]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,mc,nc]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Us,Qs]}],"font-family":[{font:[lc,rc,t]}],"font-features":[{"font-features":[Qs]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,sc,Qs]}],"line-clamp":[{"line-clamp":[Zs,"none",sc,tc]}],leading:[{leading:[o,...v()]}],"list-image":[{"list-image":["none",sc,Qs]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",sc,Qs]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:A()}],"text-color":[{text:A()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:["solid","dashed","dotted","double","wavy"]}],"text-decoration-thickness":[{decoration:[Zs,"from-font","auto",sc,ec]}],"text-decoration-color":[{decoration:A()}],"underline-offset":[{"underline-offset":[Zs,"auto",sc,Qs]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:v()}],"tab-size":[{tab:[Fs,sc,Qs]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",sc,Qs]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",sc,Qs]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:$()}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","space","round"]}]}],"bg-size":[{bg:M()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Fs,sc,Qs],radial:["",sc,Qs],conic:[Fs,sc,Qs]},pc,oc]}],"bg-color":[{bg:A()}],"gradient-from-pos":[{from:N()}],"gradient-via-pos":[{via:N()}],"gradient-to-pos":[{to:N()}],"gradient-from":[{from:A()}],"gradient-via":[{via:A()}],"gradient-to":[{to:A()}],rounded:[{rounded:O()}],"rounded-s":[{"rounded-s":O()}],"rounded-e":[{"rounded-e":O()}],"rounded-t":[{"rounded-t":O()}],"rounded-r":[{"rounded-r":O()}],"rounded-b":[{"rounded-b":O()}],"rounded-l":[{"rounded-l":O()}],"rounded-ss":[{"rounded-ss":O()}],"rounded-se":[{"rounded-se":O()}],"rounded-ee":[{"rounded-ee":O()}],"rounded-es":[{"rounded-es":O()}],"rounded-tl":[{"rounded-tl":O()}],"rounded-tr":[{"rounded-tr":O()}],"rounded-br":[{"rounded-br":O()}],"rounded-bl":[{"rounded-bl":O()}],"border-w":[{border:P()}],"border-w-x":[{"border-x":P()}],"border-w-y":[{"border-y":P()}],"border-w-s":[{"border-s":P()}],"border-w-e":[{"border-e":P()}],"border-w-bs":[{"border-bs":P()}],"border-w-be":[{"border-be":P()}],"border-w-t":[{"border-t":P()}],"border-w-r":[{"border-r":P()}],"border-w-b":[{"border-b":P()}],"border-w-l":[{"border-l":P()}],"divide-x":[{"divide-x":P()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":P()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:["solid","dashed","dotted","double","hidden","none"]}],"divide-style":[{divide:["solid","dashed","dotted","double","hidden","none"]}],"border-color":[{border:A()}],"border-color-x":[{"border-x":A()}],"border-color-y":[{"border-y":A()}],"border-color-s":[{"border-s":A()}],"border-color-e":[{"border-e":A()}],"border-color-bs":[{"border-bs":A()}],"border-color-be":[{"border-be":A()}],"border-color-t":[{"border-t":A()}],"border-color-r":[{"border-r":A()}],"border-color-b":[{"border-b":A()}],"border-color-l":[{"border-l":A()}],"divide-color":[{divide:A()}],"outline-style":[{outline:["solid","dashed","dotted","double","none","hidden"]}],"outline-offset":[{"outline-offset":[Zs,sc,Qs]}],"outline-w":[{outline:["",Zs,cc,ec]}],"outline-color":[{outline:A()}],shadow:[{shadow:["","none",d,hc,ac]}],"shadow-color":[{shadow:A()}],"inset-shadow":[{"inset-shadow":["none",u,hc,ac]}],"inset-shadow-color":[{"inset-shadow":A()}],"ring-w":[{ring:P()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:A()}],"ring-offset-w":[{"ring-offset":[Zs,ec]}],"ring-offset-color":[{"ring-offset":A()}],"inset-ring-w":[{"inset-ring":P()}],"inset-ring-color":[{"inset-ring":A()}],"text-shadow":[{"text-shadow":["none",p,hc,ac]}],"text-shadow-color":[{"text-shadow":A()}],opacity:[{opacity:[Zs,sc,Qs]}],"mix-blend":[{"mix-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Zs]}],"mask-image-linear-from-pos":[{"mask-linear-from":R()}],"mask-image-linear-to-pos":[{"mask-linear-to":R()}],"mask-image-linear-from-color":[{"mask-linear-from":A()}],"mask-image-linear-to-color":[{"mask-linear-to":A()}],"mask-image-t-from-pos":[{"mask-t-from":R()}],"mask-image-t-to-pos":[{"mask-t-to":R()}],"mask-image-t-from-color":[{"mask-t-from":A()}],"mask-image-t-to-color":[{"mask-t-to":A()}],"mask-image-r-from-pos":[{"mask-r-from":R()}],"mask-image-r-to-pos":[{"mask-r-to":R()}],"mask-image-r-from-color":[{"mask-r-from":A()}],"mask-image-r-to-color":[{"mask-r-to":A()}],"mask-image-b-from-pos":[{"mask-b-from":R()}],"mask-image-b-to-pos":[{"mask-b-to":R()}],"mask-image-b-from-color":[{"mask-b-from":A()}],"mask-image-b-to-color":[{"mask-b-to":A()}],"mask-image-l-from-pos":[{"mask-l-from":R()}],"mask-image-l-to-pos":[{"mask-l-to":R()}],"mask-image-l-from-color":[{"mask-l-from":A()}],"mask-image-l-to-color":[{"mask-l-to":A()}],"mask-image-x-from-pos":[{"mask-x-from":R()}],"mask-image-x-to-pos":[{"mask-x-to":R()}],"mask-image-x-from-color":[{"mask-x-from":A()}],"mask-image-x-to-color":[{"mask-x-to":A()}],"mask-image-y-from-pos":[{"mask-y-from":R()}],"mask-image-y-to-pos":[{"mask-y-to":R()}],"mask-image-y-from-color":[{"mask-y-from":A()}],"mask-image-y-to-color":[{"mask-y-to":A()}],"mask-image-radial":[{"mask-radial":[sc,Qs]}],"mask-image-radial-from-pos":[{"mask-radial-from":R()}],"mask-image-radial-to-pos":[{"mask-radial-to":R()}],"mask-image-radial-from-color":[{"mask-radial-from":A()}],"mask-image-radial-to-color":[{"mask-radial-to":A()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"]}],"mask-image-conic-pos":[{"mask-conic":[Zs]}],"mask-image-conic-from-pos":[{"mask-conic-from":R()}],"mask-image-conic-to-pos":[{"mask-conic-to":R()}],"mask-image-conic-from-color":[{"mask-conic-from":A()}],"mask-image-conic-to-color":[{"mask-conic-to":A()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:$()}],"mask-repeat":[{mask:["no-repeat",{repeat:["","x","y","space","round"]}]}],"mask-size":[{mask:M()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",sc,Qs]}],filter:[{filter:["","none",sc,Qs]}],blur:[{blur:L()}],brightness:[{brightness:[Zs,sc,Qs]}],contrast:[{contrast:[Zs,sc,Qs]}],"drop-shadow":[{"drop-shadow":["","none",h,hc,ac]}],"drop-shadow-color":[{"drop-shadow":A()}],grayscale:[{grayscale:["",Zs,sc,Qs]}],"hue-rotate":[{"hue-rotate":[Zs,sc,Qs]}],invert:[{invert:["",Zs,sc,Qs]}],saturate:[{saturate:[Zs,sc,Qs]}],sepia:[{sepia:["",Zs,sc,Qs]}],"backdrop-filter":[{"backdrop-filter":["","none",sc,Qs]}],"backdrop-blur":[{"backdrop-blur":L()}],"backdrop-brightness":[{"backdrop-brightness":[Zs,sc,Qs]}],"backdrop-contrast":[{"backdrop-contrast":[Zs,sc,Qs]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Zs,sc,Qs]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Zs,sc,Qs]}],"backdrop-invert":[{"backdrop-invert":["",Zs,sc,Qs]}],"backdrop-opacity":[{"backdrop-opacity":[Zs,sc,Qs]}],"backdrop-saturate":[{"backdrop-saturate":[Zs,sc,Qs]}],"backdrop-sepia":[{"backdrop-sepia":["",Zs,sc,Qs]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":v()}],"border-spacing-x":[{"border-spacing-x":v()}],"border-spacing-y":[{"border-spacing-y":v()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",sc,Qs]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Zs,"initial",sc,Qs]}],ease:[{ease:["linear","initial",w,sc,Qs]}],delay:[{delay:[Zs,sc,Qs]}],animate:[{animate:["none",b,sc,Qs]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[f,sc,Qs]}],"perspective-origin":[{"perspective-origin":y()}],rotate:[{rotate:j()}],"rotate-x":[{"rotate-x":j()}],"rotate-y":[{"rotate-y":j()}],"rotate-z":[{"rotate-z":j()}],scale:[{scale:D()}],"scale-x":[{"scale-x":D()}],"scale-y":[{"scale-y":D()}],"scale-z":[{"scale-z":D()}],"scale-3d":["scale-3d"],skew:[{skew:H()}],"skew-x":[{"skew-x":H()}],"skew-y":[{"skew-y":H()}],transform:[{transform:[sc,Qs,"","none","gpu","cpu"]}],"transform-origin":[{origin:y()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Z()}],"translate-x":[{"translate-x":Z()}],"translate-y":[{"translate-y":Z()}],"translate-z":[{"translate-z":Z()}],"translate-none":["translate-none"],zoom:[{zoom:[Fs,sc,Qs]}],accent:[{accent:A()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:A()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",sc,Qs]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":A()}],"scrollbar-track-color":[{"scrollbar-track":A()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":v()}],"scroll-mx":[{"scroll-mx":v()}],"scroll-my":[{"scroll-my":v()}],"scroll-ms":[{"scroll-ms":v()}],"scroll-me":[{"scroll-me":v()}],"scroll-mbs":[{"scroll-mbs":v()}],"scroll-mbe":[{"scroll-mbe":v()}],"scroll-mt":[{"scroll-mt":v()}],"scroll-mr":[{"scroll-mr":v()}],"scroll-mb":[{"scroll-mb":v()}],"scroll-ml":[{"scroll-ml":v()}],"scroll-p":[{"scroll-p":v()}],"scroll-px":[{"scroll-px":v()}],"scroll-py":[{"scroll-py":v()}],"scroll-ps":[{"scroll-ps":v()}],"scroll-pe":[{"scroll-pe":v()}],"scroll-pbs":[{"scroll-pbs":v()}],"scroll-pbe":[{"scroll-pbe":v()}],"scroll-pt":[{"scroll-pt":v()}],"scroll-pr":[{"scroll-pr":v()}],"scroll-pb":[{"scroll-pb":v()}],"scroll-pl":[{"scroll-pl":v()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",sc,Qs]}],fill:[{fill:["none",...A()]}],"stroke-w":[{stroke:[Zs,cc,ec,tc]}],stroke:[{stroke:["none",...A()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function Ec(...e){return zc(e.filter(Boolean).join(" "))}var Ic={none:"none",card:"0 1px 4px rgba(0,0,0,0.1)",section:"0 2px 8px rgba(0,0,0,0.06)",panel:"0 12px 40px rgba(0,0,0,0.16), 0 4px 12px rgba(0,0,0,0.08)",fab:"0 2px 8px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.04)",button:"0 4px 6px -1px rgba(0,0,0,0.1)"},Cc={none:"rounded-none",sm:"rounded-sm",md:"rounded-md",lg:"rounded-lg",xl:"rounded-xl",theme:"rounded-[var(--radius)]",pill:"rounded-full",circle:"rounded-full"},Tc={default:"text-foreground",muted:"text-foreground-muted",faint:"text-foreground-faint",primary:"text-primary",success:"text-success",warning:"text-warning",inherit:"text-inherit"},Ac={tight:"leading-tight",snug:"leading-snug",normal:"leading-normal",relaxed:"leading-relaxed"},$c={header:{height:40},tabBar:{height:48},launcher:{width:56,height:56},launcherCore:{width:48,height:48}},Mc={info:{background:"#f0f9ff",border:"1px solid #bae6fd",titleColor:"#0c4a6e",bodyColor:"#0369a1",closeColor:"#7dd3fc",closeHoverColor:"#38bdf8",actionBackground:"#e0f2fe"},error:{background:"#fef2f2",border:"1px solid #fecaca",titleColor:"#b91c1c",bodyColor:"#b91c1c",closeColor:"#f87171",closeHoverColor:"#ef4444",actionBackground:"#fee2e2"}};function Nc(e){if(e&&"none"!==e)return{boxShadow:Ic[e]}}var Oc={none:"0","2xs":"1",xs:"0.5",sm:"1.5",md:"2",lg:"3",xl:"4","2xl":"6"},Pc=/* @__PURE__ */new Set(["padding","paddingX","paddingY","paddingTop","paddingBottom","margin","marginX","marginY","marginTop","marginBottom","gap","align","justify","wrap","grow","shrink","position","inset","overflow","overflowY","width","height","minWidth","minHeight","border","rounded","shadow","cursor","opacity","animate","hidden","as","style"]);function Rc(e){const t=[];if(void 0!==e.padding&&t.push(`p-${Oc[e.padding]}`),void 0!==e.paddingX&&t.push(`px-${Oc[e.paddingX]}`),void 0!==e.paddingY&&t.push(`py-${Oc[e.paddingY]}`),void 0!==e.paddingTop&&t.push(`pt-${Oc[e.paddingTop]}`),void 0!==e.paddingBottom&&t.push(`pb-${Oc[e.paddingBottom]}`),void 0!==e.margin&&t.push(`m-${Oc[e.margin]}`),void 0!==e.marginX&&t.push(`mx-${Oc[e.marginX]}`),void 0!==e.marginY&&t.push(`my-${Oc[e.marginY]}`),void 0!==e.marginTop&&t.push(`mt-${Oc[e.marginTop]}`),void 0!==e.marginBottom&&t.push(`mb-${Oc[e.marginBottom]}`),void 0!==e.gap&&t.push(`gap-${Oc[e.gap]}`),void 0!==e.align&&t.push(`items-${e.align}`),void 0!==e.justify&&t.push(`justify-${e.justify}`),!0===e.wrap&&t.push("flex-wrap"),!0===e.grow&&t.push("flex-1"),!1===e.shrink&&t.push("flex-shrink-0"),void 0!==e.position&&t.push(e.position),void 0!==e.inset&&t.push("0"===e.inset?"inset-0":`inset-${Oc[e.inset]}`),void 0!==e.overflow&&t.push(`overflow-${e.overflow}`),void 0!==e.overflowY&&t.push(`overflow-y-${e.overflowY}`),void 0!==e.width&&t.push(`w-${e.width}`),void 0!==e.height&&t.push(`h-${e.height}`),"0"===e.minWidth&&t.push("min-w-0"),"0"===e.minHeight&&t.push("min-h-0"),void 0!==e.border&&!1!==e.border)if(!0===e.border)t.push("border","border-border");else{const n={top:"t",bottom:"b",left:"l",right:"r"}[e.border];t.push(`border-${n}`,"border-border")}if(void 0!==e.rounded&&!1!==e.rounded)if(!0===e.rounded)t.push(Cc.theme);else if("full"===e.rounded)t.push(Cc.pill);else{const n="lg"===e.rounded?"lg":e.rounded;t.push(Cc[n])}return!0!==e.shadow&&"theme"!==e.shadow||t.push("shadow-[var(--shadow)]"),void 0!==e.cursor&&t.push(`cursor-${e.cursor}`),void 0!==e.opacity&&t.push(`opacity-${e.opacity}`),void 0!==e.animate&&"none"!==e.animate&&t.push({spin:"animate-spin",ping:"animate-ping",pulse:"animate-pulse",fadeIn:"animate-fade-in"}[e.animate]),!0===e.hidden&&t.push("hidden"),t.join(" ")}function Lc(e){const t={};for(const n in e)Pc.has(n)||(t[n]=e[n]);return t}var jc={default:"",card:"bg-card text-card-foreground",transparent:"bg-transparent",muted:"bg-muted",secondary:"bg-secondary-bg",primary:"bg-primary text-primary-foreground"},Dc={none:"",compact:"px-2 py-1.5",card:"px-3 py-2",dialog:"p-4",toast:"py-2 pl-2 pr-3"},Hc=i(function(e,t){const{as:n="div",background:r="default",className:i,elevation:o,paddingPreset:a="none",radius:s,style:c,...l}=e,d=Rc(e);/* @__PURE__ */
|
|
5
5
|
return f(n,{...Lc(l),ref:t,className:Ec(jc[r],Dc[a],s&&Rc({rounded:s}),d,i),style:{...Nc(o),...c}})}),Zc="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20viewBox='0%200%20361%20360'%3e%3c!--%20Generator:%20Adobe%20Illustrator%2030.1.0,%20SVG%20Export%20Plug-In%20.%20SVG%20Version:%202.1.1%20Build%20136)%20--%3e%3cdefs%3e%3cstyle%3e%20.st0%20{%20display:%20none;%20fill:%20none;%20stroke:%20%23cdc9c2;%20stroke-width:%201.3px;%20}%20.st1%20{%20fill:%20%23fff;%20}%20.st2,%20.st3%20{%20fill:%20%237cffa6;%20}%20.st3%20{%20stroke:%20%237cffa6;%20stroke-width:%20.38px;%20}%20.st4%20{%20fill:%20%23101828;%20}%20%3c/style%3e%3c/defs%3e%3crect%20class='st4'%20x='.5'%20width='360'%20height='360'/%3e%3cpath%20class='st2'%20d='M83.37,209.58c15.35,0,27.8-12.45,27.8-27.8s-12.44-27.79-27.8-27.79-27.8,12.44-27.8,27.79,12.44,27.8,27.8,27.8Z'/%3e%3cpath%20class='st1'%20d='M85.86,68.28l152.45,223.44h67.29l-70.62-113.77,68.13-109.67h-67.29l-41.12,65.31-41.54-65.31h-67.29Z'/%3e%3cpath%20class='st3'%20d='M176.61,249.83l-35.08-51-57.82,92.71h66.85l26.05-41.7Z'/%3e%3crect%20class='st0'%20x='1.25'%20y='.65'%20width='358.7'%20height='358.7'%20rx='43.35'%20ry='43.35'/%3e%3c/svg%3e",Fc={sm:"w-5 h-5",md:"w-8 h-8",lg:"w-12 h-12"},Uc=i(function({src:e,alt:t,elevation:n,fit:r="contain",size:i="md",rounded:o,className:a,style:s,...c},l){const d="string"==typeof i,u=d?Fc[i]:void 0,p=d?s:{width:i,height:i,...s};/* @__PURE__ */
|
|
@@ -34,10 +34,10 @@ return g(Dl,{align:"center",justify:"center",gap:"lg",paddingY:"2xl",paddingX:"x
|
|
|
34
34
|
return g(Ml,{align:"start",gap:"md",children:[!n&&(()=>{switch(t){case"completed":/* @__PURE__ */return f(Ol,{name:"checkCircle",style:{color:o,marginTop:"2px",flexShrink:0},size:16});case"failed":/* @__PURE__ */return f(Ol,{name:"timesCircle",style:{opacity:.65,marginTop:"2px",flexShrink:0},size:16});case"stopped":/* @__PURE__ */return f(Ol,{name:"ban",style:{opacity:.5,marginTop:"2px",flexShrink:0},size:16});default:/* @__PURE__ */return f(kd,{size:"sm",style:{color:o,marginTop:"2px"}})}})(),/* @__PURE__ */f(Ul,{as:"span",size:"xs",weight:"medium",style:{flex:1,whiteSpace:"pre-wrap",lineHeight:"tight",opacity:"muted"===r?.5:1},children:e})]})},zd=({isWaitingForUser:e})=>/* @__PURE__ */g(Ml,{align:"center",gap:"sm",paddingY:"xs",children:[/* @__PURE__ */f(kd,{size:"sm"}),/* @__PURE__ */f(Ul,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),Ed=({message:e,isLastMessage:t})=>{const{state:n}=os(),r="waiting-for-user"===(e.placeholderState||"thinking");return e.parts&&e.parts.length>0?/* @__PURE__ */g(Dl,{gap:"sm",children:[e.parts.map((t,n)=>{if("text"===t.type){let e=(r=t.content,r.replace(/\n\n__THINKING__$/,"").replace(/__THINKING__/g,"")).trim();return e=e.replace(/\(Cancelled by cleanup\)/gi,"").replace(/\s+/g," ").trim(),e?/* @__PURE__ */f(Ul,{as:"div",size:"sm",weight:"medium",style:{lineHeight:"tight",wordBreak:"break-word",whiteSpace:"pre-wrap",marginBottom:"4px"},children:e},`part-${n}`):null}return"progress"===t.type?"done"===t.browserToolName&&"done"===e.simulationStatus?null:/* @__PURE__ */f(Sd,{content:t.content,status:t.status||"in_progress",...void 0!==t.hideIcon?{hideIcon:t.hideIcon}:{},...void 0!==t.textStyle?{textStyle:t.textStyle}:{}},`part-${n}`):null;var r}),(e.isPlaceholder&&!e.parts.some(e=>"text"===e.type)||n.isSimulationRunning&&t&&("show"===e.mode||"do"===e.mode))&&/* @__PURE__ */f(zd,{isWaitingForUser:r})]}):e.isPlaceholder||n.isSimulationRunning&&t&&("show"===e.mode||"do"===e.mode)?/* @__PURE__ */f(zd,{isWaitingForUser:r}):e.content?/* @__PURE__ */f(Ul,{as:"div",size:"sm",weight:"medium",style:{lineHeight:"tight",wordBreak:"break-word",whiteSpace:"pre-wrap"},children:e.content}):/* @__PURE__ */f(Hc,{})},Id=({status:e})=>{const{config:t}=os(),n=t.widget_accent_color;switch(e){case"done":/* @__PURE__ */return f(Ol,{name:"checkCircle",style:{color:n,flexShrink:0},size:14});case"failed":/* @__PURE__ */return f(Ol,{name:"exclamationCircle",style:{color:k(n,.75),flexShrink:0},size:14});case"stopped":/* @__PURE__ */return f(Ol,{name:"circle",style:{color:k(n,.5),flexShrink:0},size:14});default:/* @__PURE__ */return f(kd,{size:"sm",style:{color:n}})}},Cd=i(function({className:e,...t},n){/* @__PURE__ */
|
|
35
35
|
return f("video",{...t,ref:n,className:Ec(e)})}),Td="8px 8px 0 0",Ad="#111827",$d="rgba(255,255,255,0.7)",Md=({stream:e})=>{const t=u(null),n=u(null),[r,i]=p(!1),[o,a]=p(!1);return s(()=>{if(t.current&&e){const r=t.current;i(!1),a(!1),n.current&&(n.current.catch(()=>{}),n.current=null),r.srcObject=e;const o=()=>{i(!0)},s=()=>{a(!0),i(!1)};r.addEventListener("loadedmetadata",o),r.addEventListener("error",s);const c=r.play();return n.current=c,c.then(()=>{i(!0)}).catch(e=>{e instanceof Error&&"AbortError"!==e.name&&a(!0),n.current=null}),()=>{r.removeEventListener("loadedmetadata",o),r.removeEventListener("error",s)}}return()=>{n.current&&(n.current.catch(()=>{}),n.current=null),t.current&&(t.current.srcObject=null),i(!1),a(!1)}},[e]),e?/* @__PURE__ */g(Hc,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:Td,backgroundColor:"#000000",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)"},children:[!r&&!o&&/* @__PURE__ */f(Ml,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:Ad,borderRadius:Td,zIndex:10,transition:"opacity 300ms",opacity:r?0:1},children:/* @__PURE__ */g(Ml,{direction:"column",align:"center",gap:"md",children:[/* @__PURE__ */f(kd,{size:"lg",style:{color:"white"}}),/* @__PURE__ */f(Ul,{as:"span",size:"xs",weight:"medium",style:{color:$d},children:"Loading stream..."})]})}),o&&/* @__PURE__ */f(Ml,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:Ad,borderRadius:Td,zIndex:10},children:/* @__PURE__ */g(Ml,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",paddingLeft:"16px",paddingRight:"16px"},children:[/* @__PURE__ */f(Ol,{name:"alertCircle",size:32,style:{color:"#9ca3af"}}),/* @__PURE__ */f(Ul,{as:"span",size:"xs",weight:"medium",style:{color:$d},children:"Failed to load stream"})]})}),
|
|
36
36
|
/* @__PURE__ */f(Cd,{ref:t,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"auto",maxHeight:"192px",objectFit:"contain",borderRadius:Td,transition:"opacity 500ms",opacity:r?1:0,minHeight:"120px",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"}}),r&&!o&&/* @__PURE__ */g(Ml,{position:"absolute",align:"center",gap:"sm",animate:"fadeIn",style:{top:"8px",right:"8px",padding:"4px 8px",borderRadius:"9999px",backgroundColor:"rgba(55,65,81,0.9)",backdropFilter:"blur(4px)",zIndex:20,boxShadow:"0 2px 8px rgba(31, 41, 55, 0.4)"},children:[/* @__PURE__ */g(Ml,{position:"relative",align:"center",justify:"center",children:[/* @__PURE__ */f(Hc,{position:"absolute",rounded:"full",animate:"ping",style:{width:"8px",height:"8px",backgroundColor:"white",opacity:.75}}),/* @__PURE__ */f(Hc,{position:"relative",rounded:"full",style:{width:"6px",height:"6px",backgroundColor:"white"}})]}),/* @__PURE__ */f(Ul,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
|
|
37
|
-
/* @__PURE__ */f(Ml,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:Td,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */f(Hc,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */f(Ul,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]}):null},Nd=({message:e,index:t,isLastMessage:n,onScreenAccessAllow:r,onScreenAccessDeny:i})=>{if(e.isSystemMessage)/* @__PURE__ */return f(Ml,{justify:"center",align:"center",children:/* @__PURE__ */f(Ul,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})},`message-${e.id}-${t}`);const o="user"===e.sender;/* @__PURE__ */
|
|
37
|
+
/* @__PURE__ */f(Ml,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:Td,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */f(Hc,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */f(Ul,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]}):null},Nd=({message:e,index:t,isLastMessage:n,onScreenAccessAllow:r,onScreenAccessDeny:i})=>{if(e.isSystemMessage)/* @__PURE__ */return f(Ml,{justify:"center",align:"center",children:/* @__PURE__ */f(Ul,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})},`message-${e.id}-${t}`);const o="user"===e.sender,a=o?"show"===e.mode||"do"===e.mode?"mousePointerClick":void 0:e.isScreenAccessRequest||"waiting-for-user"===e.placeholderState?"checkCircle":void 0;/* @__PURE__ */
|
|
38
38
|
return g(Dl,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":o?"You said…":"Agent says…",animate:n?"fadeIn":void 0,children:[/* @__PURE__ */g(Ml,{align:"start",gap:"sm",width:"full",children:[
|
|
39
39
|
/* @__PURE__ */f(Ml,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!o&&/* @__PURE__ */f(Uc,{src:"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20viewBox='0%200%20361%20360'%3e%3c!--%20Generator:%20Adobe%20Illustrator%2030.1.0,%20SVG%20Export%20Plug-In%20.%20SVG%20Version:%202.1.1%20Build%20136)%20--%3e%3cdefs%3e%3cstyle%3e%20.st0%20{%20display:%20none;%20fill:%20none;%20stroke:%20%23cdc9c2;%20stroke-width:%201.3px;%20}%20.st1%20{%20fill:%20%23fff;%20}%20.st2,%20.st3%20{%20fill:%20%237cffa6;%20}%20.st3%20{%20stroke:%20%237cffa6;%20stroke-width:%20.38px;%20}%20.st4%20{%20fill:%20%23101828;%20}%20%3c/style%3e%3c/defs%3e%3crect%20class='st4'%20x='.5'%20width='360'%20height='360'/%3e%3cpath%20class='st2'%20d='M83.37,209.58c15.35,0,27.8-12.45,27.8-27.8s-12.44-27.79-27.8-27.79-27.8,12.44-27.8,27.79,12.44,27.8,27.8,27.8Z'/%3e%3cpath%20class='st1'%20d='M85.86,68.28l152.45,223.44h67.29l-70.62-113.77,68.13-109.67h-67.29l-41.12,65.31-41.54-65.31h-67.29Z'/%3e%3cpath%20class='st3'%20d='M176.61,249.83l-35.08-51-57.82,92.71h66.85l26.05-41.7Z'/%3e%3crect%20class='st0'%20x='1.25'%20y='.65'%20width='358.7'%20height='358.7'%20rx='43.35'%20ry='43.35'/%3e%3c/svg%3e",alt:"Marketrix AI",size:20,fit:"cover",rounded:"theme",style:{border:"none",outline:"none",display:"block",backgroundColor:"transparent"}})}),
|
|
40
|
-
/* @__PURE__ */g(Dl,{grow:!0,position:"relative",rounded:"theme",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:o?"var(--primary)":void 0,color:o?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */f(Md,{stream:e.videoStream}),!e.videoStream
|
|
40
|
+
/* @__PURE__ */g(Dl,{grow:!0,position:"relative",rounded:"theme",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:o?"var(--primary)":void 0,color:o?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */f(Md,{stream:e.videoStream}),!e.videoStream&&(a?/* @__PURE__ */g(Ml,{align:"start",gap:"sm",children:[/* @__PURE__ */f(Ml,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */f(Ol,{name:a,size:13})}),/* @__PURE__ */f(Dl,{grow:!0,children:/* @__PURE__ */f(Ed,{message:e,isLastMessage:n})})]}):/* @__PURE__ */f(Ed,{message:e,isLastMessage:n})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */g(Ml,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */f($l,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"Yes"}),/* @__PURE__ */f($l,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>i?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */f(Ul,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"Check HTML Instead"}),!o&&e.simulationStatus&&/* @__PURE__ */f(Ml,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */f(Id,{status:e.simulationStatus})})]}),
|
|
41
41
|
/* @__PURE__ */f(Ml,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */f(Ul,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:S(e.timestamp)})]},`message-${e.id}-${t}`)},Od={boxShadow:Ic.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Pd=({messages:e,messagesEndRef:t,config:n,onScreenAccessAllow:r,onScreenAccessDeny:i,onClearChat:o})=>{const{config:a,state:c,isPreviewMode:l}=os({config:n}),[h,m]=p(!1),[w,b]=p(!1),y=u(null),v=d(()=>({id:"welcome",content:a.widget_body??"How can I help you today?",sender:"agent",timestamp:/* @__PURE__ */new Date,isPlaceholder:!1}),[a.widget_body]),x=d(()=>[v,...e],[v,e]),_=()=>{if(y.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=y.current;m(e>200),b(!(Math.abs(t-e-n)<50)&&t>n)}};return s(()=>{window.requestAnimationFrame(()=>{t.current&&(!l&&t.current.scrollIntoView({behavior:"auto"}),!l&&_())})},[e.length,l]),s(()=>{const e=y.current;e&&!l&&e.scrollHeight-e.scrollTop-e.clientHeight<120&&window.requestAnimationFrame(()=>t.current?.scrollIntoView({behavior:"auto"}))},[e[e.length-1]?.content?.length??0,l,t]),/* @__PURE__ */g(Hc,{position:"relative",height:"full",children:[
|
|
42
42
|
/* @__PURE__ */g(Hc,{ref:y,onScroll:_,role:"log","aria-relevant":"additions",height:"full",overflowY:"auto",paddingX:"lg",paddingY:"sm",style:{backgroundColor:a.widget_background_color.includes("gradient")?"transparent":a.widget_background_color,backgroundImage:a.widget_background_color.includes("gradient")?a.widget_background_color:`linear-gradient(135deg, ${a.widget_background_color} 0%, ${a.widget_background_color} 100%)`,scrollbarColor:`${k(a.widget_border_color,.3)} ${k(a.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[0===e.length&&c.isLoading&&/* @__PURE__ */f(_d,{variant:"loading",message:"Connecting…"}),x.map((e,t)=>/* @__PURE__ */f(Nd,{message:e,index:t,isLastMessage:t===x.length-1,onScreenAccessAllow:r,onScreenAccessDeny:i},`message-${e.id}-${t}`)),e.length>0&&o&&/* @__PURE__ */f(Ml,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */f($l,{type:"button",variant:"bare",onClick:()=>{const e=o();e instanceof Promise&&e.catch(e=>{})},children:/* @__PURE__ */f(Ul,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
|
|
43
43
|
/* @__PURE__ */f(Hc,{ref:t},"scroll-anchor")]},"message-list-container"),h&&/* @__PURE__ */f(Ml,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */f(jl,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{y.current?.scrollTo({top:0,behavior:"smooth"})},style:Od,children:/* @__PURE__ */f(Ol,{name:"arrowUp",size:10,style:{color:a.widget_accent_color}})})}),w&&/* @__PURE__ */f(Ml,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */f(jl,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{t.current&&!l&&t.current.scrollIntoView({behavior:"smooth"})},style:Od,children:/* @__PURE__ */f(Ol,{name:"arrowDown",size:10,style:{color:a.widget_accent_color}})})})]})},Rd=class extends t.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){}render(){return this.state.hasError?/* @__PURE__ */f(Ul,{as:"div",size:"xs",align:"center",style:{padding:"16px",color:"var(--muted-foreground)"},children:"Something went wrong displaying messages. Please refresh."}):this.props.children}},Ld={show:"mousePointerClick",tell:"chatBubble",do:"ticktick"},jd=["tell","show","do"];var Dd=({config:e,messages:t,currentMode:n,isSimulationRunning:r=!1,onSendMessage:i,onSetMode:o,onAddMessage:a,onUpdateMessage:s,onRemoveMessage:c,onStopTask:l,onClearChat:d,onScreenSharingChange:h,onStartScreenShareRef:m,onStopScreenShareRef:w,messageInputRef:b})=>{const[y,v]=p(""),x=u(null),[k,_]=p(null),{isScreenSharing:S,showScreenAccessDialog:E,handleScreenAccessDialogAllow:I,handleScreenAccessDialogDeny:C,handleScreenAccessAllow:T,handleScreenAccessDeny:A,requestScreenAccess:$}=ad({onScreenSharingChange:h,onStartScreenShareRef:m,onStopScreenShareRef:w,onAddMessage:a,onUpdateMessage:s,onRemoveMessage:c,onSendMessage:i,pendingMessage:k,setPendingMessage:_}),M=e;/* @__PURE__ */
|