@marketrix.ai/widget 3.8.477 → 3.8.479

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/widget.mjs CHANGED
@@ -1,67 +1,65 @@
1
- import*as e from"react";import t,{createContext as n,createElement as r,forwardRef as o,useCallback as i,useContext as s,useEffect as a,useImperativeHandle as c,useLayoutEffect as l,useMemo as u,useRef as d,useState as p,useSyncExternalStore as h}from"react";import{createRoot as f}from"react-dom/client";import*as m from"react-dom";import{Fragment as g,jsx as y,jsxs as v}from"react/jsx-runtime";function b(e){return Array.isArray(e)?e:null==e?[]:[e]}var w="orpc",x=class extends Error{constructor(...e){super(...e),this.name="AbortError"}};function S(e){let t;return()=>{if(t)return t.result;const n=e();return t={result:n},n}}function k(){return globalThis["__@orpc/shared@1.15.0/otel/config__"]}function _(e,t={},n){return(k()?.tracer)?.startSpan(e,t,n)}function E(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 C({name:e,context:t,...n},r){const o=k()?.tracer;if(!o)return r();const i=async e=>{try{return await r(e)}catch(t){throw E(e,t,n),t}finally{e.end()}};return t?o.startActiveSpan(e,n,t,i):o.startActiveSpan(e,n,i)}async function I(e,t){const n=k();if(!e||!n)return t();const r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function T(e){return!(!e||"object"!=typeof e)&&("next"in e&&"function"==typeof e.next&&Symbol.asyncIterator in e&&"function"==typeof e[Symbol.asyncIterator])}var M=Symbol.asyncDispose??Symbol.for("asyncDispose"),O=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[M](){this.#e=!0,this.#t||(this.#t=!0,await this.#n("dispose"))}[Symbol.asyncIterator](){return this}};function R({name:e,...t},n){let r;return new O(async()=>{r??=_(e);try{const e=await I(r,()=>n.next());return r?.addEvent(e.done?"completed":"yielded"),e}catch(o){throw E(r,o,t),o}},async e=>{try{"next"!==e&&await I(r,()=>n.return?.())}catch(o){throw E(r,o,t),o}finally{r?.end()}})}function z(e,t,n){const r=(t,o)=>{const i=e[o];return i?i({...t,next:(e=t)=>r(e,o+1)}):n(t)};return r(t,0)}function A(e){if(e)return JSON.parse(e)}function P(e){return JSON.stringify(e)}function N(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function D(e){return!!e&&("object"==typeof e||"function"==typeof e)}function $(e,...t){return"function"==typeof e?e(...t):e}function L(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)&&F.test(t.toString()));var t}))return Reflect.apply(t,n,r);let o=!0;r[0].call(n,L(new Proxy(e,{get:(e,t,n)=>{if(!o||"then"!==t)return Reflect.get(e,t,n);o=!1}})))}})}})}var F=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;var j,U=/* @__PURE__ */new Set(["bind","valueOf","toString","toJSON"]),W={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 B=class e extends Error{defined;code;status;data;static{const t=Symbol.for("__@orpc/client@1.15.0/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&&!Z(n.status))throw new Error("[ORPCError] Invalid error status code.");const r=function(e,t){return t||W[e]?.message||e}(e,n.message);super(r,n),this.code=e,this.status=function(e,t){return t??W[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 D(e)?Object.getPrototypeOf(e)?.constructor:null}(e);if(t&&j.has(t))return!0}return super[Symbol.hasInstance](e)}};function H(e){return e instanceof B?e:new B("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:e})}function Z(e){return e<200||e>=400}function q(e){if(!N(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&&Z(e.status)&&"message"in e&&"string"==typeof e.message)}function V(e,t={}){return new B(e.code,{...t,...e})}var Y=class extends TypeError{},K=class extends TypeError{},J=class extends Error{data;constructor(e){super(e?.message??"An error event was received",e),this.data=e?.data}},X=/\r\n|\r(?!\n)|\n/,G=/(?:\r\n|\r(?!\n)|\n){2}/,Q=/(?:\r\n|\r(?!\n)|\n){2}/g;function ee(e){const t={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(const n of e.split(X)){if(""===n)continue;const e=n.indexOf(":"),r=-1===e?"":n.slice(32===n.charCodeAt(e+1)?e+2:e+1);if(0!==e)switch(-1===e?n:n.slice(0,e)){case"data":t.data=void 0===t.data?r:`${t.data}\n${r}`;break;case"event":t.event=r;break;case"id":t.id=r;break;case"retry":{const e=Number.parseInt(r,10);e>=0&&e.toString()===r&&(t.retry=e);break}}else t.comments.push(r)}return t}var te=class{constructor(e={}){this.options=e}pending=[];tail="";discardLeadingLF=!1;feed(e){if(""===e)return;if(this.discardLeadingLF&&(this.discardLeadingLF=!1,10===e.charCodeAt(0)&&""===(e=e.slice(1))))return;const t=this.tail+e;if(!G.test(t))return this.pending.push(e),void(this.tail=t.slice(-3));this.pending.push(e);const n=1===this.pending.length?e:this.pending.join(""),r=n.length-t.length,o=[];let i=0;for(const a of t.matchAll(Q))o.push(n.slice(i,r+a.index)),i=r+a.index+a[0].length;const s=n.slice(i);this.pending.length=0,this.tail=s.slice(-3),""===s?this.discardLeadingLF=13===e.charCodeAt(e.length-1):this.pending.push(s);for(const a of o){const e=ee(a);this.options.onEvent&&this.options.onEvent(e)}}end(){if(0!==this.pending.length)throw new K("Event Iterator ended before complete")}},ne=class extends TransformStream{constructor(){let e;super({start(t){e=new te({onEvent:e=>{t.enqueue(e)}})},transform(t){e.feed(t)},flush(){e.end()}})}},re=/\r\n|[\n\r]/,oe=/\r\n|[\n\r]/g;function ie(e){return re.test(e)}function se(e){if(ie(e))throw new Y("Event's id must not contain a carriage return or newline character")}function ae(e){if(!Number.isInteger(e)||e<0)throw new Y("Event's retry must be a integer and >= 0")}function ce(e){if(ie(e))throw new Y("Event's comment must not contain a carriage return or newline character")}function le(e){let t="";var n;return t+=function(e){let t="";for(const n of e??[])ce(n),t+=`: ${n}\n`;return t}(e.comments),void 0!==e.event&&(!function(e){if(ie(e))throw new Y("Event's event must not contain a carriage return or newline character")}(e.event),t+=`event: ${e.event}\n`),void 0!==e.retry&&(ae(e.retry),t+=`retry: ${e.retry}\n`),void 0!==e.id&&(se(e.id),t+=`id: ${e.id}\n`),t+=void 0===(n=e.data)?"":`data: ${n.replace(oe,"\ndata: ")}\n`,t+="\n",t}var ue=Symbol("ORPC_EVENT_SOURCE_META");function de(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&&ae(t.retry),void 0!==t.comments)for(const n of t.comments)ce(n);return new Proxy(e,{get:(e,n,r)=>n===ue?t:Reflect.get(e,n,r)})}function pe(e){return D(e)?Reflect.get(e,ue):void 0}function he(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=pe(e);t&&D(n)&&(n=de(n,t))}return n};return new O(async()=>{const{done:r,value:o}=await(async()=>{try{return await e.next()}catch(ko){throw await n(ko)}})();let i=await t.value(o,r);if(i!==o){const e=pe(o);e&&D(i)&&(i=de(i,e))}return{done:r,value:i}},async()=>{try{await(e.return?.())}catch(ko){throw await n(ko)}})}function me(e,t={}){const n=t.path??[];return L(new Proxy(async(...[t,r={}])=>await e.call(n,t,function(e){return{...e,context:e.context??{}}}(r)),{get:(r,o)=>"string"!=typeof o||U.has(o)?Reflect.get(r,o):me(e,{...t,path:[...n,o]})}))}function ge(e,t={}){return C({name:"parse_standard_body",signal:t.signal},async()=>{const n=e.headers.get("content-disposition");if("string"==typeof n){const t=he(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 A(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 ne))?.getReader();let r,o=!1;return new O(async()=>{r??=_("consume_event_iterator_stream");try{for(;;){if(void 0===n)return{done:!0,value:void 0};const{done:e,value:t}=await I(r,()=>n.read());if(e){if(o)throw new x("Stream was cancelled");return{done:!0,value:void 0}}switch(t.event){case"message":{let e=A(t.data);return D(e)&&(e=de(e,t)),r?.addEvent("message"),{done:!1,value:e}}case"error":{let e=new J({data:A(t.data)});throw e=de(e,t),r?.addEvent("error"),e}case"done":{let e=A(t.data);return D(e)&&(e=de(e,t)),r?.addEvent("done"),{done:!0,value:e}}default:r?.addEvent("maybe_keepalive")}}}catch(e){throw e instanceof J||E(r,e,t),e}},async e=>{try{"next"!==e&&(o=!0,r?.addEvent("cancelled")),await I(r,()=>n?.cancel())}catch(i){throw E(r,i,t),i}finally{r?.end()}})}(e.body,t);if(r.startsWith("text/plain"))return await e.text();const o=await e.blob();return new File([o],"blob",{type:o.type})})}function ye(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:T(e)?(t.set("content-type","text/event-stream"),function(e,t={}){const n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5e3,o=t.eventIteratorKeepAliveComment??"",i=t.eventIteratorInitialCommentEnabled??!0,s=t.eventIteratorInitialComment??"";let a,c,l=!1;return new ReadableStream({start(e){c=_("stream_event_iterator"),i&&e.enqueue(le({comments:[s]}))},async pull(t){try{n&&(a=setInterval(()=>{t.enqueue(le({comments:[o]})),c?.addEvent("keepalive")},r));const i=await I(c,()=>e.next());if(clearInterval(a),l)return;const s=pe(i.value);if(!i.done||void 0!==i.value||void 0!==s){const e=i.done?"done":"message";t.enqueue(le({...s,event:e,data:P(i.value)})),c?.addEvent(e)}i.done&&(t.close(),c?.end())}catch(i){if(clearInterval(a),l)return;i instanceof J?(t.enqueue(le({...pe(i),event:"error",data:P(i.data)})),c?.addEvent("error"),t.close()):(E(c,i),t.error(i)),c?.end()}},async cancel(){try{l=!0,clearInterval(a),c?.addEvent("cancelled"),await I(c,()=>e.return?.())}catch(t){throw E(c,t),t}finally{c?.end()}}}).pipeThrough(new TextEncoderStream)}(e,n)):(t.set("content-type","application/json"),P(e)):void 0}function ve(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 be(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=ye(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}var we=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)}},xe=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new we(n.plugins).init(n),this.interceptors=b(n.interceptors),this.clientInterceptors=b(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return C({name:`${w}.${e.join("/")}`,signal:n.signal},r=>(r?.setAttribute("rpc.system",w),r?.setAttribute("rpc.method",e.join(".")),T(t)&&(t=R({name:"consume_event_iterator_input",signal:n.signal},t)),z(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{const o=k();let i;const s=o?.trace.getActiveSpan()??r;s&&o&&(i=o?.trace.setSpan(o.context.active(),s));const a=await C({name:"encode_request",context:i},()=>this.codec.encode(e,t,n)),c=await z(this.clientInterceptors,{...n,input:t,path:e,request:a},({input:e,path:t,request:n,...r})=>C({name:"send_request",signal:r.signal,context:i},()=>this.sender.call(n,r,t,e))),l=await C({name:"decode_response",context:i},()=>this.codec.decode(c,n,e,t));return T(l)?R({name:"consume_event_iterator_output",signal:n.signal},l):l})))}},Se=0,ke=1,_e=2,Ee=3,Ce=4,Ie=5,Te=6,Me=7,Oe=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=[],o=[]){for(const i of this.customSerializers)if(i.condition(e)){const s=this.serialize(i.serialize(e),t,n,r,o);return n.push([i.type,...t]),s}if(e instanceof Blob)return r.push(t),o.push(e),[e,n,r,o];if("bigint"==typeof e)return n.push([Se,...t]),[e.toString(),n,r,o];if(e instanceof Date)return n.push([ke,...t]),Number.isNaN(e.getTime())?[null,n,r,o]:[e.toISOString(),n,r,o];if(Number.isNaN(e))return n.push([_e,...t]),[null,n,r,o];if(e instanceof URL)return n.push([Ce,...t]),[e.toString(),n,r,o];if(e instanceof RegExp)return n.push([Ie,...t]),[e.toString(),n,r,o];if(e instanceof Set){const i=this.serialize(Array.from(e),t,n,r,o);return n.push([Te,...t]),i}if(e instanceof Map){const i=this.serialize(Array.from(e.entries()),t,n,r,o);return n.push([Me,...t]),i}if(Array.isArray(e))return[e.map((e,i)=>void 0===e?(n.push([Ee,...t,i]),null):this.serialize(e,[...t,i],n,r,o)[0]),n,r,o];if(N(e)){const i={};for(const s in e)"toJSON"===s&&"function"==typeof e[s]||(i[s]=this.serialize(e[s],[...t,s],n,r,o)[0]);return[i,n,r,o]}return[e,n,r,o]}deserialize(e,t,n,r){const o={data:e};n&&r&&n.forEach((e,t)=>{let n=o,i="data";e.forEach(e=>{if(n=n[i],i=e,!Object.hasOwn(n,i))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${i}`)}),n[i]=r(t)});for(const i of t){const e=i[0];let t=o,n="data";for(let r=1;r<i.length;r++)if(t=t[n],n=i[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 Se:t[n]=BigInt(t[n]);break;case ke:t[n]=new Date(t[n]??"Invalid Date");break;case _e:t[n]=NaN;break;case Ee:t[n]=void 0;break;case Ce:t[n]=new URL(t[n]);break;case Ie:{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 Me:t[n]=new Map(t[n])}}return o.data}};var Re=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?ve(e):e}(await $(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]=[...b(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 o=await $(this.expectedMethod,n,e,t),i=await $(this.baseUrl,n,e,t),s=new URL(i);s.pathname=`${s.pathname.replace(/\/$/,"")}${function(e){return`/${e.map(encodeURIComponent).join("/")}`}(e)}`;const a=this.serializer.serialize(t);if(!("GET"!==o||a instanceof FormData||T(a))){const i=await $(this.maxUrlLength,n,e,t),c=new URL(s);if(c.searchParams.append("data",P(a)),c.toString().length<=i)return{body:void 0,method:o,headers:r,url:c,signal:n.signal}}return{url:s,method:"GET"===o?this.fallbackMethod:o,headers:r,body:a,signal:n.signal}}async decode(e){const t=!Z(e.status),n=await(async()=>{let t=!1;try{const n=await e.body();return t=!0,this.serializer.deserialize(n)}catch(ko){if(!t)throw new Error("Cannot parse response body, please check the response body and content-type.",{cause:ko});throw new Error("Invalid RPC response format.",{cause:ko})}})();if(!t){if(q(n))throw V(n);throw new B((r=e.status,Object.entries(W).find(([,e])=>e.status===r)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"),{status:e.status,data:{...e,body:n}})}var r;return n}},ze=class{constructor(e){this.jsonSerializer=e}serialize(e){return T(e)?fe(e,{value:async e=>this.#o(e,!1),error:async e=>new J({data:this.#o(H(e).toJSON(),!1),cause:e})}):this.#o(e,!0)}#o(e,t){const[n,r,o,i]=this.jsonSerializer.serialize(e),s=0===r.length?void 0:r;if(!t||0===i.length)return{json:n,meta:s};const a=new FormData;return a.set("data",P({json:n,meta:s,maps:o})),i.forEach((e,t)=>{a.set(t.toString(),e)}),a}deserialize(e){return T(e)?fe(e,{value:async e=>this.#i(e),error:async e=>{if(!(e instanceof J))return e;const t=this.#i(e.data);return q(t)?V(t,{cause:e}):new J({data:t,cause:e})}}):this.#i(e)}#i(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()))}},Ae=class extends xe{constructor(e,t){const n=new Oe(t),r=new ze(n);super(new Re(r,t),e,t)}},Pe=class extends we{initRuntimeAdapter(e){for(const t of this.plugins)t.initRuntimeAdapter?.(e)}},Ne=class{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new Pe(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=b(e.adapterInterceptors)}async call(e,t,n,r){const o=be(e,this.toFetchRequestOptions);return function(e,t={}){return{body:S(()=>ge(e,t)),status:e.status,get headers(){const t=ve(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:o,path:n,input:r,init:{redirect:"manual"}},({request:e,path:t,input:n,init:r,...o})=>this.fetch(e,r,o,t,n)),{signal:o.signal})}},De=class extends Ae{constructor(e){super(new Ne(e),e)}};function $e(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 Le(e,t="|"){return e.map(e=>et(e)).join(t)}function Fe(e,t){return"bigint"==typeof t?t.toString():t}function je(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ue(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function We(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Be(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function He(e){return JSON.stringify(e)}var Ze="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function qe(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Ve=/* @__PURE__*/je(()=>{if(Tt.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ye(e){if(!1===qe(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!==qe(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Ke(e){return Ye(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Je=/* @__PURE__*/new Set(["string","number","symbol"]);function Xe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ge(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Qe(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}function et(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}var tt=/*@__PURE__*/(()=>({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 nt(e,t,n,r="partial"){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(`.${r}() cannot be used on object schemas containing refinements`);return Ge(t,Be(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(r,t))throw new Error(`Unrecognized key: "${String(t)}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t of Reflect.ownKeys(r))o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return We(this,"shape",o),o},checks:[]}))}function rt(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 ot(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 it(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function st(e){return"string"==typeof e?e:e?.message}function at(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function ct(e,t,n){var r;const o=e.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);const i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:st(e.inst?._zod.def?.error?.(e))??st(i?.(e))??st(t?.error?.(e))??st(n.customError?.(e))??st(n.localeError?.(e))??"Invalid input",{inst:a,schema:c,continue:l,input:u,...d}=e;return d.path??(d.path=[]),d.message=s,t?.reportInput&&(d.input=u),d}var lt,ut=/[\uD800-\uDBFF]/;function dt(e){const t=e.length;if(!ut.test(e))return t;let n=t;for(let r=0;r<t-1;r++)55296==(64512&e.charCodeAt(r))&&56320==(64512&e.charCodeAt(r+1))&&(n--,r++);return n}function pt(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ht(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}function ft(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function mt(e,t,n){return ft(e,t,n,!1)}function gt(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return null==this?n:ft(this,t,n.bind(this))},set(e){ft(this,t,e)}})}var yt=!1,vt={configurable:!0,get(){yt=!0}};function bt(e,t,n){const r=Object.getPrototypeOf(e._zod);t in r&&lt!==e._zod?lt=void 0:(lt=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,vt);const e=yt;yt=!1;try{const r=n(this);return yt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),yt=yt||e,r}catch(r){throw delete this[t],yt=yt||e,r}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function wt(e,t,n,r){const o=function(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}(e,t);o&&Object.defineProperty(o,t,{configurable:!0,get(){const e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var xt;function St(e){const t=()=>e;return t["~constantCatch"]=!0,t}var kt={value:void 0,enumerable:!1},_t="captureStackTrace"in Error?Error:null;function Et(e,t,n,r){function o(e){this.def=e,this.constr=u,this.traits=/* @__PURE__ */new Set}o.prototype={};const i=n,s=i&&/* @__PURE__ */new WeakSet;function a(n,r){if(!n._zod){kt.value=new o(r);try{Object.defineProperty(n,"_zod",kt)}finally{kt.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){const e=Object.getPrototypeOf(n),t=n._zod.constr.prototype;let r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);const o=r??e;s.has(o)||(s.add(o),function(e,t){for(const n in t){const r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):gt(e,n,r.value)}}(o,i))}const a=u.prototype;for(const e in a)Object.prototype.hasOwnProperty.call(a,e)&&(e in n||(n[e]=a[e].bind(n)))}const c=r?.Parent??Object;class l extends c{}function u(e){const t=r?.Parent?function(e){const t=_t;if(t){const n=t.stackTraceLimit;if("number"==typeof n){try{t.stackTraceLimit=0}catch{return _t=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}(l):this;a(t,e);const n=t._zod.deferred;if(n){for(const e of n)e();t._zod.deferred=void 0}const o=globalThis.__zod_globalConfig?.postProcessor;return o&&o(t),t}return Object.defineProperty(l,"name",{value:e}),Object.defineProperty(u,"init",{value:a}),Object.defineProperty(u,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}var Ct=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},It=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(xt=globalThis).__zod_globalConfig??(xt.__zod_globalConfig={});var Tt=globalThis.__zod_globalConfig;function Mt(e){return e&&Object.assign(Tt,e),Tt}var Ot={get:function(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Fe,2)),e.message},set:function(e){this._zod.message=e},enumerable:!0,configurable:!0},Rt={value:void 0,enumerable:!1},zt={value:void 0,enumerable:!1},At=/* @__PURE__ */new WeakSet([Object.prototype,Error.prototype]),Pt=(e,t)=>{e.name="$ZodError",Rt.value=e._zod,Object.defineProperty(e,"_zod",Rt),zt.value=t,Object.defineProperty(e,"issues",zt),Rt.value=void 0,zt.value=void 0,Object.defineProperty(e,"message",Ot);const n=Object.getPrototypeOf(e);At.has(n)||(At.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){const e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Nt=Et("$ZodError",Pt),Dt=Et("$ZodError",Pt,void 0,{Parent:Error});function $t(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||("__proto__"===t?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Lt(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Ft=e=>{const t=(n,r,o,i)=>{const s=o?{...o,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Ct;if(a.issues.length){const n=new(i?.Err??e)(a.issues.map(e=>ct(e,s,Mt())));throw Ze(n,i?.callee??t),n}return a.value};return t},jt=e=>{const t=async(n,r,o,i)=>{const s=o?{...o,async:!0}:{async:!0};let a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const n=new(i?.Err??e)(a.issues.map(e=>ct(e,s,Mt())));throw Ze(n,i?.callee??t),n}return a.value};return t},Ut=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Ct;return i.issues.length?{success:!1,error:new(e??Nt)(i.issues.map(e=>ct(e,o,Mt())))}:{success:!0,data:i.value}},Wt=/* @__PURE__*/Ut(Dt),Bt=e=>async(t,n,r)=>{const o=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>ct(e,o,Mt())))}:{success:!0,data:i.value}},Ht=/* @__PURE__*/Bt(Dt),Zt=e=>{const t=Ft(e),n=(e,r,o,i)=>{const s=o?{...o,direction:"backward"}:{direction:"backward"};return t(e,r,s,Lt(n,i))};return n},qt=e=>{const t=Ft(e),n=(e,r,o,i)=>t(e,r,o,Lt(n,i));return n},Vt=e=>{const t=jt(e),n=async(e,r,o,i)=>{const s=o?{...o,direction:"backward"}:{direction:"backward"};return await t(e,r,s,Lt(n,i))};return n},Yt=e=>{const t=jt(e),n=async(e,r,o,i)=>await t(e,r,o,Lt(n,i));return n},Kt=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return Ut(e)(t,n,o)},Jt=e=>(t,n,r)=>Ut(e)(t,n,r),Xt=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return Bt(e)(t,n,o)},Gt=e=>async(t,n,r)=>Bt(e)(t,n,r),Qt=/^[cC][0-9a-z]{6,}$/,en=/^[0-9a-z]+$/,tn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,nn=/^[0-9a-vA-V]{20}$/,rn=/^[A-Za-z0-9]{27}$/,on=/^[a-zA-Z0-9_-]{21}$/;var sn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,an=/^([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})$/,cn=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)$/,ln=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var un=/^(?:(?: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])$/,dn=/^(([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}|:))$/,pn=/^((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])$/,hn=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mn=/^[A-Za-z0-9_-]*$/,gn=/^https?$/,yn=/^\+[1-9]\d{6,14}$/,vn="(?:(?:\\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])))";function bn(e){return new RegExp(`^${e}$`)}var wn=/*@__PURE__*/bn(vn);function xn(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}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}var Sn=/^-?\d+$/,kn=/^-?\d+(?:\.\d+)?$/,_n=/^(?:true|false)$/i,En=/^[^A-Z]*$/,Cn=/^[^a-z]*$/,In=/*@__PURE__*/Et("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Tn=e=>{const t=e.value;return!(n=t,null==n||void 0===t.length);var n},Mn={number:"number",bigint:"bigint",object:"date"},On=/*@__PURE__*/Et("$ZodCheckLessThan",(e,t)=>{In.init(e,t);const n=Mn[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:Mn[typeof r.value]??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})}}),Rn=/*@__PURE__*/Et("$ZodCheckGreaterThan",(e,t)=>{In.init(e,t);const n=Mn[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:Mn[typeof r.value]??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})}}),zn=/*@__PURE__*/Et("$ZodCheckMultipleOf",(e,t)=>{In.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?t.value===BigInt(0)||n.value%t.value!==BigInt(0):0!==function(e,t){const n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?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})}}),An=/*@__PURE__*/Et("$ZodCheckNumberFormat",(e,t)=>{In.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=tt[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=o,r.maximum=i,n&&(r.pattern=Sn)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a))return void s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,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}):s.issues.push({input:a,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}))}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Pn=/*@__PURE__*/Et("$ZodCheckMaxLength",(e,t)=>{var n;In.init(e,t),(n=e._zod.def).when??(n.when=Tn),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,o=r.length;if(("string"==typeof r&&o>t.maximum?dt(r):o)<=t.maximum)return;const i=pt(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Nn=/*@__PURE__*/Et("$ZodCheckMinLength",(e,t)=>{var n;In.init(e,t),(n=e._zod.def).when??(n.when=Tn),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,o=r.length;if(("string"==typeof r&&o>=t.minimum&&o<2*t.minimum?dt(r):o)>=t.minimum)return;const i=pt(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Dn=/*@__PURE__*/Et("$ZodCheckLengthEquals",(e,t)=>{var n;In.init(e,t),(n=e._zod.def).when??(n.when=Tn),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,o=r.length,i="string"==typeof r&&o>=t.length&&o<=2*t.length?dt(r):o;if(i===t.length)return;const s=pt(r),a=i>t.length;n.issues.push({origin:s,...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})}}),$n=/*@__PURE__*/Et("$ZodCheckStringFormat",(e,t)=>{var n,r;In.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=()=>{})}),Ln=/*@__PURE__*/Et("$ZodCheckRegex",(e,t)=>{$n.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})}}),Fn=/*@__PURE__*/Et("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=En),$n.init(e,t)}),jn=/*@__PURE__*/Et("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Cn),$n.init(e,t)}),Un=/*@__PURE__*/Et("$ZodCheckIncludes",(e,t)=>{In.init(e,t);const n=Xe(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})}}),Wn=/*@__PURE__*/Et("$ZodCheckStartsWith",(e,t)=>{In.init(e,t);const n=new RegExp(`^${Xe(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})}}),Bn=/*@__PURE__*/Et("$ZodCheckEndsWith",(e,t)=>{In.init(e,t);const n=new RegExp(`.*${Xe(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})}}),Hn=/*@__PURE__*/Et("$ZodCheckOverwrite",(e,t)=>{In.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Zn=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}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 o of r)this.content.push(o)}compile(){const e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {\n${t.join("\n")}\n};`)(...Object.values(this.closed))}},qn={major:4,minor:5,patch:4},Vn=/*@__PURE__*/Et("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=qn;const r=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(const i of o)for(const t of i._zod.onattach)t(e);if(0===o.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(t,n,r)=>{if(t.memo)return t;let o,i=rt(t);for(const s of n){if(s._zod.def.when){if(ot(t))continue;if(!s._zod.def.when(t))continue}else if(i)continue;const n=t.issues.length,a=s._zod.check(t);if(a instanceof Promise&&!1===r?.async)throw new Ct;if(o||a instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await a,t.issues.length!==n&&(at(t.issues,n,e),i||(i=rt(t,n)))});else{if(t.issues.length===n)continue;at(t.issues,n,e),i||(i=rt(t,n))}}return o?o.then(()=>t):t},n=(n,r,i)=>{if(rt(n))return n.aborted=!0,n;const s=t(r,o,i);if(s instanceof Promise){if(!1===i.async)throw new Ct;return s.then(t=>e._zod.parse(t,i))}return e._zod.parse(s,i)};e._zod.run=(r,i)=>{if(i.skipChecks)return e._zod.parse(r,i);if("backward"===i.direction){const t=e._zod.parse({value:r.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,i)):n(t,r,i)}const s=e._zod.parse(r,i);if(s instanceof Promise){if(!1===i.async)throw new Ct;return s.then(e=>t(e,o,i))}return t(s,o,i)}}},{get"~standard"(){return mt(this,"~standard",Kn(this))},set"~standard"(e){ft(this,"~standard",e)}}),Yn=e=>e.success?{value:e.data}:{issues:e.error?.issues};function Kn(e){return{validate:t=>{try{return Yn(Wt(e,t))}catch(n){return Ht(e,t).then(Yn)}},vendor:"zod",version:1}}var Jn=/*@__PURE__*/Et("$ZodString",(e,t)=>{var n;Vn.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}}),Xn=/*@__PURE__*/Et("$ZodStringFormat",(e,t)=>{$n.init(e,t),Jn.init(e,t)}),Gn=/*@__PURE__*/Et("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=an),Xn.init(e,t)}),Qn=/*@__PURE__*/Et("$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=cn(e))}else t.pattern??(t.pattern=cn());Xn.init(e,t)}),er=/*@__PURE__*/Et("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ln),Xn.init(e,t)});var tr=/[\t\n\r]/g;var nr=/*@__PURE__*/Et("$ZodURL",(e,t)=>{Xn.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=function(e,t){if(!t.normalize&&t.protocol?.source===gn.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}(r,t);return 1===o?void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort}):2===o?void n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort}):(t.hostname&&!function(e,t){return t.lastIndex=0,t.test(e.hostname)}(o,t.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&&!function(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}(o,t.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(n.value=t.normalize?o.href:function(e){return e.replace(tr,"")}(r)))}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),rr=/*@__PURE__*/Et("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),Xn.init(e,t)}),or=/*@__PURE__*/Et("$ZodNanoID",(e,t)=>{if(void 0!==t.length&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);var n;t.pattern??(t.pattern=void 0===t.length?on:(n=t.length,new RegExp(`^[a-zA-Z0-9_-]{${n}}$`))),Xn.init(e,t)}),ir=/*@__PURE__*/Et("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Qt),Xn.init(e,t)}),sr=/*@__PURE__*/Et("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=en),Xn.init(e,t)}),ar=/*@__PURE__*/Et("$ZodULID",(e,t)=>{t.pattern??(t.pattern=tn),Xn.init(e,t)}),cr=/*@__PURE__*/Et("$ZodXID",(e,t)=>{t.pattern??(t.pattern=nn),Xn.init(e,t)}),lr=/*@__PURE__*/Et("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=rn),Xn.init(e,t)}),ur=/*@__PURE__*/Et("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${xn({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${xn({precision:e.precision})}`:n;return new RegExp(`^${vn}T(?:${r})$`)}(t)),Xn.init(e,t),(t.local||-1===t.precision)&&(e._zod.bag.laxFormat=!0,e._zod.onattach.push(e=>{e._zod.bag.laxFormat=!0}))}),dr=/*@__PURE__*/Et("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=wn),Xn.init(e,t)}),pr=/*@__PURE__*/Et("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${xn(t)}$`)),Xn.init(e,t)}),hr=/*@__PURE__*/Et("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=sn),Xn.init(e,t)}),fr=/*@__PURE__*/Et("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=un),Xn.init(e,t),e._zod.bag.format="ipv4"}),mr=/^[0-9a-fA-F:.]+$/;function gr(e){if(!mr.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}var yr=/*@__PURE__*/Et("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=dn),Xn.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{gr(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),vr=/*@__PURE__*/Et("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=pn),Xn.init(e,t)});var br=/*@__PURE__*/Et("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=hn),Xn.init(e,t),e._zod.check=n=>{(function(e){const t=e.split("/");if(2!==t.length)return!1;const[n,r]=t;if(!r)return!1;const o=Number(r);return`${o}`===r&&!(o<0||o>128)&&gr(n)})(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function wr(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 xr=/*@__PURE__*/Et("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=fn),Xn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{wr(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var Sr=/*@__PURE__*/Et("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mn),Xn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!mn.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return wr(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})}}),kr=/*@__PURE__*/Et("$ZodE164",(e,t)=>{t.pattern??(t.pattern=yn),Xn.init(e,t)});var _r=/*@__PURE__*/Et("$ZodJWT",(e,t)=>{Xn.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 o=JSON.parse(atob(r));return!("typ"in o&&"JWT"!==o?.typ||!o.alg||t&&(!("alg"in o)||o.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})}}),Er=/*@__PURE__*/Et("$ZodNumber",(e,t)=>{Vn.init(e,t),e._zod.pattern=e._zod.bag.pattern??kn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Cr=/*@__PURE__*/Et("$ZodNumberFormat",(e,t)=>{An.init(e,t),Er.init(e,t)}),Ir=/*@__PURE__*/Et("$ZodBoolean",(e,t)=>{Vn.init(e,t),e._zod.pattern=_n,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}const o=n.value;return"boolean"==typeof o||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Tr=/*@__PURE__*/Et("$ZodUnknown",(e,t)=>{Vn.init(e,t),e._zod.parse=e=>e}),Mr=/*@__PURE__*/Et("$ZodNever",(e,t)=>{Vn.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),Or=/*@__PURE__*/Et("$ZodDate",(e,t)=>{Vn.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}const o=n.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),n}});function Rr(e,t,n){e.issues.length&&t.issues.push(...it(n,e.issues)),t.value[n]=e.value}var zr=/*@__PURE__*/Et("$ZodArray",(e,t)=>{Vn.init(e,t);const n=Tt.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=n?n.alloc(e,r,Array(i.length),o):Array(i.length);const s=[];for(let e=0;e<i.length;e++){const n=i[e],a=t.element._zod.run({value:n,issues:[]},o);a instanceof Promise?s.push(a.then(t=>Rr(t,r,e))):Rr(a,r,e)}return s.length?Promise.all(s).then(()=>r):r}});function Ar(e,t,n,r,o,i){const s=n in r,a="optional"===i;if(s||!a||"optional"!==o){if(e.issues.length){if(void 0!==o&&a&&!s)return;t.issues.push(...it(n,e.issues))}s||void 0!==o?void 0===e.value?s&&(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]})}}var Pr=[];function Nr(e){const t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Pr,o=r.length?[...t,...r]:t;for(const a of o)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(a)}": expected a Zod schema`);const i=(s=e.shape,Object.keys(s).filter(e=>void 0!==s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{...e,allKeys:o,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function Dr(e,t,n,r,o,i){const s=[],a=o.keySet,c=o.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(const p in t){if(a.has(p))continue;if("__proto__"===p){"never"===l&&s.push(p);continue}if("never"===l){s.push(p);continue}const o=c.run({value:t[p],issues:[]},r);o instanceof Promise?e.push(o.then(e=>Ar(e,n,p,t,u,d))):Ar(o,n,p,t,u,d)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var $r=/* @__PURE__ */new WeakMap,Lr=/*@__PURE__*/Et("$ZodObject",(e,t)=>{if(Vn.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const e=t.shape;$r.set(t,e),Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),$r.set(t,n),n}})}const n=je(()=>Nr(t));bt(e,"propValues",e=>{const t=e.def.shape,n={};for(const r in t){const e=t[r]._zod;if(e.values){Object.prototype.hasOwnProperty.call(n,r)||We(n,r,/* @__PURE__ */new Set);for(const t of e.values)n[r].add(t);void 0!==e.optin&&n[r].add(void 0)}}return n});const r=qe,o=t.catchall;let i;const s=Tt.memoizer;s?.attach(e),e._zod.parse=(t,a)=>{i??(i=n.value);const c=t.value;if(!r(c))return t.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),t;t.value=s?s.alloc(e,t,{},a):{};const l=[],u=i.shape;for(const e of i.allKeys){if("__proto__"===e)continue;const n=u[e],r=n._zod.optin,o=n._zod.optout,i=n._zod.run({value:c[e],issues:[]},a);i instanceof Promise?l.push(i.then(n=>Ar(n,t,e,c,r,o))):Ar(i,t,e,c,r,o)}return o?Dr(l,c,t,a,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),Fr=/*@__PURE__*/Et("$ZodObjectJIT",(e,t)=>{Lr.init(e,t);const n=e._zod.parse,r=je(()=>Nr(t)),o=Tt.memoizer;let i;const s=qe,a=!Tt.jitless,c=a&&Ve.value,l=t.catchall;let u;e._zod.parse=(d,p)=>{u??(u=r.value);const h=d.value;return s(h)?a&&c&&!1===p?.async&&!0!==p.jitless?(i||(i=(t=>{const n=r.value,i=n.symbolKeys,s=new Zn(["payload","ctx"],{shape:t,inst:e,memo:o,syms:i}),a=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`\n for (let i = 0; i < ${e}.issues.length; i++) {\n const iss = ${e}.issues[i];\n iss.path = iss.path ? [${t}, ...iss.path] : [${t}];\n payload.issues.push(iss);\n }`;s.write("const input = payload.value;");const l=Object.create(null);let u=0;for(const e of n.allKeys)l[e]="key_"+u++;s.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const e of n.allKeys){if("__proto__"===e)continue;const n=l[e],r="symbol"==typeof e?`syms[${i.indexOf(e)}]`:He(e),o=`${r} in input`,u=t[e],d=u?._zod?.optin,p=void 0!==d,h="optional"===u?._zod?.optout;if(s.write(`const ${n} = ${a(r)};`),p&&h){const e="optional"===d?`${n}_present`:`${n}.value !== undefined || ${n}_present`;s.write(`\n const ${n}_present = ${o};\n if (!${n}.issues.length || ${n}_present) {\n if (${n}.issues.length) {${c(n,r)}\n }\n\n if (${e}) {\n newResult[${r}] = ${n}.value;\n }\n }\n\n `)}else p?s.write(`\n if (${n}.issues.length) {${c(n,r)}\n }\n \n if (${n}.value === undefined) {\n if (${o}) {\n newResult[${r}] = undefined;\n }\n } else {\n newResult[${r}] = ${n}.value;\n }\n\n `):s.write(`\n const ${n}_present = ${o};\n if (${n}.issues.length) {${c(n,r)}\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${r}]\n });\n }\n\n if (${n}_present) {\n newResult[${r}] = ${n}.value;\n }\n\n `)}return s.write("payload.value = newResult;"),s.write("return payload;"),s.compile()})(t.shape)),d=i(d,p),l?Dr([],h,d,p,u,e):d):n(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),d)}});function jr(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const o=e.filter(e=>!rt(e));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ct(e,r,Mt())))}),t)}var Ur=/*@__PURE__*/Et("$ZodUnion",(e,t)=>{Vn.init(e,t),bt(e,"optin",e=>e.def.options.some(e=>"defaulted"===e._zod.optin)?"defaulted":e.def.options.some(e=>void 0!==e._zod.optin)?"optional":void 0),bt(e,"optout",e=>e.def.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),bt(e,"values",e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),bt(e,"pattern",e=>{if(e.def.options.every(e=>e._zod.pattern)){const t=e.def.options.map(e=>e._zod.pattern);return new RegExp(`^(${t.map(e=>Ue(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},o);if(t instanceof Promise)s.push(t),i=!0;else{if(0===t.issues.length)return t;s.push(t)}}return i?Promise.all(s).then(t=>jr(t,r,e,o)):jr(s,r,e,o)}}),Wr=/*@__PURE__*/Et("$ZodIntersection",(e,t)=>{Vn.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([t,n])=>Hr(e,t,n)):Hr(e,o,i)}});function Br(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(Ye(e)&&Ye(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),o={...e,...t};Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__;for(const i of r){if("__proto__"===i)continue;const n=Br(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};o[i]=n.data}return{valid:!0,data:o}}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 o=Br(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Hr(e,t,n){const r=/* @__PURE__ */new Map;let o;const i=/* @__PURE__ */new Map,s=(e,t)=>{let n;if("unrecognized_keys"!==e.code||e.path?.length){if("invalid_key"!==e.code||"record"!==e.origin||1!==e.path?.length)return!1;{const t=String(e.path[0]);i.has(t)||i.set(t,e),n=[t]}}else o??(o=e),n=e.keys;for(const o of n)r.has(o)||r.set(o,{}),r.get(o)[t]=!0;return!0};for(const l of t.issues)s(l,"l")||e.issues.push(l);for(const l of n.issues)s(l,"r")||e.issues.push(l);const a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length){const t=o?a.filter(e=>o.keys.includes(e)):[];t.length&&e.issues.push({...o,keys:t});for(const n of a)!t.includes(n)&&i.has(n)&&e.issues.push(i.get(n))}const c=Br(t.value,n.value);if(!c.valid){if(rt(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Zr=/*@__PURE__*/Et("$ZodRecord",(e,t)=>{Vn.init(e,t);const n=Tt.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{const i=r.value;if(!Ye(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;const s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};const c=/* @__PURE__ */new Set;for(const n of a)if("string"==typeof n||"number"==typeof n||"symbol"==typeof n){if(c.add("number"==typeof n?n.toString():n),"__proto__"===n)continue;const a=t.keyType._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>ct(e,o,Mt())),input:n,path:[n],inst:e});continue}const l=a.value;if("__proto__"===l)continue;const u=t.valueType._zod.run({value:i[n],issues:[]},o);u instanceof Promise?s.push(u.then(e=>{e.issues.length&&r.issues.push(...it(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...it(n,u.issues)),r.value[l]=u.value)}let l;for(const e in i)if(!c.has(e))if("loose"===t.mode){if("__proto__"===e)continue;r.value[e]=i[e]}else l=l??[],l.push(e);l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l,continue:!0})}else{let c;r.value=n?n.alloc(e,r,{},o):{};for(const n of Reflect.ownKeys(i)){if("__proto__"===n)continue;if(!Object.prototype.propertyIsEnumerable.call(i,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof n&&kn.test(n)&&l.issues.length){const e=t.keyType._zod.run({value:Number(n),issues:[]},o);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(l=e)}if(l.issues.length){"loose"===t.mode?r.value[n]=i[n]:a?(c=c??[],c.push(n)):r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(e=>ct(e,o,Mt())),input:n,path:[n],inst:e});continue}const u=l.value;if("__proto__"===u)continue;const d=t.valueType._zod.run({value:i[n],issues:[]},o);d instanceof Promise?s.push(d.then(e=>{e.issues.length&&r.issues.push(...it(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...it(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c,continue:!0})}return s.length?Promise.all(s).then(()=>r):r}}),qr=/*@__PURE__*/Et("$ZodEnum",(e,t)=>{Vn.init(e,t);const n=$e(t.entries),r=new Set(n);e._zod.values=r;const o=n.filter(e=>Je.has(typeof e));e._zod.pattern=new RegExp(o.length?`^(${o.map(e=>Xe(e.toString())).join("|")})$`:"^[^\\s\\S]$"),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),Vr=/*@__PURE__*/Et("$ZodLiteral",(e,t)=>{Vn.init(e,t);const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(t.values.length?`^(${t.values.map(e=>"string"==typeof e?Xe(e):e?Xe(e.toString()):String(e)).join("|")})$`:"^[^\\s\\S]$"),e._zod.parse=(r,o)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),Yr=/*@__PURE__*/Et("$ZodTransform",(e,t)=>{Vn.init(e,t),e._zod.optin="optional",Tt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new It(e.constructor.name);const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n));if(o instanceof Promise)throw new Ct;return n.value=o,n}});function Kr(e,t){return e.value=t.issues.length?void 0:t.value,e}var Jr=/*@__PURE__*/Et("$ZodOptional",(e,t)=>{Vn.init(e,t),bt(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),e._zod.optout="optional",bt(e,"values",e=>{const t=e.def.innerType._zod.values;return t?/* @__PURE__ */new Set([...t,void 0]):void 0}),bt(e,"pattern",e=>{const t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Ue(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(void 0===e.value){if("defaulted"!==t.innerType._zod.optin)return e;const r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Kr(e,t)):Kr(e,r)}return t.innerType._zod.run(e,n)}}),Xr=/*@__PURE__*/Et("$ZodExactOptional",(e,t)=>{Jr.init(e,t),bt(e,"values",e=>e.def.innerType._zod.values),bt(e,"pattern",e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Gr=/*@__PURE__*/Et("$ZodNullable",(e,t)=>{Vn.init(e,t),bt(e,"optin",e=>e.def.innerType._zod.optin),bt(e,"optout",e=>e.def.innerType._zod.optout),bt(e,"pattern",e=>{const t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Ue(t.source)}|null)$`):void 0}),bt(e,"values",e=>e.def.innerType._zod.values?/* @__PURE__ */new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Qr=/*@__PURE__*/Et("$ZodDefault",(e,t)=>{Vn.init(e,t),e._zod.optin="defaulted",bt(e,"values",e=>e.def.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=>eo(e,t)):eo(r,t)}});function eo(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var to=/*@__PURE__*/Et("$ZodPrefault",(e,t)=>{Vn.init(e,t),e._zod.optin="defaulted",bt(e,"values",e=>e.def.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))}),no=/*@__PURE__*/Et("$ZodNonOptional",(e,t)=>{Vn.init(e,t),bt(e,"values",e=>{const t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(t=>ro(t,e)):ro(o,e)}});function ro(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function oo(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>ct(e,r,Mt()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var io=/*@__PURE__*/Et("$ZodCatch",(e,t)=>{Vn.init(e,t),bt(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),bt(e,"optout",e=>e.def.innerType._zod.optout),bt(e,"values",e=>e.def.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({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>oo(e,r,t,n)):oo(e,r,t,n)}}),so=/*@__PURE__*/Et("$ZodPipe",(e,t)=>{Vn.init(e,t),bt(e,"values",e=>e.def.in._zod.values),bt(e,"optin",e=>e.def.in._zod.optin),bt(e,"optout",e=>e.def.out._zod.optout),bt(e,"propValues",e=>e.def.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=>ao(e,t.in,n)):ao(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ao(e,t.out,n)):ao(r,t.out,n)}});function ao(e,t,n){return e.issues.some(e=>"unrecognized_keys"!==e.code)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var co=/*@__PURE__*/Et("$ZodReadonly",(e,t)=>{Vn.init(e,t),bt(e,"propValues",e=>e.def.innerType._zod.propValues),bt(e,"values",e=>e.def.innerType._zod.values),bt(e,"optin",e=>e.def.innerType?._zod?.optin),bt(e,"optout",e=>e.def.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(lo):lo(r)}});function lo(e){return e.memo||(e.value=Object.freeze(e.value)),e}var uo=/*@__PURE__*/Et("$ZodCustom",(e,t)=>{In.init(e,t),Vn.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(t=>po(t,n,r,e));po(o,n,r,e)}});function po(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(ht(e))}}var ho=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},fo="~memo",mo=[];function go(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var yo,vo=/*@__PURE__*/new WeakMap;function bo(e,t){const n=vo.get(e);if(void 0!==n)return n;if(t.has(e))return!0;t.add(e);let r=!1;const o=e=>{!r&&e?._zod&&bo(e,t)&&(r=!0)},i=e._zod.def;switch(i.type){case"object":for(const e of Reflect.ownKeys(i.shape))o(i.shape[e]);o(i.catchall);break;case"array":o(i.element);break;case"tuple":for(const e of i.items)o(e);o(i.rest);break;case"record":case"map":o(i.keyType),o(i.valueType);break;case"set":o(i.valueType);break;case"union":for(const e of i.options)o(e);break;case"intersection":o(i.left),o(i.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(i.innerType);break;case"pipe":o(i.in),o(i.out);break;case"function":o(i.input),o(i.output);break;case"lazy":o(e._zod.innerType);break;case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const e in i){const t=Object.getOwnPropertyDescriptor(i,e);if(!t||t.get)continue;const n=t.value;if(n&&"object"==typeof n)if(n._zod)o(n);else if(Array.isArray(n))for(const e of n)o(e)}}return t.delete(e),vo.set(e,r),r}var wo=[],xo={alloc(e,t,n){const r=yo;if(!r)return n;yo=void 0;const o={value:n,issues:null};return r.set(t.value,o),wo.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const t=e._zod.parse,n=(e,n)=>{if("backward"!==n.direction&&function(e,t){const n=e[fo]?.backEdges;return void 0!==n&&null!==t&&"object"==typeof t&&n.has(t)}(n,e.value))throw new ho;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const t=e._zod.parse,i=(s,a)=>{if(void 0===n&&(n=bo(e,/* @__PURE__ */new Set),!n))return e._zod.parse=t,e._zod.run===i&&(e._zod.run=t),t(s,a);const c=s.value;if(null===c||"object"!=typeof c)return t(s,a);let l,u=a[fo];u||(u={buckets:/* @__PURE__ */new Map,backEdges:void 0},a[fo]=u),r===a?l=o:(l=function(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */new Map,e.buckets.set(t,n)),n}(u,e),r=a,o=l);const d=l.get(c);if(d)return s.value=d.value,d.issues?d.issues.length&&s.issues.push(...go(d.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */new Set),u.backEdges.add(d.value)),s;yo=l;const p=wo.length,h=t(s,a);yo=void 0;const f=wo.length>p?wo.pop():void 0;return h instanceof Promise?h.then(e=>(f&&(f.issues=e.issues.length?go(e.issues):mo),e)):(f&&(f.issues=h.issues.length?go(h.issues):mo),h)};e._zod.parse=i,e._zod.run===t&&(e._zod.run=i)})}};var So,ko=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",credit_card:"credit card number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(e,t){return"number"!==e||"number"!=typeof t||Number.isFinite(t)?r[e]??e:String(t)}return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${o(e.expected)}, received ${o(function(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(null===e)return"null";if(Array.isArray(e))return"array";const t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return t}(e.input),e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${et(e.values[0])}`:`Invalid option: expected one of ${Le(e.values,"|")}`;case"too_big":{const n=e.exact?"exactly ":e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.exact?"exactly ":e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Le(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(" | ")}`:!1===e.inclusive?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`;default:return"Invalid input"}}};var _o=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)}};(So=globalThis).__zod_globalRegistry??(So.__zod_globalRegistry=new _o);var Eo=globalThis.__zod_globalRegistry;function Co(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Qe(t)})}function Io(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Qe(t)})}function To(e,t){return new On({check:"less_than",...Qe(t),value:e,inclusive:!1})}function Mo(e,t){return new On({check:"less_than",...Qe(t),value:e,inclusive:!0})}function Oo(e,t){return new Rn({check:"greater_than",...Qe(t),value:e,inclusive:!1})}function Ro(e,t){return new Rn({check:"greater_than",...Qe(t),value:e,inclusive:!0})}function zo(e,t){return new zn({check:"multiple_of",...Qe(t),value:e})}function Ao(e,t){return new Pn({check:"max_length",...Qe(t),maximum:e})}function Po(e,t){return new Nn({check:"min_length",...Qe(t),minimum:e})}function No(e,t){return new Dn({check:"length_equals",...Qe(t),length:e})}function Do(e){return new Hn({check:"overwrite",tx:e})}function $o(e,t){const n=new In({check:"custom",...Qe(t)});return n._zod.check=e,n}function Lo(e,...t){for(const n of t)for(const t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&We(e,t,n[t]);return e}function Fo(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??Eo,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:/* @__PURE__ */new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function jo(e,t,n,r,o){const i="function"==typeof t.unrepresentable?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if("any"===i)return!1;if(void 0===i||"throw"===i)throw new Error(o);return Object.assign(n,i),!0}function Uo(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{const n=s.schema,i=t.processors[o.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(s.ref||(s.ref=i),Uo(i,t,r),t.seen.get(i).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Lo(s.schema,c),"input"===t.io&&Xo(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Wo(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Bo(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;const r=/* @__PURE__ */new Map;for(const i of e.seen.entries()){const t=e.metadataRegistry.get(i[0])?.id;if(t){const e=r.get(t);if(e&&e!==i[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,i[0])}}const o=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:o,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,o=e.external.uri??(e=>e);if(n)return{ref:o(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${o("__shared")}#/${r}/${Wo(i)}`}}const o=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:"#"};const i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:o+Wo(i)}})(t);r.def={...r.schema},i&&(r.defId=i);const s=r.schema;for(const e in s)delete s[e];s.$ref=o};if("throw"===e.cycles)for(const i of e.seen.entries()){const e=i[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 i of e.seen.entries()){const n=i[1];if(t!==i[0]){if(e.external){const n=e.external.registry.get(i[0])?.id;if(t!==i[0]&&n){o(i);continue}}(e.metadataRegistry.get(i[0])?.id||n.cycle||n.count>1&&"ref"===e.reused)&&o(i)}else o(i)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Ho(e){const t=e.anyOf;if(!Array.isArray(t)||0===t.length||void 0!==e.type)return;const n=[];for(const r of t){if(!r||"object"!=typeof r)return;Ho(r);const e=Object.keys(r);if(1!==e.length||"type"!==e[0])return;const t=r.type;for(const r of Array.isArray(t)?t:[t]){if("string"!=typeof r)return;n.includes(r)||n.push(r)}}delete e.anyOf,e.type=1===n.length?n[0]:n}var Zo=/* @__PURE__ */new Set(["type","properties","required","additionalProperties"]),qo=["oneOf","anyOf"];function Vo(e){const t=e.additionalProperties;return void 0===t||!1===t||"object"!=typeof t||null===t?null:Object.keys(t).length?t:null}function Yo(e){const t=[];for(const i of e){if("object"!=typeof i||"object"!==i.type)return null;for(const e in i)if(!Zo.has(e))return null;t.push(i)}const n={},r=/* @__PURE__ */new Set;for(const i of t){for(const e in i.properties){if(Object.prototype.hasOwnProperty.call(n,e))continue;const r=[];for(const n of t){const t=n.properties?.[e]??Vo(n);null!=t&&(r.some(e=>JSON.stringify(e)===JSON.stringify(t))||r.push(t))}We(n,e,1===r.length?r[0]:Yo(r)??{allOf:r})}for(const e of i.required??[])r.add(e)}const o={type:"object",properties:n};if(r.size&&(o.required=[...r]),t.every(e=>!1===e.additionalProperties))o.additionalProperties=!1;else{const e=[];for(const n of t){const t=Vo(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}1===e.length?o.additionalProperties=e[0]:e.length>1&&(o.additionalProperties={allOf:e})}return o}function Ko(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const o of Zo)if(o in e)return;const n=t.filter(e=>qo.some(t=>Array.isArray(e[t])));let r=null;if(n.length){const e=n[0],o=qo.find(t=>Array.isArray(e[t]));if(1!==Object.keys(e).length)return;const i=t.filter(t=>t!==e),s=e[o].map(e=>Yo([...i,e]));if(s.some(e=>!e))return;r={[o]:s}}else r=Yo(t);r&&(delete e.allOf,Lo(e,r))}function Jo(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 o=n.def??n.schema,i={...o},s=n.ref;if(n.ref=null,s){r(s);const n=e.seen.get(s),a=n.schema;if(!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Lo(o,a):(o.allOf=o.allOf??[],o.allOf.push(a)),Lo(o,i),t._zod.parent===s)for(const e in o)"$ref"!==e&&"allOf"!==e&&(e in i||delete o[e]);if(a.$ref&&n.def)for(const e in o)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(o[e])===JSON.stringify(n.def[e])&&delete o[e]}const a=t._zod.parent;if(a&&a!==s){r(a);const t=e.seen.get(a);if(t?.schema.$ref&&(o.$ref=t.schema.$ref,t.def))for(const e in o)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(o[e])===JSON.stringify(t.def[e])&&delete o[e]}e.override({zodSchema:t,jsonSchema:o,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const t of[...e.seen.entries()].reverse())r(t[0]);if("openapi-3.0"!==e.target)for(const t of e.seen.entries())Ho(t[1].def??t[1].schema);for(const t of e.deferred)t();if(e.intersections.length){const t=/* @__PURE__ */new Map;for(const n of e.seen.values())for(const e of[n.schema,n.def]){const n=e?.allOf;if(!Array.isArray(n))continue;const r=t.get(n);r?r.push(e):t.set(n,[e])}for(const n of e.intersections)for(const e of t.get(n)??[])Ko(e)}}const o={};if("draft-2020-12"===e.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?o.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?o.$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");o.$id=e.external.uri(n)}Lo(o,n.defId?n.schema:n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;void 0!==i&&o.id===i&&delete o.id;const s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const c of e.seen.entries()){const e=c[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,We(s,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?o.$defs=s:o.definitions=s);try{const n=JSON.parse(JSON.stringify(o));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:Go(t,"input",e.processors),output:Go(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(a){throw new Error("Error converting schema to JSON.")}}function Xo(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 Xo(r.element,n);if("set"===r.type)return Xo(r.valueType,n);if("lazy"===r.type)return Xo(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||"catch"===r.type)return Xo(r.innerType,n);if("intersection"===r.type)return Xo(r.left,n)||Xo(r.right,n);if("record"===r.type||"map"===r.type)return Xo(r.keyType,n)||Xo(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(Xo(r.in,n)||Xo(r.out,n));if("object"===r.type){for(const e in r.shape)if(Xo(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(Xo(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(Xo(e,n))return!0;return!(!r.rest||!Xo(r.rest,n))}return!1}var Go=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},s=Fo({...o??{},target:i,io:t,processors:n});return Uo(e,s),Bo(s,e),Jo(s,e)},Qo={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};function ei(e){const t=e._zod.def;return"pipe"===t.type&&t.in._zod.traits.has("$ZodTransform")?ei(t.out):"catch"===t.type?ei(t.innerType):e._zod.optin}function ti(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);const r=e.get(t)?.def;if(!r)return t;const o=ti(e,r,n);return o===r?t:o}for(const f of["anyOf","oneOf"]){const r=t[f];if(!Array.isArray(r))continue;const o=r.map(t=>ti(e,t,n));o.some((e,t)=>e!==r[t])&&(t={...t,[f]:o})}const r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some(e=>"number"===e||"integer"===e),i=t.enum??(void 0!==t.const?[t.const]:void 0);if(!o&&!i?.some(e=>"number"==typeof e))return t;const{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:p,...h}=t;return h.enum?h.enum=h.enum.map(e=>"number"==typeof e?String(e):e):"number"==typeof h.const&&(h.const=String(h.const)),o?(h.type="string",i||(h.pattern=(r.includes("number")?kn:Sn).source),h):h}var ni=/* @__PURE__ */new WeakMap;var ri=(e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object";const s=i.keyType,a=s._zod.bag?.patterns;if("loose"===i.mode&&a&&a.size>0){const e=Uo(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const t of a)We(o.patternProperties,t.source,e)}else{if("draft-07"===t.target||"draft-2020-12"===t.target){o.propertyNames=Uo(i.keyType,t,{...r,path:[...r.path,"propertyNames"]});let n=ni.get(t);n||(n=[],ni.set(t,n),t.deferred.push(()=>function(e){const t=/* @__PURE__ */new Map;for(const r of e.seen.values())r.def&&!t.has(r.schema)&&t.set(r.schema,r);const n=/* @__PURE__ */new Map;for(const r of ni.get(e)??[]){const o=e.seen.get(r),i=(o?.def??o?.schema)?.propertyNames;if(!i||!0===i||n.has(i))continue;const s=ti(t,i,/* @__PURE__ */new Set);s!==i&&n.set(i,s)}if(n.size)for(const r of e.seen.values())for(const e of[r.schema,r.def]){const t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}(t))),n.push(e)}o.additionalProperties=Uo(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}const c=s._zod.values,l="input"===t.io&&void 0!==ei(i.valueType);if(c&&!i.partial&&!l){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(o.required=e.map(String))}},oi=Symbol();function ii(e,t,n,r,o){let i=!1;const s=JSON.stringify(e,(e,t)=>"bigint"!=typeof t?t:(i=!0,null));return i?(jo(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),oi):JSON.parse(s)}var si=(e,t,n,r)=>{const o=e._zod.def;Uo(o.innerType,t,r);t.seen.get(e).ref=o.innerType},ai=/* @__PURE__ */new WeakSet([Object.prototype,Error.prototype]);function ci(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var li=(e,t)=>{Nt.init(e,t),e.name="ZodError";const n=Object.getPrototypeOf(e);ai.has(n)||(ai.add(n),ci(n,"format",e=>t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,o=[])=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e},[...o,...i.path]));else if("invalid_key"===i.code)r({issues:i.issues},[...o,...i.path]);else if("invalid_element"===i.code)r({issues:i.issues},[...o,...i.path]);else{const e=[...o,...i.path];if(0===e.length)n._errors.push(t(i));else{let r=n,o=0;for(;o<e.length;){const n=e[o],s=o===e.length-1;if("_errors"===n){s&&r._errors.push(t(i)),o++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});const a=r[n];s&&a._errors.push(t(i)),r=a,o++}}}};return r(e),n}(e,t)),ci(n,"flatten",e=>t=>function(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?$t(n,o.path[0],()=>[]).push(t(o)):r.push(t(o));return{formErrors:r,fieldErrors:n}}(e,t)),ci(n,"addIssue",e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Fe,2)}),ci(n,"addIssues",e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Fe,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},ui=/*@__PURE__*/Et("ZodError",li,void 0,{Parent:Error}),di=/* @__PURE__ */Ft(ui),pi=/* @__PURE__ */jt(ui),hi=/* @__PURE__ */Ut(ui),fi=/* @__PURE__ */Bt(ui),mi=/* @__PURE__ */Zt(ui),gi=/* @__PURE__ */qt(ui),yi=/* @__PURE__ */Vt(ui),vi=/* @__PURE__ */Yt(ui),bi=/* @__PURE__ */Kt(ui),wi=/* @__PURE__ */Jt(ui),xi=/* @__PURE__ */Xt(ui),Si=/* @__PURE__ */Gt(ui);function ki(){Tt.localeError||Mt({localeError:ko()})}function _i(){Tt.memoizer||Mt({memoizer:xo})}var Ei=/*@__PURE__*/Et("ZodType",(e,t)=>(ki(),Vn.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(Be(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 Ge(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,...Qe(n)})}(Ns,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return function(e,t){const n=/* @__PURE__ */$o(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(ht(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),"input"in r||(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(ht(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(Do(e))},optional(){return _s(this)},exactOptional(){return new Es({type:"optional",innerType:this})},nullable(){return Is(this)},nullish(){return _s(Is(this))},nonoptional(e){return function(e,t){return new Os({type:"nonoptional",innerType:e,...Qe(t)})}(this,e)},array(){return ds(this)},or(e){return ms([this,e])},and(e){return new gs({type:"intersection",left:this,right:e})},transform(e){return As(this,new Ss({type:"transform",transform:e}))},default(e){return t=e,new Ts({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():Ke(t)}});var t},prefault(e){return t=e,new Ms({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():Ke(t)}});var t},catch(e){return new Rs({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:St(t)});var t},pipe(e){return As(this,e)},readonly(){return new Ps({type:"readonly",innerType:this})},describe(e){const t=this.clone();return Eo.add(t,{description:e}),t},meta(...e){if(0===e.length)return Eo.get(this);const t=this.clone();return Eo.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return 0===t.length?e(this):e(this,...t)},get"~standard"(){return mt(this,"~standard",{...Kn(this),jsonSchema:{input:Go(this,"input"),output:Go(this,"output")}})},set"~standard"(e){ft(this,"~standard",e)},parse:function e(t,n){return di(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await pi(this,t,n,{callee:e})},safeParse(e,t){return hi(this,e,t)},async safeParseAsync(e,t){return fi(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ft(this,"spa",e)},encode:function e(t,n){return mi(this,t,n,{callee:e})},decode:function e(t,n){return gi(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await yi(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await vi(this,t,n,{callee:e})},safeEncode(e,t){return bi(this,e,t)},safeDecode(e,t){return wi(this,e,t)},async safeEncodeAsync(e,t){return xi(this,e,t)},async safeDecodeAsync(e,t){return Si(this,e,t)},toJSONSchema(e){return((e,t={})=>n=>{const r=Fo({...n,processors:t});return Uo(e,r),Bo(r,e),Jo(r,e)})(this,{})(e)},get description(){return Eo.get(this)?.description},get _def(){return this._zod.def}}),Ci=/*@__PURE__*/Et("_ZodString",(e,t)=>{Jn.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:o,maximum:i,format:s,patterns:a,contentEncoding:c,laxFormat:l}=e._zod.bag;if("number"==typeof o&&(r.minLength=o),"number"==typeof i&&(r.maxLength=i),s&&(r.format=Qo[s]??s,""===r.format&&delete r.format,("time"===s||l)&&delete r.format),c&&(r.contentEncoding=c),a&&a.size>0){const e=[...a];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},{regex(...e){return this.check(function(e,t){return new Ln({check:"string_format",format:"regex",...Qe(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new Un({check:"string_format",format:"includes",...Qe(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Wn({check:"string_format",format:"starts_with",...Qe(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Bn({check:"string_format",format:"ends_with",...Qe(t),suffix:e})}(...e))},min(...e){return this.check(Po(...e))},max(...e){return this.check(Ao(...e))},length(...e){return this.check(No(...e))},nonempty(...e){return this.check(Po(1,...e))},lowercase(e){return this.check(function(e){return new Fn({check:"string_format",format:"lowercase",...Qe(e)})}(e))},uppercase(e){return this.check(function(e){return new jn({check:"string_format",format:"uppercase",...Qe(e)})}(e))},trim(){return this.check(/* @__PURE__ */Do(e=>e.trim()))},normalize(...e){return this.check(function(e){/* @__PURE__ */
2
- return Do(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(/* @__PURE__ */Do(e=>e.toLowerCase()))},toUpperCase(){return this.check(/* @__PURE__ */Do(e=>e.toUpperCase()))},slugify(){return this.check(/* @__PURE__ */Do(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}}),Ii=/*@__PURE__*/Et("ZodString",(e,t)=>{Jn.init(e,t),Ci.init(e,t)},{email(e){return this.check(Co(Pi,e))},url(e){return this.check(Io($i,e))},jwt(e){return this.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Qe(t)})}(Gi,e))},emoji(e){return this.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Qe(t)})}(Li,e))},guid(e){return this.check(function(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Qe(t)})}(Ni,e))},uuid(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Qe(t)})}(Di,e))},uuidv4(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Qe(t)})}(Di,e))},uuidv6(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Qe(t)})}(Di,e))},uuidv7(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Qe(t)})}(Di,e))},nanoid(e){return this.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Qe(t)})}(Fi,e))},cuid(e){return this.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Qe(t)})}(ji,e))},cuid2(e){return this.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Qe(t)})}(Ui,e))},ulid(e){return this.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Qe(t)})}(Wi,e))},base64(e){return this.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Qe(t)})}(Ki,e))},base64url(e){return this.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Qe(t)})}(Ji,e))},xid(e){return this.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Qe(t)})}(Bi,e))},ksuid(e){return this.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Qe(t)})}(Hi,e))},ipv4(e){return this.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Qe(t)})}(Zi,e))},ipv6(e){return this.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Qe(t)})}(qi,e))},cidrv4(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Qe(t)})}(Vi,e))},cidrv6(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Qe(t)})}(Yi,e))},e164(e){return this.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Qe(t)})}(Xi,e))},datetime(e){return this.check(function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Qe(t)})}(Oi,e))},date(e){return this.check(function(e,t){return new e({type:"string",format:"date",check:"string_format",...Qe(t)})}(Ri,e))},time(e){return this.check(function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Qe(t)})}(zi,e))},duration(e){return this.check(function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Qe(t)})}(Ai,e))}});function Ti(e){return function(e,t){return new e({type:"string",...Qe(t)})}(Ii,e)}var Mi=/*@__PURE__*/Et("ZodStringFormat",(e,t)=>{Xn.init(e,t),Ci.init(e,t)}),Oi=/*@__PURE__*/Et("ZodISODateTime",(e,t)=>{ur.init(e,t),Mi.init(e,t)}),Ri=/*@__PURE__*/Et("ZodISODate",(e,t)=>{dr.init(e,t),Mi.init(e,t)}),zi=/*@__PURE__*/Et("ZodISOTime",(e,t)=>{pr.init(e,t),Mi.init(e,t)}),Ai=/*@__PURE__*/Et("ZodISODuration",(e,t)=>{hr.init(e,t),Mi.init(e,t)}),Pi=/*@__PURE__*/Et("ZodEmail",(e,t)=>{er.init(e,t),Mi.init(e,t)});var Ni=/*@__PURE__*/Et("ZodGUID",(e,t)=>{Gn.init(e,t),Mi.init(e,t)}),Di=/*@__PURE__*/Et("ZodUUID",(e,t)=>{Qn.init(e,t),Mi.init(e,t)}),$i=/*@__PURE__*/Et("ZodURL",(e,t)=>{nr.init(e,t),Mi.init(e,t)});var Li=/*@__PURE__*/Et("ZodEmoji",(e,t)=>{rr.init(e,t),Mi.init(e,t)}),Fi=/*@__PURE__*/Et("ZodNanoID",(e,t)=>{or.init(e,t),Mi.init(e,t)}),ji=/*@__PURE__*/Et("ZodCUID",(e,t)=>{ir.init(e,t),Mi.init(e,t)}),Ui=/*@__PURE__*/Et("ZodCUID2",(e,t)=>{sr.init(e,t),Mi.init(e,t)}),Wi=/*@__PURE__*/Et("ZodULID",(e,t)=>{ar.init(e,t),Mi.init(e,t)}),Bi=/*@__PURE__*/Et("ZodXID",(e,t)=>{cr.init(e,t),Mi.init(e,t)}),Hi=/*@__PURE__*/Et("ZodKSUID",(e,t)=>{lr.init(e,t),Mi.init(e,t)}),Zi=/*@__PURE__*/Et("ZodIPv4",(e,t)=>{fr.init(e,t),Mi.init(e,t)}),qi=/*@__PURE__*/Et("ZodIPv6",(e,t)=>{yr.init(e,t),Mi.init(e,t)}),Vi=/*@__PURE__*/Et("ZodCIDRv4",(e,t)=>{vr.init(e,t),Mi.init(e,t)}),Yi=/*@__PURE__*/Et("ZodCIDRv6",(e,t)=>{br.init(e,t),Mi.init(e,t)}),Ki=/*@__PURE__*/Et("ZodBase64",(e,t)=>{xr.init(e,t),Mi.init(e,t)}),Ji=/*@__PURE__*/Et("ZodBase64URL",(e,t)=>{Sr.init(e,t),Mi.init(e,t)}),Xi=/*@__PURE__*/Et("ZodE164",(e,t)=>{kr.init(e,t),Mi.init(e,t)}),Gi=/*@__PURE__*/Et("ZodJWT",(e,t)=>{_r.init(e,t),Mi.init(e,t)}),Qi=/*@__PURE__*/Et("ZodNumber",(e,t)=>{Er.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;"string"==typeof a&&a.includes("int")?o.type="integer":o.type="number";const d="number"==typeof u&&u>=(i??Number.NEGATIVE_INFINITY),p="number"==typeof l&&l<=(s??Number.POSITIVE_INFINITY),h="draft-04"===t.target||"openapi-3.0"===t.target;d?h?(o.minimum=u,o.exclusiveMinimum=!0):o.exclusiveMinimum=u:"number"==typeof i&&(o.minimum=i),p?h?(o.maximum=l,o.exclusiveMaximum=!0):o.exclusiveMaximum=l:"number"==typeof s&&(o.maximum=s),"number"==typeof c&&(Number.isFinite(c)&&0!==c?o.multipleOf=Math.abs(c):jo(e,t,o,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))})(e,t,n,r);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},{gt(e,t){return this.check(Oo(e,t))},gte(e,t){return this.check(Ro(e,t))},min(e,t){return this.check(Ro(e,t))},lt(e,t){return this.check(To(e,t))},lte(e,t){return this.check(Mo(e,t))},max(e,t){return this.check(Mo(e,t))},int(e){return this.check(ns(e))},safe(e){return this.check(ns(e))},positive(e){return this.check(Oo(0,e))},nonnegative(e){return this.check(Ro(0,e))},negative(e){return this.check(To(0,e))},nonpositive(e){return this.check(Mo(0,e))},multipleOf(e,t){return this.check(zo(e,t))},step(e,t){return this.check(zo(e,t))},finite(){return this}});function es(e){return function(e,t){return new e({type:"number",checks:[],...Qe(t)})}(Qi,e)}var ts=/*@__PURE__*/Et("ZodNumberFormat",(e,t)=>{Cr.init(e,t),Qi.init(e,t)});function ns(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Qe(t)})}(ts,e)}var rs=/*@__PURE__*/Et("ZodBoolean",(e,t)=>{Ir.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function os(e){return function(e,t){return new e({type:"boolean",...Qe(t)})}(rs,e)}var is=/*@__PURE__*/Et("ZodUnknown",(e,t)=>{Tr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function ss(){return new is({type:"unknown"})}var as=/*@__PURE__*/Et("ZodNever",(e,t)=>{Mr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function cs(e){return function(e,t){return new e({type:"never",...Qe(t)})}(as,e)}var ls=/*@__PURE__*/Et("ZodDate",(e,t)=>{Or.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{jo(e,t,n,r,"Date cannot be represented in JSON Schema")})(e,t,n,r),e.min=(t,n)=>e.check(Ro(t,n)),e.max=(t,n)=>e.check(Mo(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}),us=/*@__PURE__*/Et("ZodArray",(e,t)=>{_i(),zr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(o.minItems=s),"number"==typeof a&&(o.maxItems=a),o.type="array",o.items=Uo(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Po(e,t))},nonempty(e){return this.check(Po(1,e))},max(e,t){return this.check(Ao(e,t))},length(e,t){return this.check(No(e,t))},unwrap(){return this.element}});function ds(e,t){return function(e,t,n){return new e({type:"array",element:t,...Qe(n)})}(us,e,t)}var ps=/*@__PURE__*/Et("ZodObject",(e,t)=>{_i(),Fr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&jo(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(const l in s)We(o.properties,l,Uo(s[l],t,{...r,path:[...r.path,"properties",l]}));const a=new Set(Object.keys(s)),c=new Set([...a].filter(e=>{const n=i.shape[e];return"input"===t.io?void 0===ei(n):void 0===n._zod.optout}));c.size>0&&(o.required=Array.from(c)),"never"===i.catchall?._zod.def.type?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Uo(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),wt(e,"shape",e=>e._zod.def.shape,!1)},{keyof(){return ws(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:ss()})},loose(){return this.clone({...this._zod.def,catchall:ss()})},strict(){return this.clone({...this._zod.def,catchall:cs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!Ye(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 of Reflect.ownKeys(t))if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ge(e,Be(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return We(this,"shape",n),n}}))}(this,e)},safeExtend(e){return function(e,t){if(!Ye(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Ge(e,Be(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return We(this,"shape",n),n}}))}(this,e)},merge(e){return function(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return Ge(e,Be(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return We(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 Ge(e,Be(e._zod.def,{get shape(){const e={};for(const r of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,r))throw new Error(`Unrecognized key: "${String(r)}"`);t[r]&&We(e,r,n.shape[r])}return We(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 Ge(e,Be(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,e))throw new Error(`Unrecognized key: "${String(e)}"`);t[e]&&delete r[e]}return We(this,"shape",r),r},checks:[]}))}(this,e)},partial(...e){return nt(ks,this,e[0])},exactPartial(...e){return nt(Es,this,e[0],"exactPartial")},required(...e){return t=Os,n=this,r=e[0],Ge(n,Be(n._zod.def,{get shape(){const e=n._zod.def.shape,o={...e};if(r)for(const n of Reflect.ownKeys(r)){if(!Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Unrecognized key: "${String(n)}"`);r[n]&&(o[n]=new t({type:"nonoptional",innerType:e[n]}))}else for(const n of Reflect.ownKeys(e))o[n]=new t({type:"nonoptional",innerType:e[n]});return We(this,"shape",o),o}}));var t,n,r}});function hs(e,t){const n={type:"object",shape:e??{},...Qe(t)};return new ps(n)}var fs=/*@__PURE__*/Et("ZodUnion",(e,t)=>{Ur.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=!1===o.inclusive,s=o.options.map((e,n)=>Uo(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=s:n.anyOf=s})(e,t,n,r),e.options=t.options});function ms(e,t){return new fs({type:"union",options:e,...Qe(t)})}var gs=/*@__PURE__*/Et("ZodIntersection",(e,t)=>{Wr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Uo(o.left,t,{...r,path:[...r.path,"allOf",0]}),s=Uo(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c,t.intersections.push(c)})(e,t,n,r)});var ys=/*@__PURE__*/Et("ZodRecord",(e,t)=>{_i(),Zr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ri(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function vs(e,t,n){return t&&t._zod?new ys({type:"record",keyType:e,valueType:t,...Qe(n)}):new ys({type:"record",keyType:Ti(),valueType:e,...Qe(t)})}var bs=/*@__PURE__*/Et("ZodEnum",(e,t)=>{qr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=$e(e._zod.def.entries);0!==r.length?(r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r):n.not={}})(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 o={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);o[i]=t.entries[i]}return new bs({...t,checks:[],...Qe(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new bs({...t,checks:[],...Qe(r),entries:o})}});function ws(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new bs({type:"enum",entries:n,...Qe(t)})}var xs=/*@__PURE__*/Et("ZodLiteral",(e,t)=>{Vr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;if(0===o.values.length)return void(n.not={});const i=[];for(const s of o.values)if(void 0===s){if(jo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(jo(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);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,r),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 Ss=/*@__PURE__*/Et("ZodTransform",(e,t)=>{_i(),Yr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{jo(e,t,n,r,"Transforms cannot be represented in JSON Schema")})(e,t,n,r),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new It(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(ht(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),"input"in t||(t.input=n.value),t.inst??(t.inst=e),n.issues.push(ht(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}});var ks=/*@__PURE__*/Et("ZodOptional",(e,t)=>{Jr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>si(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function _s(e){return new ks({type:"optional",innerType:e})}var Es=/*@__PURE__*/Et("ZodExactOptional",(e,t)=>{Xr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>si(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Cs=/*@__PURE__*/Et("ZodNullable",(e,t)=>{Gr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Uo(o.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Is(e){return new Cs({type:"nullable",innerType:e})}var Ts=/*@__PURE__*/Et("ZodDefault",(e,t)=>{Qr.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Uo(o.innerType,t,r),t.seen.get(e).ref=o.innerType;const i=ii(o.defaultValue,e,t,n,r);i!==oi&&(n.default=i)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var Ms=/*@__PURE__*/Et("ZodPrefault",(e,t)=>{to.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;if(Uo(o.innerType,t,r),t.seen.get(e).ref=o.innerType,"input"!==t.io)return;const i=ii(o.defaultValue,e,t,n,r);i!==oi&&(n._prefault=i)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Os=/*@__PURE__*/Et("ZodNonOptional",(e,t)=>{no.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Uo(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Rs=/*@__PURE__*/Et("ZodCatch",(e,t)=>{io.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;Uo(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{return void jo(e,t,n,r,"Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var zs=/*@__PURE__*/Et("ZodPipe",(e,t)=>{so.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s="input"===t.io?i?o.out:o.in:o.out;Uo(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function As(e,t){return new zs({type:"pipe",in:e,out:t})}var Ps=/*@__PURE__*/Et("ZodReadonly",(e,t)=>{co.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Uo(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Ns=/*@__PURE__*/Et("ZodCustom",(e,t)=>{uo.init(e,t),Ei.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{jo(e,t,n,r,"Custom types cannot be represented in JSON Schema")})(e,t,n,r)});function Ds(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Qe(t)})}(Qi,e)}function $s(e){return function(e,t){return new e({type:"date",coerce:!0,...Qe(t)})}(ls,e)}var Ls,Fs=ws(["created","active","suspended"]),js=hs({id:es().optional(),created_at:$s().optional(),updated_at:$s().optional()}),Us=(hs({id:Ds()}),hs({slug:Ti()}),hs({widget_id:Ds()}),hs({simulation_id:Ds()}),hs({application_id:Ds()}),hs({user_id:Ds()}),hs({limit:Ds().optional().default(50),offset:Ds().optional().default(0)}),ms([os(),Ti()]).transform(e=>"boolean"==typeof e?e:"true"===e||"false"!==e&&void 0).optional(),hs({success:function(e,t){return new xs({type:"literal",values:Array.isArray(e)?e:[e],...Qe(t)})}(!0)})),Ws=(Us.extend({message:Ti()}),hs({name:Ti().min(1),params:vs(Ti(),ss()).default({}),result:vs(Ti(),ss()).default({})}),Io($i,Ls).refine(e=>/^https:\/\/hooks\.slack\.com\//.test(e),{message:"Slack webhook URL must start with https://hooks.slack.com/"}),hs({start:Ti(),end:Ti(),action:Ti()}).passthrough()),Bs=hs({id:Ti(),label:Ti(),purpose:Ti(),elements:ds(vs(Ti(),ss())).default([]),bbox:vs(Ti(),ss()).default({}),screenshot:Ti().default(""),embedding:ds(es()).nullish()}).passthrough(),Hs=hs({id:Ti(),title:Ti(),url:Ti(),summary:Ti().default(""),screenshot:Ti().default(""),sections:ds(Bs).default([]),sequence_ids:ds(es()).default([]),embedding:ds(es()).nullish()}).passthrough(),Zs=(hs({nodes:ds(Hs),edges:ds(Ws)}),ws(["answered","dismissed","cancelled"]),ws(["study_plan","qa_generate_journeys","qa_prefill_values","persona_generate","persona_from_description","persona_autocomplete"]),ws(["free","startup","growth","enterprise"])),qs=ws(["app","website"]),Vs=ws(["widget"]),Ys=ws(["tell","show","do"]),Ks=ws(["password","oauth"]),Js=ws(["admin","member"]),Xs=(js.extend({is_super:os(),status:Fs,email:function(e){return Co(Pi,e)}(),external_id:Ti().nullish(),first_name:Ti().nullish(),last_name:Ti().nullish(),password:Ti().nullish(),image_url:Ti().nullish(),last_login_at:$s().nullish(),auth_method:Ks.nullish(),workspace_role:Js.nullish()}),js.extend({name:Ti(),slug:Ti(),status:Fs,package:Zs,ending_date:$s().nullish(),external_workspace_id:Ti().nullish(),slack_webhook_configured:os().optional(),notify_all_members_on_question:os().optional()}),js.extend({workspace_id:es(),name:Ti(),slug:Ti(),type:qs,url:Ti(),username:Ti().nullish(),password:Ti().nullish(),allowed_domains:ds(Ti()).default([])}).omit({password:!0}),hs({chip_mode:Ys,chip_text:Ti()})),Gs=hs({widget_enabled:os(),widget_appearance:ws(["default","hidden"]),widget_position:ws(["bottom_left","bottom_right","top_left","top_right"]),widget_header:Ti(),widget_body:Ti(),widget_greeting:Ti(),widget_greeting_toast:os(),widget_recording:os(),widget_feature_tell:os(),widget_feature_show:os(),widget_feature_do:os(),widget_background_color:Ti(),widget_text_color:Ti(),widget_border_color:Ti(),widget_accent_color:Ti(),widget_secondary_color:Ti(),widget_border_radius:Ti(),widget_font_size:Ti(),widget_width:Ti(),widget_height:Ti(),widget_animation_duration:Ti(),widget_fade_duration:Ti(),widget_chips:ds(Xs)}),Qs=(Gs.omit({widget_border_radius:!0,widget_font_size:!0,widget_animation_duration:!0,widget_fade_duration:!0}),js.extend({application_id:es(),type:Vs,settings:Gs,status:Fs,marketrix_id:Ti(),marketrix_key:Ti(),snippet:Ti().nullish()}),ws(["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","request_membership","invite_user","create_workspace","trial_started","trial_ending_soon","trial_ended","subscription_created","subscription_canceled","plan_changed","payment_succeeded","payment_failed","widget_question","qa_run_started","start_simulation","create_workflow","update_workflow","delete_workflow","toggle_workflow","slack_command","create_form","update_form","delete_form","duplicate_form","publish_form","unpublish_form","archive_form","submit_form_response","delete_form_response"])),ea=hs({details:Ti().optional(),id:es().optional(),type:Ti().optional(),name:Ti().optional(),target_user_id:es().optional(),target_user_email:Ti().optional(),reason:Ti().optional(),ip_address:Ti().optional(),user_agent:Ti().optional(),widget_type:Ti().optional(),created_by:es().optional()}).passthrough();js.extend({workspace_id:es(),user_id:es().nullable(),type:Qs,metadata:ea.optional()}).partial().extend({type:Qs});function ta(e){return me(new De({url:e}))}var na="",ra=ta(""),oa=new Proxy({},{get:(e,t)=>ra[t]}),ia="marketrix_chat_context",sa={chat_id:null,messages:[],currentMode:"tell",isOpen:!1,config:null,timestamp:0};function aa(e){try{return"undefined"==typeof localStorage?null:localStorage.getItem(e)}catch(ko){return console.warn("[StorageService] localStorage is unreadable:",ko),null}}function ca(e,t){try{"undefined"!=typeof localStorage&&localStorage.setItem(e,t)}catch(ko){console.warn("[StorageService] localStorage is unwritable:",ko)}}var la,ua=new class{context=function(){const e=aa(ia);if(!e)return{...sa};try{const t={...sa,...JSON.parse(e)};if(Date.now()-t.timestamp<=6048e5)return t}catch(ko){console.warn("[StorageService] Failed to parse the stored context:",ko)}return{...sa}}();getContext(){return this.context}updateContext(e){this.context={...this.context,...e,timestamp:Date.now()},ca(ia,JSON.stringify(this.context))}getChatId(){return this.context.chat_id}setChatId(e){this.updateContext({chat_id:e})}getCredentialedConfig(){const{config:e}=this.context;return e?.mtxId&&e.mtxKey?e:null}setConfig(e){this.updateContext({config:e})}},da=new class{creation=null;async getOrCreateChatId(){const e=ua.getChatId();return e||(this.creation??=this.createChatId().finally(()=>{this.creation=null}),this.creation)}async createChatId(){const e=await oa.chatCreate(void 0);if(!e)throw new Error("API returned empty chat ID");return ua.setChatId(e),e}},pa=Object.defineProperty,ha=(e,t,n)=>((e,t,n)=>t in e?pa(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n),fa=/* @__PURE__ */(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e[e.Asset=7]="Asset",e))(fa||{}),ma=/* @__PURE__ */(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(ma||{}),ga=/* @__PURE__ */(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(ga||{}),ya=/* @__PURE__ */(e=>(e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e))(ya||{}),va=/* @__PURE__ */(e=>(e[e["2D"]=0]="2D",e[e.WebGL=1]="WebGL",e[e.WebGL2=2]="WebGL2",e))(va||{}),ba=/* @__PURE__ */(e=>(e[e.Play=0]="Play",e[e.Pause=1]="Pause",e[e.Seeked=2]="Seeked",e[e.VolumeChange=3]="VolumeChange",e[e.RateChange=4]="RateChange",e))(ba||{}),wa=/* @__PURE__ */(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(wa||{}),xa={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Sa={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},ka={},_a={};function Ea(e){if(ka[e])return ka[e];const t=globalThis[e],n=t.prototype,r=e in xa?xa[e]:void 0,o=Boolean(r&&r.every(e=>{var t,r;return Boolean(null==(r=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:r.toString().includes("[native code]"))})),i=e in Sa?Sa[e]:void 0,s=Boolean(i&&i.every(e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))}));if(o&&s&&!globalThis.Zone)return ka[e]=t.prototype,t.prototype;try{const r=document.createElement("iframe");r.style.display="none",document.body.appendChild(r);const o=r.contentWindow;if(!o)return t.prototype;const i=o[e].prototype;if(!i)return r.remove(),n;const s=navigator.userAgent;return s.includes("Safari")&&!s.includes("Chrome")?(r.classList.add("rr-block"),r.setAttribute("__rrwebUntaintedMutationObserver",""),_a[e]=()=>r.remove()):r.remove(),ka[e]=i}catch{return n}}var Ca={};function Ia(e,t,n){var r;const o=`${e}.${String(n)}`;if(Ca[o])return Ca[o].call(t);const i=Ea(e),s=null==(r=Object.getOwnPropertyDescriptor(i,n))?void 0:r.get;return s?(Ca[o]=s,s.call(t)):t[n]}var Ta={};function Ma(e,t,n){const r=`${e}.${String(n)}`;if(Ta[r])return Ta[r].bind(t);const o=Ea(e)[n];return"function"!=typeof o?t[n]:(Ta[r]=o,o.bind(t))}function Oa(){return[Ea("MutationObserver").constructor,_a.MutationObserver??(()=>{})]}var Ra=Date.now;function za(e,t,n){try{if(!(t in e))return()=>{};const r=e[t],o=n(r);return"function"==typeof o&&(o.prototype=o.prototype||{},Object.defineProperties(o,{__rrweb_original__:{enumerable:!1,value:r}})),e[t]=o,()=>{e[t]=r}}catch{return()=>{}}}/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())||(Ra=()=>/* @__PURE__ */(new Date).getTime());var Aa={ownerDocument:function(e){return Ia("Node",e,"ownerDocument")},childNodes:function(e){return Ia("Node",e,"childNodes")},parentNode:function(e){return Ia("Node",e,"parentNode")},parentElement:function(e){return Ia("Node",e,"parentElement")},textContent:function(e){return Ia("Node",e,"textContent")},contains:function(e,t){return Ma("Node",e,"contains")(t)},getRootNode:function(e){return Ma("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?Ia("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?Ia("Element",e,"shadowRoot"):null},querySelector:function(e,t){return Ia("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return Ia("Element",e,"querySelectorAll")(t)},nowTimestamp:Ra,mutationObserverCtor:Oa,patch:za};function Pa(e){return e.nodeType===e.ELEMENT_NODE}function Na(e){const t=e&&"host"in e&&"mode"in e&&Aa.host(e)||null;return Boolean(t&&"shadowRoot"in t&&Aa.shadowRoot(t)===e)}function Da(e){return"[object ShadowRoot]"===Object.prototype.toString.call(e)}function $a(e){try{const n=e.rules||e.cssRules;if(!n)return null;let r=e.href;return!r&&e.ownerNode&&(r=e.ownerNode.baseURI),(t=Array.from(n,e=>La(e,r)).join("")).includes(" background-clip: text;")&&!t.includes(" -webkit-background-clip: text;")&&(t=t.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),t}catch(ko){return null}var t}function La(e,t){if(function(e){return"styleSheet"in e}(e)){let t;try{t=$a(e.styleSheet)||function(e){const{cssText:t}=e;if(t.split('"').length<3)return t;const n=["@import",`url(${JSON.stringify(e.href)})`];return""===e.layerName?n.push("layer"):e.layerName&&n.push(`layer(${e.layerName})`),e.supportsText&&n.push(`supports(${e.supportsText})`),e.media.length&&n.push(e.media.mediaText),n.join(" ")+";"}(e)}catch(ko){t=e.cssText}return e.styleSheet.href?Ka(t,e.styleSheet.href):t}{let n=e.cssText;return function(e){return"selectorText"in e}(e)&&e.selectorText.includes(":")&&(n=n.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm,"$1\\$2")),t?Ka(n,t):n}}var Fa=class{constructor(){ha(this,"idNodeMap",/* @__PURE__ */new Map),ha(this,"nodeMetaMap",/* @__PURE__ */new WeakMap)}getId(e){var t;return e?(null==(t=this.getMeta(e))?void 0:t.id)??-1:-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(e=>this.removeNodeFromMap(e))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const n=t.id;this.idNodeMap.set(n,e),this.nodeMetaMap.set(e,t)}replace(e,t){const n=this.getNode(e);if(n){const e=this.nodeMetaMap.get(n);e&&this.nodeMetaMap.set(t,e)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=/* @__PURE__ */new Map,this.nodeMetaMap=/* @__PURE__ */new WeakMap}};function ja({element:e,maskInputOptions:t,tagName:n,type:r,value:o,maskInputFn:i}){let s=o||"";const a=r&&Ua(r);return(t[n.toLowerCase()]||a&&t[a])&&(s=i?i(s,e):"*".repeat(s.length)),s}function Ua(e){return e.toLowerCase()}var Wa="__rrweb_original__";function Ba(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?Ua(t):null}function Ha(e,t){let n;try{n=new URL(e,t??window.location.href)}catch(o){return null}const r=n.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==r?void 0:r[1])??null}var Za=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,qa=/^(?:[a-z+]+:)?\/\//i,Va=/^www\..*/i,Ya=/^(data:)([^,]*),(.*)/i;function Ka(e,t){return(e||"").replace(Za,(e,n,r,o,i,s)=>{const a=r||i||s,c=n||o||"";if(!a)return e;if(qa.test(a)||Va.test(a))return`url(${c}${a}${c})`;if(Ya.test(a))return`url(${c}${a}${c})`;if("/"===a[0])return`url(${c}${function(e){let t="";return t=e.indexOf("//")>-1?e.split("/").slice(0,3).join("/"):e.split("/")[0],t=t.split("?")[0],t}(t)+a}${c})`;const l=a.split("#")[0],u=a.substring(l.length),d=t.split("#")[0].split("/"),p=l.split("/");d.pop();for(const t of p){if("."===t)continue;".."===t?d.pop():d.push(t)}return`url(${c}${d.join("/")}${u}${c})`})}function Ja(e,t=!1){return t?e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,""):e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"").replace(/0px/g,"0")}function Xa(e,t){return function(e,t,n=!1){const r=Array.from(t.childNodes),o=[];let i=0;if(r.length>1&&e&&"string"==typeof e){let t=Ja(e,n);const s=t.length/e.length;for(let a=1;a<r.length;a++)if(r[a].textContent&&"string"==typeof r[a].textContent){const c=Ja(r[a].textContent,n),l=100;let u=3;for(;u<c.length&&(c[u].match(/[a-zA-Z0-9]/)||-1!==c.indexOf(c.substring(0,u),1));u++);for(;u<c.length;u++){let d=c.substring(0,u),p=t.split(d),h=-1;if(2===p.length)h=p[0].length;else if(p.length>2&&""===p[0]&&""!==r[a-1].textContent)h=t.indexOf(d,1);else if(1===p.length){if(d=d.substring(0,d.length-1),p=t.split(d),p.length<=1)return o.push(e),o;u=101}else u===c.length-1&&(h=t.indexOf(d));if(p.length>=2&&u>l){const e=r[a-1].textContent;if(e&&"string"==typeof e){const n=Ja(e).length;h=t.indexOf(d,n)}-1===h&&(h=p[0].length)}if(-1!==h){let a=Math.floor(h/s);for(;a>0&&a<e.length;){if(i+=1,i>50*r.length)return o.push(e),o;const c=Ja(e.substring(0,a),n);if(c.length===h){o.push(e.substring(0,a)),e=e.substring(a),t=t.substring(h);break}c.length<h?a+=Math.max(1,Math.floor((h-c.length)/s)):a-=Math.max(1,Math.floor((c.length-h)*s))}break}}}}return o.push(e),o}(e,t).join("/* rr_split */")}var Ga,Qa,ec=1,tc=/* @__PURE__ */new RegExp("[^a-z0-9-_:]");function nc(){return ec++}var rc=/^[^ \t\n\r\u000c]+/,oc=/^[, \t\n\r\u000c]+/;var ic=/* @__PURE__ */new WeakMap;function sc(e,t){return t&&""!==t.trim()?cc(e,t):t}function ac(e){return Boolean("svg"===e.tagName||e.ownerSVGElement)}function cc(e,t){let n=ic.get(e);if(n||(n=e.createElement("a"),ic.set(e,n)),t){if(t.startsWith("blob:")||t.startsWith("data:"))return t}else t="";return n.setAttribute("href",t),n.href}function lc(e,t,n,r){return r?"src"===n||"href"===n&&("use"!==t||"#"!==r[0])||"xlink:href"===n&&"#"!==r[0]||"background"===n&&["table","td","th"].includes(t)?sc(e,r):"srcset"===n?function(e,t){if(""===t.trim())return t;let n=0;function r(e){let r;const o=e.exec(t.substring(n));return o?(r=o[0],n+=r.length,r):""}const o=[];for(;r(oc),!(n>=t.length);){let i=r(rc);if(","===i.slice(-1))i=sc(e,i.substring(0,i.length-1)),o.push(i);else{let r="";i=sc(e,i);let s=!1;for(;;){const e=t.charAt(n);if(""===e){o.push((i+r).trim());break}if(s)")"===e&&(s=!1);else{if(","===e){n+=1,o.push((i+r).trim());break}"("===e&&(s=!0)}r+=e,n+=1}}}return o.join(", ")}(e,r):"style"===n?Ka(r,cc(e)):"object"===t&&"data"===n?sc(e,r):r:r}function uc(e,t,n){return["video","audio"].includes(e)&&"autoplay"===t}function dc(e,t,n){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!n&&dc(Aa.parentNode(e),t,n);for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}return!!n&&dc(Aa.parentNode(e),t,n)}function pc(e,t,n,r){let o;if(Pa(e)){if(o=e,!Aa.childNodes(o).length)return!1}else{if(null===Aa.parentElement(e))return!1;o=Aa.parentElement(e)}try{if("string"==typeof t){if(r){if(o.closest(`.${t}`))return!0}else if(o.classList.contains(t))return!0}else if(dc(o,t,r))return!0;if(n)if(r){if(o.closest(n))return!0}else if(o.matches(n))return!0}catch(i){}return!1}function hc(e,t){const{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:s,inlineStylesheet:a,maskInputOptions:c={},maskTextFn:l,maskInputFn:u,dataURLOptions:d={},inlineImages:p,recordCanvas:h,keepIframeSrcFn:f,newlyAddedElement:m=!1,cssCaptured:g=!1}=t,y=function(e,t){if(!t.hasNode(e))return;const n=t.getId(e);return 1===n?void 0:n}(n,r);switch(e.nodeType){case e.DOCUMENT_NODE:return"CSS1Compat"!==e.compatMode?{type:wa.Document,childNodes:[],compatMode:e.compatMode}:{type:wa.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:wa.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:y};case e.ELEMENT_NODE:return function(e,t){const{doc:n,blockClass:r,blockSelector:o,inlineStylesheet:i,maskInputOptions:s={},maskInputFn:a,dataURLOptions:c={},inlineImages:l,recordCanvas:u,keepIframeSrcFn:d,newlyAddedElement:p=!1,rootId:h}=t,f=function(e,t,n){try{if("string"==typeof t){if(e.classList.contains(t))return!0}else for(let n=e.classList.length;n--;){const r=e.classList[n];if(t.test(r))return!0}if(n)return e.matches(n)}catch(r){}return!1}(e,r,o),m=function(e){if(e instanceof HTMLFormElement)return"form";const t=Ua(e.tagName);return tc.test(t)?"div":t}(e);let g={};const y=e.attributes.length;for(let w=0;w<y;w++){const t=e.attributes[w];uc(m,t.name,t.value)||(g[t.name]=lc(n,m,Ua(t.name),t.value))}if("link"===m&&i){const t=Array.from(n.styleSheets).find(t=>t.href===e.href);let r=null;t&&(r=$a(t)),r&&(delete g.rel,delete g.href,g._cssText=r)}if("style"===m&&e.sheet){let t=$a(e.sheet);t&&(e.childNodes.length>1&&(t=Xa(t,e)),g._cssText=t)}if(["input","textarea","select"].includes(m)){const t=e.value,n=e.checked;"radio"!==g.type&&"checkbox"!==g.type&&"submit"!==g.type&&"button"!==g.type&&t?g.value=ja({element:e,type:Ba(e),tagName:m,value:t,maskInputOptions:s,maskInputFn:a}):n&&(g.checked=n)}"option"===m&&(e.selected&&!s.select?g.selected=!0:delete g.selected);"dialog"===m&&e.open&&(g.rr_open_mode=e.matches("dialog:modal")?"modal":"non-modal");if("canvas"===m&&u)if("2d"===e.__context)(function(e){const t=e.getContext("2d");if(!t)return!0;for(let n=0;n<e.width;n+=50)for(let r=0;r<e.height;r+=50){const o=t.getImageData,i=Wa in o?o[Wa]:o;if(new Uint32Array(i.call(t,n,r,Math.min(50,e.width-n),Math.min(50,e.height-r)).data.buffer).some(e=>0!==e))return!1}return!0})(e)||(g.rr_dataURL=e.toDataURL(c.type,c.quality));else if(!("__context"in e)){const t=e.toDataURL(c.type,c.quality),r=n.createElement("canvas");r.width=e.width,r.height=e.height,t!==r.toDataURL(c.type,c.quality)&&(g.rr_dataURL=t)}if("img"===m&&l){Ga||(Ga=n.createElement("canvas"),Qa=Ga.getContext("2d"));const t=e,r=t.currentSrc||t.getAttribute("src")||"<unknown-src>",o=t.crossOrigin,i=()=>{t.removeEventListener("load",i);try{Ga.width=t.naturalWidth,Ga.height=t.naturalHeight,Qa.drawImage(t,0,0),g.rr_dataURL=Ga.toDataURL(c.type,c.quality)}catch(e){if("anonymous"!==t.crossOrigin)return t.crossOrigin="anonymous",void(t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i));console.warn(`Cannot inline img src=${r}! Error: ${e}`)}"anonymous"===t.crossOrigin&&(o?g.crossOrigin=o:t.removeAttribute("crossorigin"))};t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i)}if(["audio","video"].includes(m)){const t=g;t.rr_mediaState=e.paused?"paused":"played",t.rr_mediaCurrentTime=e.currentTime,t.rr_mediaPlaybackRate=e.playbackRate,t.rr_mediaMuted=e.muted,t.rr_mediaLoop=e.loop,t.rr_mediaVolume=e.volume}p||(e.scrollLeft&&(g.rr_scrollLeft=e.scrollLeft),e.scrollTop&&(g.rr_scrollTop=e.scrollTop));if(f){const{width:t,height:n}=e.getBoundingClientRect();g={class:g.class,rr_width:`${t}px`,rr_height:`${n}px`}}"iframe"!==m||d(g.src)||(e.contentDocument||(g.rr_src=g.src),delete g.src);let v;try{customElements.get(m)&&(v=!0)}catch(b){}return{type:wa.Element,tagName:m,attributes:g,childNodes:[],isSVG:ac(e)||void 0,needBlock:f,rootId:h,isCustom:v}}(e,{doc:n,blockClass:o,blockSelector:i,inlineStylesheet:a,maskInputOptions:c,maskInputFn:u,dataURLOptions:d,inlineImages:p,recordCanvas:h,keepIframeSrcFn:f,newlyAddedElement:m,rootId:y});case e.TEXT_NODE:return function(e,t){const{needsMask:n,maskTextFn:r,rootId:o,cssCaptured:i}=t,s=Aa.parentNode(e),a=s&&s.tagName;let c="";const l="STYLE"===a||void 0,u="SCRIPT"===a||void 0;u?c="SCRIPT_PLACEHOLDER":i||(c=Aa.textContent(e),l&&c&&(c=Ka(c,cc(t.doc))));!l&&!u&&c&&n&&(c=r?r(c,Aa.parentElement(e)):c.replace(/[\S]/g,"*"));return{type:wa.Text,textContent:c||"",rootId:o}}(e,{doc:n,needsMask:s,maskTextFn:l,rootId:y,cssCaptured:g});case e.CDATA_SECTION_NODE:return{type:wa.CDATA,textContent:"",rootId:y};case e.COMMENT_NODE:return{type:wa.Comment,textContent:Aa.textContent(e)||"",rootId:y};default:return!1}}function fc(e){return null==e?"":e.toLowerCase()}function mc(e){return!0===e||"all"===e?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===e,headMetaDescKeywords:"all"===e,headTitleMutations:"all"===e}:e||{}}function gc(e,t){const{doc:n,mirror:r,blockClass:o,blockSelector:i,maskTextClass:s,maskTextSelector:a,skipChild:c=!1,inlineStylesheet:l=!0,maskInputOptions:u={},maskTextFn:d,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f={},inlineImages:m=!1,recordCanvas:g=!1,onSerialize:y,onIframeLoad:v,iframeLoadTimeout:b=5e3,onStylesheetLoad:w,stylesheetLoadTimeout:x=5e3,keepIframeSrcFn:S=()=>!1,newlyAddedElement:k=!1,cssCaptured:_=!1}=t;let{needsMask:E}=t,{preserveWhiteSpace:C=!0}=t;E||(E=pc(e,s,a,void 0===E));const I=hc(e,{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:p,dataURLOptions:f,inlineImages:m,recordCanvas:g,keepIframeSrcFn:S,newlyAddedElement:k,cssCaptured:_});if(!I)return console.warn(e,"not serialized"),null;let T;T=r.hasNode(e)?r.getId(e):function(e,t){if(t.comment&&e.type===wa.Comment)return!0;if(e.type===wa.Element){if(t.script&&("script"===e.tagName||"link"===e.tagName&&("preload"===e.attributes.rel&&"script"===e.attributes.as||"modulepreload"===e.attributes.rel)||"link"===e.tagName&&"prefetch"===e.attributes.rel&&"string"==typeof e.attributes.href&&"js"===Ha(e.attributes.href)))return!0;if(t.headFavicon&&("link"===e.tagName&&"shortcut icon"===e.attributes.rel||"meta"===e.tagName&&(fc(e.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===fc(e.attributes.name)||"icon"===fc(e.attributes.rel)||"apple-touch-icon"===fc(e.attributes.rel)||"shortcut icon"===fc(e.attributes.rel))))return!0;if("meta"===e.tagName){if(t.headMetaDescKeywords&&fc(e.attributes.name).match(/^description|keywords$/))return!0;if(t.headMetaSocial&&(fc(e.attributes.property).match(/^(og|twitter|fb):/)||fc(e.attributes.name).match(/^(og|twitter):/)||"pinterest"===fc(e.attributes.name)))return!0;if(t.headMetaRobots&&("robots"===fc(e.attributes.name)||"googlebot"===fc(e.attributes.name)||"bingbot"===fc(e.attributes.name)))return!0;if(t.headMetaHttpEquiv&&void 0!==e.attributes["http-equiv"])return!0;if(t.headMetaAuthorship&&("author"===fc(e.attributes.name)||"generator"===fc(e.attributes.name)||"framework"===fc(e.attributes.name)||"publisher"===fc(e.attributes.name)||"progid"===fc(e.attributes.name)||fc(e.attributes.property).match(/^article:/)||fc(e.attributes.property).match(/^product:/)))return!0;if(t.headMetaVerification&&("google-site-verification"===fc(e.attributes.name)||"yandex-verification"===fc(e.attributes.name)||"csrf-token"===fc(e.attributes.name)||"p:domain_verify"===fc(e.attributes.name)||"verify-v1"===fc(e.attributes.name)||"verification"===fc(e.attributes.name)||"shopify-checkout-api-token"===fc(e.attributes.name)))return!0}}return!1}(I,h)||!C&&I.type===wa.Text&&!I.textContent.replace(/^\s+|\s+$/gm,"").length?-2:nc();const M=Object.assign(I,{id:T});if(r.add(e,M),-2===T)return null;y&&y(e);let O=!c;if(M.type===wa.Element){O=O&&!M.needBlock,delete M.needBlock;const t=Aa.shadowRoot(e);t&&Da(t)&&(M.isShadowHost=!0)}if((M.type===wa.Document||M.type===wa.Element)&&O){h.headWhitespace&&M.type===wa.Element&&"head"===M.tagName&&(C=!1);const t={doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:c,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:C,onSerialize:y,onIframeLoad:v,iframeLoadTimeout:b,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S,cssCaptured:!1};if(M.type===wa.Element&&"textarea"===M.tagName&&void 0!==M.attributes.value);else{M.type===wa.Element&&void 0!==M.attributes._cssText&&"string"==typeof M.attributes._cssText&&(t.cssCaptured=!0);for(const n of Array.from(Aa.childNodes(e))){const e=gc(n,t);e&&M.childNodes.push(e)}}let k=null;if(Pa(e)&&(k=Aa.shadowRoot(e)))for(const e of Array.from(Aa.childNodes(k))){const n=gc(e,t);n&&(Da(k)&&(n.isShadow=!0),M.childNodes.push(n))}}const R=Aa.parentNode(e);return R&&Na(R)&&Da(R)&&(M.isShadow=!0),M.type===wa.Element&&"iframe"===M.tagName&&function(e,t,n){const r=e.contentWindow;if(!r)return;let o,i=!1;try{o=r.document.readyState}catch(ko){return}if("complete"!==o){const r=setTimeout(()=>{i||(t(),i=!0)},n);return void e.addEventListener("load",()=>{clearTimeout(r),i=!0,t()})}const s="about:blank";if(r.location.href!==s||e.src===s||""===e.src)return setTimeout(t,0),e.addEventListener("load",t);e.addEventListener("load",t)}(e,()=>{const t=e.contentDocument;if(t&&v){const n=gc(t,{doc:t,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:C,onSerialize:y,onIframeLoad:v,iframeLoadTimeout:b,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S});n&&v(e,n)}},b),M.type===wa.Element&&"link"===M.tagName&&"string"==typeof M.attributes.rel&&("stylesheet"===M.attributes.rel||"preload"===M.attributes.rel&&"string"==typeof M.attributes.href&&"css"===Ha(M.attributes.href))&&function(e,t,n){let r,o=!1;try{r=e.sheet}catch(ko){return}if(r)return;const i=setTimeout(()=>{o||(t(),o=!0)},n);e.addEventListener("load",()=>{clearTimeout(i),o=!0,t()})}(e,()=>{if(w){const t=gc(e,{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:C,onSerialize:y,onIframeLoad:v,iframeLoadTimeout:b,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S});t&&w(e,t)}},x),M}var yc=class e{constructor(...e){ha(this,"parentElement",null),ha(this,"parentNode",null),ha(this,"ownerDocument"),ha(this,"firstChild",null),ha(this,"lastChild",null),ha(this,"previousSibling",null),ha(this,"nextSibling",null),ha(this,"ELEMENT_NODE",1),ha(this,"TEXT_NODE",3),ha(this,"nodeType"),ha(this,"nodeName"),ha(this,"RRNodeType")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(t){if(!(t instanceof e))return!1;if(t.ownerDocument!==this.ownerDocument)return!1;if(t===this)return!0;for(;t.parentNode;){if(t.parentNode===this)return!0;t=t.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}};function vc(e,t,n=document){const r={capture:!0,passive:!0};return n.addEventListener(e,t,r),()=>n.removeEventListener(e,t,r)}var bc="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.",wc={map:{},getId:()=>(console.error(bc),-1),getNode:()=>(console.error(bc),null),removeNodeFromMap(){console.error(bc)},has:()=>(console.error(bc),!1),reset(){console.error(bc)}};function xc(e,t,n={}){let r=null,o=0;return function(...i){const s=Date.now();o||!1!==n.leading||(o=s);const a=t-(s-o),c=this;a<=0||a>t?(r&&(clearTimeout(r),r=null),o=s,e.apply(c,i)):r||!1===n.trailing||(r=setTimeout(()=>{o=!1===n.leading?0:Date.now(),r=null,e.apply(c,i)},a))}}function Sc(e,t,n,r,o=window){const i=o.Object.getOwnPropertyDescriptor(e,t);return o.Object.defineProperty(e,t,r?n:{set(e){setTimeout(()=>{n.set.call(this,e)},0),i&&i.set&&i.set.call(this,e)}}),()=>Sc(e,t,i||{},!0)}function kc(e){var t,n,r,o;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null==(t=Aa.parentElement(i.body))?void 0:t.scrollLeft)||(null==(n=null==i?void 0:i.body)?void 0:n.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null==(r=Aa.parentElement(i.body))?void 0:r.scrollTop)||(null==(o=null==i?void 0:i.body)?void 0:o.scrollTop)||0}}function _c(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Ec(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Cc(e){return e?e.nodeType===e.ELEMENT_NODE?e:Aa.parentElement(e):null}function Ic(e,t,n,r){if(!e)return!1;const o=Cc(e);if(!o)return!1;try{if("string"==typeof t){if(o.classList.contains(t))return!0;if(r&&null!==o.closest("."+t))return!0}else if(dc(o,t,r))return!0}catch(i){}if(n){if(o.matches(n))return!0;if(r&&null!==o.closest(n))return!0}return!1}function Tc(e,t,n){return!("TITLE"!==e.tagName||!n.headTitleMutations)||-2===t.getId(e)}function Mc(e,t){if(Na(e))return!1;const n=t.getId(e);if(!t.has(n))return!0;const r=Aa.parentNode(e);return(!r||r.nodeType!==e.DOCUMENT_NODE)&&(!r||Mc(r,t))}function Oc(e){return Boolean(e.changedTouches)}function Rc(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))}function zc(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))}function Ac(e){return!!e&&(e instanceof yc&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(Aa.shadowRoot(e)))}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(wc=new Proxy(wc,{get:(e,t,n)=>("map"===t&&console.error(bc),Reflect.get(e,t,n))}));var Pc=class{constructor(){ha(this,"id",1),ha(this,"styleIDMap",/* @__PURE__ */new WeakMap),ha(this,"idStyleMap",/* @__PURE__ */new Map)}getId(e){return this.styleIDMap.get(e)??-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let n;return n=void 0===t?this.id++:t,this.styleIDMap.set(e,n),this.idStyleMap.set(n,e),n}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=/* @__PURE__ */new WeakMap,this.idStyleMap=/* @__PURE__ */new Map,this.id=1}generateId(){return this.id++}};function Nc(e){var t;let n=null;return"getRootNode"in e&&(null==(t=Aa.getRootNode(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&Aa.host(Aa.getRootNode(e))&&(n=Aa.host(Aa.getRootNode(e))),n}function Dc(e){const t=Aa.ownerDocument(e);if(!t)return!1;const n=function(e){let t,n=e;for(;t=Nc(n);)n=t;return n}(e);return Aa.contains(t,n)}function $c(e){const t=Aa.ownerDocument(e);return!!t&&(Aa.contains(t,e)||Dc(e))}function Lc(e){return"__ln"in e}var Fc,jc=class{constructor(){ha(this,"length",0),ha(this,"head",null),ha(this,"tail",null)}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let n=0;n<e;n++)t=(null==t?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&Lc(e.previousSibling)){const n=e.previousSibling.__ln.next;t.next=n,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,n&&(n.previous=t)}else if(e.nextSibling&&Lc(e.nextSibling)&&e.nextSibling.__ln.previous){const n=e.nextSibling.__ln.previous;t.previous=n,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,n&&(n.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;null===t.next&&(this.tail=t),this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next?t.next.previous=t.previous:this.tail=t.previous):(this.head=t.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)}},Uc=(e,t)=>`${e}@${t}`,Wc=class{constructor(){ha(this,"frozen",!1),ha(this,"locked",!1),ha(this,"texts",[]),ha(this,"attributes",[]),ha(this,"attributeMap",/* @__PURE__ */new WeakMap),ha(this,"removes",[]),ha(this,"mapRemoves",[]),ha(this,"movedMap",{}),ha(this,"addedSet",/* @__PURE__ */new Set),ha(this,"movedSet",/* @__PURE__ */new Set),ha(this,"droppedSet",/* @__PURE__ */new Set),ha(this,"removesSubTreeCache",/* @__PURE__ */new Set),ha(this,"mutationCb"),ha(this,"blockClass"),ha(this,"blockSelector"),ha(this,"maskTextClass"),ha(this,"maskTextSelector"),ha(this,"inlineStylesheet"),ha(this,"maskInputOptions"),ha(this,"maskTextFn"),ha(this,"maskInputFn"),ha(this,"keepIframeSrcFn"),ha(this,"recordCanvas"),ha(this,"inlineImages"),ha(this,"slimDOMOptions"),ha(this,"dataURLOptions"),ha(this,"doc"),ha(this,"mirror"),ha(this,"iframeManager"),ha(this,"stylesheetManager"),ha(this,"shadowDomManager"),ha(this,"canvasManager"),ha(this,"processedNodeManager"),ha(this,"unattachedDoc"),ha(this,"processMutations",e=>{e.forEach(this.processMutation),this.emit()}),ha(this,"emit",()=>{if(this.frozen||this.locked)return;const e=[],t=/* @__PURE__ */new Set,n=new jc,r=e=>{let t=e,n=-2;for(;-2===n;)t=t&&t.nextSibling,n=t&&this.mirror.getId(t);return n},o=o=>{const i=Aa.parentNode(o);if(!i||!$c(o))return;let s=!1;if(o.nodeType===Node.TEXT_NODE){const e=i.tagName;if("TEXTAREA"===e)return;"STYLE"===e&&this.addedSet.has(i)&&(s=!0)}const a=Na(i)?this.mirror.getId(Nc(o)):this.mirror.getId(i),c=r(o);if(-1===a||-1===c)return n.addNode(o);const l=gc(o,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:e=>{Rc(e,this.mirror)&&this.iframeManager.addIframe(e),zc(e,this.mirror)&&this.stylesheetManager.trackLinkElement(e),Ac(o)&&this.shadowDomManager.addShadowRoot(Aa.shadowRoot(o),this.doc)},onIframeLoad:(e,t)=>{this.iframeManager.attachIframe(e,t),this.shadowDomManager.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{this.stylesheetManager.attachLinkElement(e,t)},cssCaptured:s});l&&(e.push({parentId:a,nextId:c,node:l}),t.add(l.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of this.movedSet)Hc(this.removesSubTreeCache,a,this.mirror)&&!this.movedSet.has(Aa.parentNode(a))||o(a);for(const a of this.addedSet)Zc(this.droppedSet,a)||Hc(this.removesSubTreeCache,a,this.mirror)?Zc(this.movedSet,a)?o(a):this.droppedSet.add(a):o(a);let i=null;for(;n.length;){let e=null;if(i){const t=this.mirror.getId(Aa.parentNode(i.value)),n=r(i.value);-1!==t&&-1!==n&&(e=i)}if(!e){let t=n.tail;for(;t;){const n=t;if(t=t.previous,n){const t=this.mirror.getId(Aa.parentNode(n.value));if(-1===r(n.value))continue;if(-1!==t){e=n;break}{const t=n.value,r=Aa.parentNode(t);if(r&&r.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const t=Aa.host(r);if(-1!==this.mirror.getId(t)){e=n;break}}}}}}if(!e){for(;n.head;)n.removeNode(n.head.value);break}i=e.previous,n.removeNode(e.value),o(e.value)}const s={texts:this.texts.map(e=>{const t=e.node,n=Aa.parentNode(t);return n&&"TEXTAREA"===n.tagName&&this.genTextAreaValueMutation(n),{id:this.mirror.getId(t),value:e.value}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),attributes:this.attributes.map(e=>{const{attributes:t}=e;if("string"==typeof t.style){const n=JSON.stringify(e.styleDiff),r=JSON.stringify(e._unchangedStyles);n.length<t.style.length&&(n+r).split("var(").length===t.style.split("var(").length&&(t.style=e.styleDiff)}return{id:this.mirror.getId(e.node),attributes:t}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),removes:this.removes,adds:e};(s.texts.length||s.attributes.length||s.removes.length||s.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=/* @__PURE__ */new WeakMap,this.removes=[],this.addedSet=/* @__PURE__ */new Set,this.movedSet=/* @__PURE__ */new Set,this.droppedSet=/* @__PURE__ */new Set,this.removesSubTreeCache=/* @__PURE__ */new Set,this.movedMap={},this.mutationCb(s))}),ha(this,"genTextAreaValueMutation",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t));const n=Array.from(Aa.childNodes(e),e=>Aa.textContent(e)||"").join("");t.attributes.value=ja({element:e,maskInputOptions:this.maskInputOptions,tagName:e.tagName,type:Ba(e),value:n,maskInputFn:this.maskInputFn})}),ha(this,"processMutation",e=>{if(!Tc(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case"characterData":{const t=Aa.textContent(e.target);Ic(e.target,this.blockClass,this.blockSelector,!1)||t===e.oldValue||this.texts.push({value:pc(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,Cc(e.target)):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const n=e.target;let r=e.attributeName,o=e.target.getAttribute(r);if("value"===r){const e=Ba(n);o=ja({element:n,maskInputOptions:this.maskInputOptions,tagName:n.tagName,type:e,value:o,maskInputFn:this.maskInputFn})}if(Ic(e.target,this.blockClass,this.blockSelector,!1)||o===e.oldValue)return;let i=this.attributeMap.get(e.target);if("IFRAME"===n.tagName&&"src"===r&&!this.keepIframeSrcFn(o)){if(n.contentDocument)return;r="rr_src"}if(i||(i={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(i),this.attributeMap.set(e.target,i)),"type"===r&&"INPUT"===n.tagName&&"password"===(e.oldValue||"").toLowerCase()&&n.setAttribute("data-rr-is-password","true"),!uc(n.tagName,r))if(i.attributes[r]=lc(this.doc,Ua(n.tagName),Ua(r),o),"style"===r){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(t){this.unattachedDoc=this.doc}const r=this.unattachedDoc.createElement("span");e.oldValue&&r.setAttribute("style",e.oldValue);for(const e of Array.from(n.style)){const t=n.style.getPropertyValue(e),o=n.style.getPropertyPriority(e);t!==r.style.getPropertyValue(e)||o!==r.style.getPropertyPriority(e)?i.styleDiff[e]=""===o?t:[t,o]:i._unchangedStyles[e]=[t,o]}for(const e of Array.from(r.style))""===n.style.getPropertyValue(e)&&(i.styleDiff[e]=!1)}else"open"===r&&"DIALOG"===n.tagName&&(n.matches("dialog:modal")?i.attributes.rr_open_mode="modal":i.attributes.rr_open_mode="non-modal");break}case"childList":if(Ic(e.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===e.target.tagName)return void this.genTextAreaValueMutation(e.target);e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const n=this.mirror.getId(t),r=Na(e.target)?this.mirror.getId(Aa.host(e.target)):this.mirror.getId(e.target);Ic(e.target,this.blockClass,this.blockSelector,!1)||Tc(t,this.mirror,this.slimDOMOptions)||!function(e,t){return-1!==t.getId(e)}(t,this.mirror)||(this.addedSet.has(t)?(Bc(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&-1===n||Mc(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[Uc(n,r)]?Bc(this.movedSet,t):(this.removes.push({parentId:r,id:n,isShadow:!(!Na(e.target)||!Da(e.target))||void 0}),function(e,t){const n=[e];for(;n.length;){const e=n.pop();t.has(e)||(t.add(e),Aa.childNodes(e).forEach(e=>n.push(e)))}}(t,this.removesSubTreeCache))),this.mapRemoves.push(t))})}}),ha(this,"genAdds",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!this.addedSet.has(e)&&!this.movedSet.has(e)){if(this.mirror.hasNode(e)){if(Tc(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let n=null;t&&this.mirror.hasNode(t)&&(n=this.mirror.getId(t)),n&&-1!==n&&(this.movedMap[Uc(this.mirror.getId(e),n)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Ic(e,this.blockClass,this.blockSelector,!1)||(Aa.childNodes(e).forEach(e=>this.genAdds(e)),Ac(e)&&Aa.childNodes(Aa.shadowRoot(e)).forEach(t=>{this.processedNodeManager.add(t,this),this.genAdds(t,e)}))}})}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}};function Bc(e,t){e.delete(t),Aa.childNodes(t).forEach(t=>Bc(e,t))}function Hc(e,t,n){return 0!==e.size&&function(e,t){const n=Aa.parentNode(t);return!!n&&e.has(n)}(e,t)}function Zc(e,t){return 0!==e.size&&qc(e,t)}function qc(e,t){const n=Aa.parentNode(t);return!!n&&(!!e.has(n)||qc(e,n))}var Vc=e=>{if(!Fc)return e;return(...t)=>{try{return e(...t)}catch(ko){if(Fc&&!0===Fc(ko))return;throw ko}}},Yc=[];function Kc(e){try{if("composedPath"in e){const t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch{}return e&&e.target}function Jc(e,t){const n=new Wc;Yc.push(n),n.init(e);const[r,o]=Oa(),i=new r(Vc(n.processMutations.bind(n)));return i.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),[i,o]}function Xc({mouseInteractionCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,sampling:i}){if(!1===i.mouseInteraction)return()=>{};const s=!0===i.mouseInteraction||void 0===i.mouseInteraction?{}:i.mouseInteraction,a=[];let c=null;return Object.keys(ga).filter(e=>Number.isNaN(Number(e))&&!e.endsWith("_Departed")&&!1!==s[e]).forEach(i=>{let s=Ua(i);const l=(t=>i=>{const s=Kc(i);if(Ic(s,r,o,!0))return;let a=null,l=t;if("pointerType"in i){switch(i.pointerType){case"mouse":a=ya.Mouse;break;case"touch":a=ya.Touch;break;case"pen":a=ya.Pen}a===ya.Touch?ga[t]===ga.MouseDown?l="TouchStart":ga[t]===ga.MouseUp&&(l="TouchEnd"):ya.Pen}else Oc(i)&&(a=ya.Touch);null!==a?(c=a,(l.startsWith("Touch")&&a===ya.Touch||l.startsWith("Mouse")&&a===ya.Mouse)&&(a=null)):ga[t]===ga.Click&&(a=c,c=null);const u=Oc(i)?i.changedTouches[0]:i;if(!u)return;const d=n.getId(s),{clientX:p,clientY:h}=u;Vc(e)({type:ga[l],id:d,x:p,y:h,...null!==a&&{pointerType:a}})})(i);if(window.PointerEvent)switch(ga[i]){case ga.MouseDown:case ga.MouseUp:s=s.replace("mouse","pointer");break;case ga.TouchStart:case ga.TouchEnd:return}a.push(vc(s,l,t))}),Vc(()=>{a.forEach(e=>e())})}function Gc({scrollCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,sampling:i}){return vc("scroll",Vc(xc(Vc(i=>{const s=Kc(i);if(!s||Ic(s,r,o,!0))return;const a=n.getId(s);if(s===t&&t.defaultView){const n=kc(t.defaultView);e({id:a,x:n.left,y:n.top})}else e({id:a,x:s.scrollLeft,y:s.scrollTop})}),i.scroll||100)),t)}var Qc=["INPUT","TEXTAREA","SELECT"],el=/* @__PURE__ */new WeakMap;function tl(e){return function e(t,n){if(il("CSSGroupingRule")&&t.parentRule instanceof CSSGroupingRule||il("CSSMediaRule")&&t.parentRule instanceof CSSMediaRule||il("CSSSupportsRule")&&t.parentRule instanceof CSSSupportsRule||il("CSSConditionRule")&&t.parentRule instanceof CSSConditionRule){const r=Array.from(t.parentRule.cssRules).indexOf(t);return n.unshift(r),e(t.parentRule,n)}if(t.parentStyleSheet){const e=Array.from(t.parentStyleSheet.cssRules).indexOf(t);n.unshift(e)}return n}(e,[])}function nl(e,t,n){let r,o;return e?(e.ownerNode?r=t.getId(e.ownerNode):o=n.getId(e),{styleId:o,id:r}):{}}function rl({mirror:e,stylesheetManager:t},n){var r,o,i;let s=null;s="#document"===n.nodeName?e.getId(n):e.getId(Aa.host(n));const a="#document"===n.nodeName?null==(r=n.defaultView)?void 0:r.Document:null==(i=null==(o=n.ownerDocument)?void 0:o.defaultView)?void 0:i.ShadowRoot,c=(null==a?void 0:a.prototype)?Object.getOwnPropertyDescriptor(null==a?void 0:a.prototype,"adoptedStyleSheets"):void 0;return null!==s&&-1!==s&&a&&c?(Object.defineProperty(n,"adoptedStyleSheets",{configurable:c.configurable,enumerable:c.enumerable,get(){var e;return null==(e=c.get)?void 0:e.call(this)},set(e){var n;const r=null==(n=c.set)?void 0:n.call(this,e);if(null!==s&&-1!==s)try{t.adoptStyleSheets(e,s)}catch(o){}return r}}),Vc(()=>{Object.defineProperty(n,"adoptedStyleSheets",{configurable:c.configurable,enumerable:c.enumerable,get:c.get,set:c.set})})):()=>{}}function ol(e,t={}){const n=e.doc.defaultView;if(!n)return()=>{};let r;!function(e,t){const{mutationCb:n,mousemoveCb:r,mouseInteractionCb:o,scrollCb:i,viewportResizeCb:s,inputCb:a,mediaInteractionCb:c,styleSheetRuleCb:l,styleDeclarationCb:u,canvasMutationCb:d,fontCb:p,selectionCb:h,customElementCb:f}=e;e.mutationCb=(...e)=>{t.mutation&&t.mutation(...e),n(...e)},e.mousemoveCb=(...e)=>{t.mousemove&&t.mousemove(...e),r(...e)},e.mouseInteractionCb=(...e)=>{t.mouseInteraction&&t.mouseInteraction(...e),o(...e)},e.scrollCb=(...e)=>{t.scroll&&t.scroll(...e),i(...e)},e.viewportResizeCb=(...e)=>{t.viewportResize&&t.viewportResize(...e),s(...e)},e.inputCb=(...e)=>{t.input&&t.input(...e),a(...e)},e.mediaInteractionCb=(...e)=>{t.mediaInteaction&&t.mediaInteaction(...e),c(...e)},e.styleSheetRuleCb=(...e)=>{t.styleSheetRule&&t.styleSheetRule(...e),l(...e)},e.styleDeclarationCb=(...e)=>{t.styleDeclaration&&t.styleDeclaration(...e),u(...e)},e.canvasMutationCb=(...e)=>{t.canvasMutation&&t.canvasMutation(...e),d(...e)},e.fontCb=(...e)=>{t.font&&t.font(...e),p(...e)},e.selectionCb=(...e)=>{t.selection&&t.selection(...e),h(...e)},e.customElementCb=(...e)=>{t.customElement&&t.customElement(...e),f(...e)}}(e,t);let o=()=>{};e.recordDOM&&([r,o]=Jc(e,e.doc));const i=function({mousemoveCb:e,sampling:t,doc:n,mirror:r}){if(!1===t.mousemove)return()=>{};const o="number"==typeof t.mousemove?t.mousemove:50,i="number"==typeof t.mousemoveCallback?t.mousemoveCallback:500;let s,a=[];const c=xc(Vc(t=>{const n=Date.now()-s;e(a.map(e=>(e.timeOffset-=n,e)),t),a=[],s=null}),i),l=Vc(xc(Vc(e=>{const t=Kc(e),{clientX:n,clientY:o}=Oc(e)?e.changedTouches[0]:e;s||(s=Ra()),a.push({x:n,y:o,id:r.getId(t),timeOffset:Ra()-s}),c("undefined"!=typeof DragEvent&&e instanceof DragEvent?ma.Drag:e instanceof MouseEvent?ma.MouseMove:ma.TouchMove)}),o,{trailing:!1})),u=[vc("mousemove",l,n),vc("touchmove",l,n),vc("drag",l,n)];return Vc(()=>{u.forEach(e=>e())})}(e),s=Xc(e),a=Gc(e),c=function({viewportResizeCb:e},{win:t}){let n=-1,r=-1;return vc("resize",Vc(xc(Vc(()=>{const t=_c(),o=Ec();n===t&&r===o||(e({width:Number(o),height:Number(t)}),n=t,r=o)}),200)),t)}(e,{win:n}),l=function({inputCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,ignoreClass:i,ignoreSelector:s,maskInputOptions:a,maskInputFn:c,sampling:l,userTriggeredOnInput:u}){function d(e){let n=Kc(e);const l=e.isTrusted,d=n&&n.tagName;if(n&&"OPTION"===d&&(n=Aa.parentElement(n)),!n||!d||Qc.indexOf(d)<0||Ic(n,r,o,!0))return;if(n.classList.contains(i)||s&&n.matches(s))return;let h=n.value,f=!1;const m=Ba(n)||"";"radio"===m||"checkbox"===m?f=n.checked:(a[d.toLowerCase()]||a[m])&&(h=ja({element:n,maskInputOptions:a,tagName:d,type:m,value:h,maskInputFn:c})),p(n,u?{text:h,isChecked:f,userTriggered:l}:{text:h,isChecked:f});const g=n.name;"radio"===m&&g&&f&&t.querySelectorAll(`input[type="radio"][name="${g}"]`).forEach(e=>{if(e!==n){const t=e.value;p(e,u?{text:t,isChecked:!f,userTriggered:!1}:{text:t,isChecked:!f})}})}function p(t,r){const o=el.get(t);if(!o||o.text!==r.text||o.isChecked!==r.isChecked){el.set(t,r);const o=n.getId(t);Vc(e)({...r,id:o})}}const h=("last"===l.input?["change"]:["input","change"]).map(e=>vc(e,Vc(d),t)),f=t.defaultView;if(!f)return()=>{h.forEach(e=>e())};const m=f.Object.getOwnPropertyDescriptor(f.HTMLInputElement.prototype,"value"),g=[[f.HTMLInputElement.prototype,"value"],[f.HTMLInputElement.prototype,"checked"],[f.HTMLSelectElement.prototype,"value"],[f.HTMLTextAreaElement.prototype,"value"],[f.HTMLSelectElement.prototype,"selectedIndex"],[f.HTMLOptionElement.prototype,"selected"]];return m&&m.set&&h.push(...g.map(e=>Sc(e[0],e[1],{set(){Vc(d)({target:this,isTrusted:!1})}},!1,f))),Vc(()=>{h.forEach(e=>e())})}(e),u=function({mediaInteractionCb:e,blockClass:t,blockSelector:n,mirror:r,sampling:o,doc:i}){const s=Vc(i=>xc(Vc(o=>{const s=Kc(o);if(!s||Ic(s,t,n,!0))return;const{currentTime:a,volume:c,muted:l,playbackRate:u,loop:d}=s;e({type:i,id:r.getId(s),currentTime:a,volume:c,muted:l,playbackRate:u,loop:d})}),o.media||500)),a=[vc("play",s(ba.Play),i),vc("pause",s(ba.Pause),i),vc("seeked",s(ba.Seeked),i),vc("volumechange",s(ba.VolumeChange),i),vc("ratechange",s(ba.RateChange),i)];return Vc(()=>{a.forEach(e=>e())})}(e);let d=()=>{},p=()=>{},h=()=>{},f=()=>{};e.recordDOM&&(d=function({styleSheetRuleCb:e,mirror:t,stylesheetManager:n},{win:r}){if(!r.CSSStyleSheet||!r.CSSStyleSheet.prototype)return()=>{};const o=r.CSSStyleSheet.prototype.insertRule;r.CSSStyleSheet.prototype.insertRule=new Proxy(o,{apply:Vc((r,o,i)=>{const[s,a]=i,{id:c,styleId:l}=nl(o,t,n.styleMirror);return(c&&-1!==c||l&&-1!==l)&&e({id:c,styleId:l,adds:[{rule:s,index:a}]}),r.apply(o,i)})}),r.CSSStyleSheet.prototype.addRule=function(e,t,n=this.cssRules.length){const o=`${e} { ${t} }`;return r.CSSStyleSheet.prototype.insertRule.apply(this,[o,n])};const i=r.CSSStyleSheet.prototype.deleteRule;let s,a;r.CSSStyleSheet.prototype.deleteRule=new Proxy(i,{apply:Vc((r,o,i)=>{const[s]=i,{id:a,styleId:c}=nl(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,removes:[{index:s}]}),r.apply(o,i)})}),r.CSSStyleSheet.prototype.removeRule=function(e){return r.CSSStyleSheet.prototype.deleteRule.apply(this,[e])},r.CSSStyleSheet.prototype.replace&&(s=r.CSSStyleSheet.prototype.replace,r.CSSStyleSheet.prototype.replace=new Proxy(s,{apply:Vc((r,o,i)=>{const[s]=i,{id:a,styleId:c}=nl(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,replace:s}),r.apply(o,i)})})),r.CSSStyleSheet.prototype.replaceSync&&(a=r.CSSStyleSheet.prototype.replaceSync,r.CSSStyleSheet.prototype.replaceSync=new Proxy(a,{apply:Vc((r,o,i)=>{const[s]=i,{id:a,styleId:c}=nl(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,replaceSync:s}),r.apply(o,i)})}));const c={};sl("CSSGroupingRule")?c.CSSGroupingRule=r.CSSGroupingRule:(sl("CSSMediaRule")&&(c.CSSMediaRule=r.CSSMediaRule),sl("CSSConditionRule")&&(c.CSSConditionRule=r.CSSConditionRule),sl("CSSSupportsRule")&&(c.CSSSupportsRule=r.CSSSupportsRule));const l={};return Object.entries(c).forEach(([r,o])=>{l[r]={insertRule:o.prototype.insertRule,deleteRule:o.prototype.deleteRule},o.prototype.insertRule=new Proxy(l[r].insertRule,{apply:Vc((r,o,i)=>{const[s,a]=i,{id:c,styleId:l}=nl(o.parentStyleSheet,t,n.styleMirror);return(c&&-1!==c||l&&-1!==l)&&e({id:c,styleId:l,adds:[{rule:s,index:[...tl(o),a||0]}]}),r.apply(o,i)})}),o.prototype.deleteRule=new Proxy(l[r].deleteRule,{apply:Vc((r,o,i)=>{const[s]=i,{id:a,styleId:c}=nl(o.parentStyleSheet,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,removes:[{index:[...tl(o),s]}]}),r.apply(o,i)})})}),Vc(()=>{r.CSSStyleSheet.prototype.insertRule=o,r.CSSStyleSheet.prototype.deleteRule=i,s&&(r.CSSStyleSheet.prototype.replace=s),a&&(r.CSSStyleSheet.prototype.replaceSync=a),Object.entries(c).forEach(([e,t])=>{t.prototype.insertRule=l[e].insertRule,t.prototype.deleteRule=l[e].deleteRule})})}(e,{win:n}),p=rl(e,e.doc),h=function({styleDeclarationCb:e,mirror:t,ignoreCSSAttributes:n,stylesheetManager:r},{win:o}){const i=o.CSSStyleDeclaration.prototype.setProperty;o.CSSStyleDeclaration.prototype.setProperty=new Proxy(i,{apply:Vc((o,s,a)=>{var c;const[l,u,d]=a;if(n.has(l))return i.apply(s,[l,u,d]);const{id:p,styleId:h}=nl(null==(c=s.parentRule)?void 0:c.parentStyleSheet,t,r.styleMirror);return(p&&-1!==p||h&&-1!==h)&&e({id:p,styleId:h,set:{property:l,value:u,priority:d},index:tl(s.parentRule)}),o.apply(s,a)})});const s=o.CSSStyleDeclaration.prototype.removeProperty;return o.CSSStyleDeclaration.prototype.removeProperty=new Proxy(s,{apply:Vc((o,i,a)=>{var c;const[l]=a;if(n.has(l))return s.apply(i,[l]);const{id:u,styleId:d}=nl(null==(c=i.parentRule)?void 0:c.parentStyleSheet,t,r.styleMirror);return(u&&-1!==u||d&&-1!==d)&&e({id:u,styleId:d,remove:{property:l},index:tl(i.parentRule)}),o.apply(i,a)})}),Vc(()=>{o.CSSStyleDeclaration.prototype.setProperty=i,o.CSSStyleDeclaration.prototype.removeProperty=s})}(e,{win:n}),e.collectFonts&&(f=function({fontCb:e,doc:t}){const n=t.defaultView;if(!n)return()=>{};const r=[],o=/* @__PURE__ */new WeakMap,i=n.FontFace;n.FontFace=function(e,t,n){const r=new i(e,t,n);return o.set(r,{family:e,buffer:"string"!=typeof t,descriptors:n,fontSource:"string"==typeof t?t:JSON.stringify(Array.from(new Uint8Array(t)))}),r};const s=za(t.fonts,"add",function(t){return function(n){return setTimeout(Vc(()=>{const t=o.get(n);t&&(e(t),o.delete(n))}),0),t.apply(this,[n])}});return r.push(()=>{n.FontFace=i}),r.push(s),Vc(()=>{r.forEach(e=>e())})}(e)));const m=function(e){const{doc:t,mirror:n,blockClass:r,blockSelector:o,selectionCb:i}=e;let s=!0;const a=Vc(()=>{const e=t.getSelection();if(!e||s&&(null==e?void 0:e.isCollapsed))return;s=e.isCollapsed||!1;const a=[],c=e.rangeCount||0;for(let t=0;t<c;t++){const{startContainer:i,startOffset:s,endContainer:c,endOffset:l}=e.getRangeAt(t);Ic(i,r,o,!0)||Ic(c,r,o,!0)||a.push({start:n.getId(i),startOffset:s,end:n.getId(c),endOffset:l})}i({ranges:a})});return a(),vc("selectionchange",a)}(e),g=function({doc:e,customElementCb:t}){const n=e.defaultView;return n&&n.customElements?za(n.customElements,"define",function(e){return function(n,r,o){try{t({define:{name:n}})}catch(i){console.warn(`Custom element callback failed for ${n}`)}return e.apply(this,[n,r,o])}}):()=>{}}(e),y=[];for(const v of e.plugins)y.push(v.observer(v.callback,n,v.options));return Vc(()=>{Yc.forEach(e=>e.reset()),r?.disconnect(),o(),i(),s(),a(),c(),l(),u(),d(),p(),h(),f(),m(),g(),y.forEach(e=>e())})}function il(e){return void 0!==window[e]}function sl(e){return Boolean(void 0!==window[e]&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}for(var al=class{constructor(e){ha(this,"iframeIdToRemoteIdMap",/* @__PURE__ */new WeakMap),ha(this,"iframeRemoteIdToIdMap",/* @__PURE__ */new WeakMap),this.generateIdFn=e}getId(e,t,n,r){const o=n||this.getIdToRemoteIdMap(e),i=r||this.getRemoteIdToIdMap(e);let s=o.get(t);return s||(s=this.generateIdFn(),o.set(t,s),i.set(s,t)),s}getIds(e,t){const n=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(t=>this.getId(e,t,n,r))}getRemoteId(e,t,n){const r=n||this.getRemoteIdToIdMap(e);if("number"!=typeof t)return t;const o=r.get(t);return o||-1}getRemoteIds(e,t){const n=this.getRemoteIdToIdMap(e);return t.map(t=>this.getRemoteId(e,t,n))}reset(e){if(!e)return this.iframeIdToRemoteIdMap=/* @__PURE__ */new WeakMap,void(this.iframeRemoteIdToIdMap=/* @__PURE__ */new WeakMap);this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=/* @__PURE__ */new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=/* @__PURE__ */new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}},cl=class{constructor(e){ha(this,"iframes",/* @__PURE__ */new WeakMap),ha(this,"crossOriginIframeMap",/* @__PURE__ */new WeakMap),ha(this,"crossOriginIframeMirror",new al(nc)),ha(this,"crossOriginIframeStyleMirror"),ha(this,"crossOriginIframeRootIdMap",/* @__PURE__ */new WeakMap),ha(this,"mirror"),ha(this,"mutationCb"),ha(this,"wrappedEmit"),ha(this,"loadListener"),ha(this,"stylesheetManager"),ha(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new al(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var n,r;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(n=e.contentWindow)||n.addEventListener("message",this.handleMessage.bind(this))),null==(r=this.loadListener)||r.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){const t=e;if("rrweb"!==t.data.type||t.origin!==t.data.origin)return;if(!e.source)return;const n=this.crossOriginIframeMap.get(e.source);if(!n)return;const r=this.transformCrossOriginEvent(n,t.data.event);r&&this.wrappedEmit(r,t.data.isCheckout)}transformCrossOriginEvent(e,t){var n;switch(t.type){case fa.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);const n=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,n),this.patchRootIdOnNode(t.data.node,n),{timestamp:t.timestamp,type:fa.IncrementalSnapshot,data:{source:ma.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case fa.Meta:case fa.Load:case fa.DomContentLoaded:return!1;case fa.Plugin:return t;case fa.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case fa.IncrementalSnapshot:switch(t.data.source){case ma.Mutation:return t.data.adds.forEach(t=>{this.replaceIds(t,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(t.node,e);const n=this.crossOriginIframeRootIdMap.get(e);n&&this.patchRootIdOnNode(t.node,n)}),t.data.removes.forEach(t=>{this.replaceIds(t,e,["parentId","id"])}),t.data.attributes.forEach(t=>{this.replaceIds(t,e,["id"])}),t.data.texts.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case ma.Drag:case ma.TouchMove:case ma.MouseMove:return t.data.positions.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case ma.ViewportResize:return!1;case ma.MediaInteraction:case ma.MouseInteraction:case ma.Scroll:case ma.CanvasMutation:case ma.Input:return this.replaceIds(t.data,e,["id"]),t;case ma.StyleSheetRule:case ma.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case ma.Font:return t;case ma.Selection:return t.data.ranges.forEach(t=>{this.replaceIds(t,e,["start","end"])}),t;case ma.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),null==(n=t.data.styles)||n.forEach(t=>{this.replaceStyleIds(t,e,["styleId"])}),t}}return!1}replace(e,t,n,r){for(const o of r)(Array.isArray(t[o])||"number"==typeof t[o])&&(Array.isArray(t[o])?t[o]=e.getIds(n,t[o]):t[o]=e.getId(n,t[o]));return t}replaceIds(e,t,n){return this.replace(this.crossOriginIframeMirror,e,t,n)}replaceStyleIds(e,t,n){return this.replace(this.crossOriginIframeStyleMirror,e,t,n)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(e=>{this.replaceIdOnNode(e,t)})}patchRootIdOnNode(e,t){e.type===wa.Document||e.rootId||(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(e=>{this.patchRootIdOnNode(e,t)})}},ll=class{constructor(e){ha(this,"shadowDoms",/* @__PURE__ */new WeakSet),ha(this,"mutationCb"),ha(this,"scrollCb"),ha(this,"bypassOptions"),ha(this,"mirror"),ha(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!Da(e))return;if(this.shadowDoms.has(e))return;this.shadowDoms.add(e);const[n]=Jc({...this.bypassOptions,doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>n.disconnect()),this.restoreHandlers.push(Gc({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(Aa.host(e))),this.restoreHandlers.push(rl({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){e.contentWindow&&e.contentDocument&&this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){const n=this;this.restoreHandlers.push(za(e.prototype,"attachShadow",function(e){return function(r){const o=e.call(this,r),i=Aa.shadowRoot(this);return i&&$c(this)&&n.addShadowRoot(i,t),o}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(t){}}),this.restoreHandlers=[],this.shadowDoms=/* @__PURE__ */new WeakSet}},ul="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",dl="undefined"==typeof Uint8Array?[]:/* @__PURE__ */new Uint8Array(256),pl=0;pl<64;pl++)dl[ul.charCodeAt(pl)]=pl;var hl=function(e){var t,n=new Uint8Array(e),r=n.length,o="";for(t=0;t<r;t+=3)o+=ul[n[t]>>2],o+=ul[(3&n[t])<<4|n[t+1]>>4],o+=ul[(15&n[t+1])<<2|n[t+2]>>6],o+=ul[63&n[t+2]];return r%3==2?o=o.substring(0,o.length-1)+"=":r%3==1&&(o=o.substring(0,o.length-2)+"=="),o},fl=/* @__PURE__ */new Map;var ml=(e,t,n)=>{if(!e||!vl(e,t)&&"object"!=typeof e)return;const r=function(e,t){let n=fl.get(e);return n||(n=/* @__PURE__ */new Map,fl.set(e,n)),n.has(t)||n.set(t,[]),n.get(t)}(n,e.constructor.name);let o=r.indexOf(e);return-1===o&&(o=r.length,r.push(e)),o};function gl(e,t,n){if(e instanceof Array)return e.map(e=>gl(e,t,n));if(null===e)return e;if(e instanceof Float32Array||e instanceof Float64Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Int8Array||e instanceof Uint8ClampedArray)return{rr_type:e.constructor.name,args:[Object.values(e)]};if(e instanceof ArrayBuffer)return{rr_type:e.constructor.name,base64:hl(e)};if(e instanceof DataView)return{rr_type:e.constructor.name,args:[gl(e.buffer,t,n),e.byteOffset,e.byteLength]};if(e instanceof HTMLImageElement){const t=e.constructor.name,{src:n}=e;return{rr_type:t,src:n}}return e instanceof HTMLCanvasElement?{rr_type:"HTMLImageElement",src:e.toDataURL()}:e instanceof ImageData?{rr_type:e.constructor.name,args:[gl(e.data,t,n),e.width,e.height]}:vl(e,t)||"object"==typeof e?{rr_type:e.constructor.name,index:ml(e,t,n)}:e}var yl=(e,t,n)=>e.map(e=>gl(e,t,n)),vl=(e,t)=>{const n=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(e=>"function"==typeof t[e]);return Boolean(n.find(n=>e instanceof t[n]))};function bl(e,t,n,r){const o=[];try{const i=za(e.HTMLCanvasElement.prototype,"getContext",function(e){return function(o,...i){if(!Ic(this,t,n,!0)){const e=function(e){return"experimental-webgl"===e?"webgl":e}(o);if("__context"in this||(this.__context=e),r&&["webgl","webgl2"].includes(e))if(i[0]&&"object"==typeof i[0]){const e=i[0];e.preserveDrawingBuffer||(e.preserveDrawingBuffer=!0)}else i.splice(0,1,{preserveDrawingBuffer:!0})}return e.apply(this,[o,...i])}});o.push(i)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{o.forEach(e=>e())}}function wl(e,t,n,r,o,i){const s=[],a=Object.getOwnPropertyNames(e);for(const c of a)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(c))try{if("function"!=typeof e[c])continue;const a=za(e,c,function(e){return function(...s){const a=e.apply(this,s);if(ml(a,i,this),"tagName"in this.canvas&&!Ic(this.canvas,r,o,!0)){const e=yl(s,i,this),r={type:t,property:c,args:e};n(this.canvas,r)}return a}});s.push(a)}catch{const r=Sc(e,c,{set(e){n(this.canvas,{type:t,property:c,args:[e],setter:!0})}});s.push(r)}return s}var xl='(function() {\n "use strict";\n var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);\n for (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n }\n var encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";\n for (i2 = 0; i2 < len; i2 += 3) {\n base64 += chars[bytes[i2] >> 2];\n base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\n base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\n base64 += chars[bytes[i2 + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + "=";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + "==";\n }\n return base64;\n };\n const lastBlobMap = /* @__PURE__ */ new Map();\n const transparentBlobMap = /* @__PURE__ */ new Map();\n async function getTransparentBlobFor(width, height, dataURLOptions) {\n const id = `${width}-${height}`;\n if ("OffscreenCanvas" in globalThis) {\n if (transparentBlobMap.has(id)) return transparentBlobMap.get(id);\n const offscreen = new OffscreenCanvas(width, height);\n offscreen.getContext("2d");\n const blob = await offscreen.convertToBlob(dataURLOptions);\n const arrayBuffer = await blob.arrayBuffer();\n const base64 = encode(arrayBuffer);\n transparentBlobMap.set(id, base64);\n return base64;\n } else {\n return "";\n }\n }\n const worker = self;\n worker.onmessage = async function(e) {\n if ("OffscreenCanvas" in globalThis) {\n const { id, bitmap, width, height, dataURLOptions } = e.data;\n const transparentBase64 = getTransparentBlobFor(\n width,\n height,\n dataURLOptions\n );\n const offscreen = new OffscreenCanvas(width, height);\n const ctx = offscreen.getContext("2d");\n ctx.drawImage(bitmap, 0, 0);\n bitmap.close();\n const blob = await offscreen.convertToBlob(dataURLOptions);\n const type = blob.type;\n const arrayBuffer = await blob.arrayBuffer();\n const base64 = encode(arrayBuffer);\n if (!lastBlobMap.has(id) && await transparentBase64 === base64) {\n lastBlobMap.set(id, base64);\n return worker.postMessage({ id });\n }\n if (lastBlobMap.get(id) === base64) return worker.postMessage({ id });\n worker.postMessage({\n id,\n type,\n base64,\n width,\n height\n });\n lastBlobMap.set(id, base64);\n } else {\n return worker.postMessage({ id: e.data.id });\n }\n };\n})();\n//# sourceMappingURL=image-bitmap-data-url-worker-IJpC7g_b.js.map\n',Sl="undefined"!=typeof self&&self.Blob&&new Blob([xl],{type:"text/javascript;charset=utf-8"});function kl(e){let t;try{if(t=Sl&&(self.URL||self.webkitURL).createObjectURL(Sl),!t)throw"";const n=new Worker(t,{name:null==e?void 0:e.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch(n){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(xl),{name:null==e?void 0:e.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}var _l,El,Cl,Il=class{constructor(e){ha(this,"pendingCanvasMutations",/* @__PURE__ */new Map),ha(this,"rafStamps",{latestId:0,invokeId:null}),ha(this,"mirror"),ha(this,"mutationCb"),ha(this,"resetObservers"),ha(this,"frozen",!1),ha(this,"locked",!1),ha(this,"processMutation",(e,t)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(e)||this.pendingCanvasMutations.set(e,[]),this.pendingCanvasMutations.get(e).push(t)});const{sampling:t="all",win:n,blockClass:r,blockSelector:o,recordCanvas:i,dataURLOptions:s}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,i&&"all"===t&&this.initCanvasMutationObserver(n,r,o),i&&"number"==typeof t&&this.initCanvasFPSObserver(t,n,r,o,{dataURLOptions:s})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,n,r,o){const i=bl(t,n,r,!0),s=/* @__PURE__ */new Map,a=new kl;a.onmessage=e=>{const{id:t}=e.data;if(s.set(t,!1),!("base64"in e.data))return;const{base64:n,type:r,width:o,height:i}=e.data;this.mutationCb({id:t,type:va["2D"],commands:[{property:"clearRect",args:[0,0,o,i]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:n}],type:r}]},0,0]}]})};const c=1e3/e;let l,u=0;const d=e=>{u&&e-u<c||(u=e,(()=>{const e=[];return t.document.querySelectorAll("canvas").forEach(t=>{Ic(t,n,r,!0)||e.push(t)}),e})().forEach(async e=>{var t;const n=this.mirror.getId(e);if(s.get(n))return;if(0===e.width||0===e.height)return;if(s.set(n,!0),["webgl","webgl2"].includes(e.__context)){const n=e.getContext(e.__context);!1===(null==(t=null==n?void 0:n.getContextAttributes())?void 0:t.preserveDrawingBuffer)&&n.clear(n.COLOR_BUFFER_BIT)}const r=await createImageBitmap(e);a.postMessage({id:n,bitmap:r,width:e.width,height:e.height,dataURLOptions:o.dataURLOptions},[r])})),l=requestAnimationFrame(d)};l=requestAnimationFrame(d),this.resetObservers=()=>{i(),cancelAnimationFrame(l)}}initCanvasMutationObserver(e,t,n){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=bl(e,t,n,!1),o=function(e,t,n,r){const o=[],i=Object.getOwnPropertyNames(t.CanvasRenderingContext2D.prototype);for(const s of i)try{if("function"!=typeof t.CanvasRenderingContext2D.prototype[s])continue;const i=za(t.CanvasRenderingContext2D.prototype,s,function(o){return function(...i){return Ic(this.canvas,n,r,!0)||setTimeout(()=>{const n=yl(i,t,this);e(this.canvas,{type:va["2D"],property:s,args:n})},0),o.apply(this,i)}});o.push(i)}catch{const n=Sc(t.CanvasRenderingContext2D.prototype,s,{set(t){e(this.canvas,{type:va["2D"],property:s,args:[t],setter:!0})}});o.push(n)}return()=>{o.forEach(e=>e())}}(this.processMutation.bind(this),e,t,n),i=function(e,t,n,r){const o=[];return void 0!==t.WebGLRenderingContext&&o.push(...wl(t.WebGLRenderingContext.prototype,va.WebGL,e,n,r,t)),void 0!==t.WebGL2RenderingContext&&o.push(...wl(t.WebGL2RenderingContext.prototype,va.WebGL2,e,n,r,t)),()=>{o.forEach(e=>e())}}(this.processMutation.bind(this),e,t,n);this.resetObservers=()=>{r(),o(),i()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const n=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,n)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const n=this.pendingCanvasMutations.get(e);if(!n||-1===t)return;const r=n.map(e=>{const{type:t,...n}=e;return n}),{type:o}=n[0];this.mutationCb({id:t,type:o,commands:r}),this.pendingCanvasMutations.delete(e)}},Tl=class{constructor(e){ha(this,"trackedLinkElements",/* @__PURE__ */new WeakSet),ha(this,"mutationCb"),ha(this,"adoptedStyleSheetCb"),ha(this,"styleMirror",new Pc),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(0===e.length)return;const n={id:t,styleIds:[]},r=[];for(const o of e){let e;this.styleMirror.has(o)?e=this.styleMirror.getId(o):(e=this.styleMirror.add(o),r.push({styleId:e,rules:Array.from(o.rules||CSSRule,(e,t)=>({rule:La(e,o.href),index:t}))})),n.styleIds.push(e)}r.length>0&&(n.styles=r),this.adoptedStyleSheetCb(n)}reset(){this.styleMirror.reset(),this.trackedLinkElements=/* @__PURE__ */new WeakSet}trackStylesheetInLinkElement(e){}},Ml=class{constructor(){ha(this,"nodeMap",/* @__PURE__ */new WeakMap),ha(this,"active",!1)}inOtherBuffer(e,t){const n=this.nodeMap.get(e);return n&&Array.from(n).some(e=>e!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=/* @__PURE__ */new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||/* @__PURE__ */new Set).add(t))}destroy(){}},Ol=!1;try{if(2!==Array.from([1],e=>2*e)[0]){const e=document.createElement("iframe");document.body.appendChild(e),Array.from=(null==(la=e.contentWindow)?void 0:la.Array.from)||Array.from,document.body.removeChild(e)}}catch(Vy){}var Rl=new Fa;function zl(e={}){const{emit:t,checkoutEveryNms:n,checkoutEveryNth:r,blockClass:o="rr-block",blockSelector:i=null,ignoreClass:s="rr-ignore",ignoreSelector:a=null,maskTextClass:c="rr-mask",maskTextSelector:l=null,inlineStylesheet:u=!0,maskAllInputs:d,maskInputOptions:p,slimDOMOptions:h,maskInputFn:f,maskTextFn:m,hooks:g,packFn:y,sampling:v={},dataURLOptions:b={},mousemoveWait:w,recordDOM:x=!0,recordCanvas:S=!1,recordCrossOriginIframes:k=!1,recordAfter:_=("DOMContentLoaded"===e.recordAfter?e.recordAfter:"load"),userTriggeredOnInput:E=!1,collectFonts:C=!1,inlineImages:I=!1,plugins:T,keepIframeSrcFn:M=()=>!1,ignoreCSSAttributes:O=/* @__PURE__ */new Set([]),errorHandler:R}=e;Fc=R;const z=!k||window.parent===window;let A=!1;if(!z)try{window.parent.document&&(A=!1)}catch(q){A=!0}if(z&&!t)throw new Error("emit function is required");if(!z&&!A)return()=>{};void 0!==w&&void 0===v.mousemove&&(v.mousemove=w),Rl.reset();const P=!0===d?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==p?p:{password:!0},N=mc(h);let D;!function(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let $=0;const L=e=>{for(const t of T||[])t.eventProcessor&&(e=t.eventProcessor(e));return y&&!A&&(e=y(e)),e};_l=(e,o)=>{var i;const s=e;if(s.timestamp=Ra(),!(null==(i=Yc[0])?void 0:i.isFrozen())||s.type===fa.FullSnapshot||s.type===fa.IncrementalSnapshot&&s.data.source===ma.Mutation||Yc.forEach(e=>e.unfreeze()),z)t?.(L(s),o);else if(A){const e={type:"rrweb",event:L(s),origin:window.location.origin,isCheckout:o};window.parent.postMessage(e,"*")}if(s.type===fa.FullSnapshot)D=s,$=0;else if(s.type===fa.IncrementalSnapshot){if(s.data.source===ma.Mutation&&s.data.isAttachIframe)return;$++;const e=r&&$>=r,t=n&&s.timestamp-D.timestamp>n;(e||t)&&El(!0)}};const F=e=>{_l({type:fa.IncrementalSnapshot,data:{source:ma.Mutation,...e}})},j=e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.Scroll,...e}}),U=e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.CanvasMutation,...e}}),W=new Tl({mutationCb:F,adoptedStyleSheetCb:e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.AdoptedStyleSheet,...e}})}),B=new cl({mirror:Rl,mutationCb:F,stylesheetManager:W,recordCrossOriginIframes:k,wrappedEmit:_l});for(const V of T||[])V.getMirror&&V.getMirror({nodeMirror:Rl,crossOriginIframeMirror:B.crossOriginIframeMirror,crossOriginIframeStyleMirror:B.crossOriginIframeStyleMirror});const H=new Ml;Cl=new Il({recordCanvas:S,mutationCb:U,win:window,blockClass:o,blockSelector:i,mirror:Rl,sampling:v.canvas,dataURLOptions:b});const Z=new ll({mutationCb:F,scrollCb:j,bypassOptions:{blockClass:o,blockSelector:i,maskTextClass:c,maskTextSelector:l,inlineStylesheet:u,maskInputOptions:P,dataURLOptions:b,maskTextFn:m,maskInputFn:f,recordCanvas:S,inlineImages:I,sampling:v,slimDOMOptions:N,iframeManager:B,stylesheetManager:W,canvasManager:Cl,keepIframeSrcFn:M,processedNodeManager:H},mirror:Rl});El=(e=!1)=>{if(!x)return;_l({type:fa.Meta,data:{href:window.location.href,width:Ec(),height:_c()}},e),W.reset(),Z.init(),Yc.forEach(e=>e.lock());const t=function(e,t){const{mirror:n=new Fa,blockClass:r="rr-block",blockSelector:o=null,maskTextClass:i="rr-mask",maskTextSelector:s=null,inlineStylesheet:a=!0,inlineImages:c=!1,recordCanvas:l=!1,maskAllInputs:u=!1,maskTextFn:d,maskInputFn:p,slimDOM:h=!1,dataURLOptions:f,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:v,onStylesheetLoad:b,stylesheetLoadTimeout:w,keepIframeSrcFn:x=()=>!1}=t;return gc(e,{doc:e,mirror:n,blockClass:r,blockSelector:o,maskTextClass:i,maskTextSelector:s,skipChild:!1,inlineStylesheet:a,maskInputOptions:!0===u?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===u?{password:!0}:u,maskTextFn:d,maskInputFn:p,slimDOMOptions:mc(h),dataURLOptions:f,inlineImages:c,recordCanvas:l,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:v,onStylesheetLoad:b,stylesheetLoadTimeout:w,keepIframeSrcFn:x,newlyAddedElement:!1})}(document,{mirror:Rl,blockClass:o,blockSelector:i,maskTextClass:c,maskTextSelector:l,inlineStylesheet:u,maskAllInputs:P,maskTextFn:m,maskInputFn:f,slimDOM:N,dataURLOptions:b,recordCanvas:S,inlineImages:I,onSerialize:e=>{Rc(e,Rl)&&B.addIframe(e),zc(e,Rl)&&W.trackLinkElement(e),Ac(e)&&Z.addShadowRoot(Aa.shadowRoot(e),document)},onIframeLoad:(e,t)=>{B.attachIframe(e,t),Z.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{W.attachLinkElement(e,t)},keepIframeSrcFn:M});if(!t)return console.warn("Failed to snapshot the document");_l({type:fa.FullSnapshot,data:{node:t,initialOffset:kc(window)}},e),Yc.forEach(e=>e.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&W.adoptStyleSheets(document.adoptedStyleSheets,Rl.getId(document))};try{const e=[],t=e=>{var t;return Vc(ol)({mutationCb:F,mousemoveCb:(e,t)=>_l({type:fa.IncrementalSnapshot,data:{source:t,positions:e}}),mouseInteractionCb:e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.MouseInteraction,...e}}),scrollCb:j,viewportResizeCb:e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.ViewportResize,...e}}),inputCb:e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.Input,...e}}),mediaInteractionCb:e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.MediaInteraction,...e}}),styleSheetRuleCb:e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.StyleSheetRule,...e}}),styleDeclarationCb:e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.StyleDeclaration,...e}}),canvasMutationCb:U,fontCb:e=>_l({type:fa.IncrementalSnapshot,data:{source:ma.Font,...e}}),selectionCb:e=>{_l({type:fa.IncrementalSnapshot,data:{source:ma.Selection,...e}})},customElementCb:e=>{_l({type:fa.IncrementalSnapshot,data:{source:ma.CustomElement,...e}})},blockClass:o,ignoreClass:s,ignoreSelector:a,maskTextClass:c,maskTextSelector:l,maskInputOptions:P,inlineStylesheet:u,sampling:v,recordDOM:x,recordCanvas:S,inlineImages:I,userTriggeredOnInput:E,collectFonts:C,doc:e,maskInputFn:f,maskTextFn:m,keepIframeSrcFn:M,blockSelector:i,slimDOMOptions:N,dataURLOptions:b,mirror:Rl,iframeManager:B,stylesheetManager:W,shadowDomManager:Z,processedNodeManager:H,canvasManager:Cl,ignoreCSSAttributes:O,plugins:(null==(t=null==T?void 0:T.filter(e=>e.observer))?void 0:t.map(e=>({observer:e.observer,options:e.options,callback:t=>_l({type:fa.Plugin,data:{plugin:e.name,payload:t}})})))||[]},g)};B.addLoadListener(n=>{try{e.push(t(n.contentDocument))}catch(ko){console.warn(ko)}});const n=()=>{El(),e.push(t(document)),Ol=!0};return["interactive","complete"].includes(document.readyState)?n():(e.push(vc("DOMContentLoaded",()=>{_l({type:fa.DomContentLoaded,data:{}}),"DOMContentLoaded"===_&&n()})),e.push(vc("load",()=>{_l({type:fa.Load,data:{}}),"load"===_&&n()},window))),()=>{e.forEach(e=>{try{e()}catch(ko){String(ko).toLowerCase().includes("cross-origin")||console.warn(ko)}}),H.destroy(),Ol=!1,Fc=void 0}}catch(ko){console.warn(ko)}}zl.addCustomEvent=(e,t)=>{if(!Ol)throw new Error("please add custom event after start recording");_l({type:fa.Custom,data:{tag:e,payload:t}})},zl.freezePage=()=>{Yc.forEach(e=>e.freeze())},zl.takeFullSnapshot=e=>{if(!Ol)throw new Error("please take full snapshot after start recording");El(e)},zl.mirror=Rl;var Al=class extends Error{},Pl=class e{static instance=null;abortController=null;chatId=null;status="disconnected";callbacks=/* @__PURE__ */new Set;tornDown=!1;credentialRejected=!1;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;maxReconnectDelay=3e4;reconnectTimer=null;connectionId=0;tabId=globalThis.crypto.randomUUID();registrationWaiters=/* @__PURE__ */new Set;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}addCallbacks(e){this.callbacks.add(e)}removeCallbacks(e){this.callbacks.delete(e)}isConnected(){return"registered"===this.status}reconnectSuppressed(){return this.tornDown||this.credentialRejected}canReconnect(){return null!==this.chatId&&!this.reconnectSuppressed()&&!this.isConnected()}reconnectNow(){this.canReconnect()&&null!==this.chatId&&(this.clearReconnectTimer(),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.connect(this.chatId).catch(console.error))}async ready(e){await this.connect(e),await this.waitUntilRegistered()}async waitUntilRegistered(){if(!this.isConnected()){if(this.credentialRejected)throw new Al("Chat is unavailable — the widget credentials were rejected.");await new Promise((e,t)=>this.registrationWaiters.add({resolve:e,reject:t}))}}async connect(e){if(this.credentialRejected)return;if(this.tornDown=!1,this.chatId===e&&("connecting"===this.status||"open"===this.status||"registered"===this.status))return;this.abortController&&(this.abortController.abort(),this.abortController=null),this.chatId=e,this.status="connecting";const t=++this.connectionId;this.abortController=new AbortController;const n=this.abortController.signal;try{const r=ua.getCredentialedConfig(),o=await oa.widgetStream({chat_id:e,tab_id:this.tabId,...r&&{marketrix_id:r.mtxId,marketrix_key:r.mtxKey}},{signal:n});this.status="open",this.consumeEvents(o,t)}catch(ko){n.aborted||(console.error("[StreamClient] Connection failed:",ko),this.status="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(ko){this.connectionId!==t?n=!0:this.reconnectSuppressed()||(console.warn("[StreamClient] Stream error:",ko),this.status="error")}finally{n||this.connectionId!==t||this.reconnectSuppressed()||(this.status="disconnected",this.scheduleReconnect())}}disconnect(){this.tornDown=!0,this.credentialRejected=!1,this.clearReconnectTimer(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.status="disconnected",this.chatId=null,this.settleWaiters(/* @__PURE__ */new Error("Stream disconnected before registration"))}send(e){return this.chatId?oa.widgetMessagePost({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"))}notifyError(e){this.callbacks.forEach(t=>t.onError?.(e))}settleWaiters(e){for(const t of this.registrationWaiters)t.reject(e);this.registrationWaiters.clear()}giveUp(e){const t=new Al(e);this.notifyError(t),this.settleWaiters(t)}handleMessage(e){if(!this.reconnectSuppressed()&&"heartbeat"!==e.type){if("registered"===e.type&&e.chat_id===this.chatId){this.status="registered",this.reconnectAttempts=0,this.reconnectDelay=1e3;for(const e of this.registrationWaiters)e.resolve();this.registrationWaiters.clear()}"chat/error"===e.type&&"auth"===e.request_id&&(console.error("[StreamClient] Authentication failed — will not reconnect"),this.credentialRejected=!0,this.giveUp("Chat is unavailable — the widget credentials were rejected.")),this.callbacks.forEach(t=>t.onMessage?.(e))}}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.giveUp("Could not reconnect to the assistant. Try again.");this.clearReconnectTimer(),this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);this.reconnectTimer=setTimeout(()=>{!this.reconnectSuppressed()&&this.chatId&&this.connect(this.chatId).catch(console.error)},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},Nl=class{chatId;applicationId;events=[];sessionId=globalThis.crypto.randomUUID();stopRecording=null;flushTimer=null;flushPromise=Promise.resolve();stopped=!1;constructor(e,t){this.chatId=e,this.applicationId=t}async start(){this.stopRecording||this.stopped||(await Pl.getInstance().ready(this.chatId),this.stopped||(await oa.widgetMessagePost({chat_id:this.chatId,command:{type:"rrweb/metadata",rrweb_session_id:this.sessionId,chat_id:this.chatId,application_id:this.applicationId,url:window.location.href,user_agent:navigator.userAgent,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}}}),this.stopped||(this.stopRecording=zl({emit:e=>this.buffer(e),maskAllInputs:!0,maskTextClass:/^(rr-mask|mtx-mask)$/,blockClass:/^(rr-block|mtx-block)$/}))))}stop(){this.stopped=!0,this.stopRecording?.(),this.stopRecording=null,this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.flush()}buffer(e){this.events.push(e),this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flush()},500))}flush(){return this.flushPromise=this.flushPromise.then(async()=>{this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null;const e=this.events.splice(0);if(e.length)try{await oa.widgetMessagePost({chat_id:this.chatId,command:{type:"rrweb/events",rrweb_session_id:this.sessionId,events:e}})}catch(ko){this.events=e.concat(this.events).slice(0,2e4),console.error("Failed to record session events:",ko)}}),this.flushPromise}};var Dl=e=>`Widget settings are invalid: ${[...new Set(e.issues.map(e=>e.path.join(".")||"settings"))].join(", ")}`;function $l(e,t={}){return{...t,...e}}function Ll(e){return e.mtxId??(null!=e.mtxApp?String(e.mtxApp):"default")}function Fl(e){return e instanceof Error?e.message:"string"==typeof e?e:"Unknown error"}function jl(e,t){const n=new Error(e);return n.cause=t,n}async function Ul(e){const{mtxId:t,mtxKey:n}=e;if(!t||!n)throw new Error("Please provide mtxId + mtxKey");let r;try{({items:r}=await oa.widgetSearch({marketrix_id:t,marketrix_key:n}))}catch(ko){throw function(e,t){const n=Fl(e);return n.includes("Failed to fetch")||n.includes("ERR_CONNECTION_REFUSED")||n.includes("NetworkError")||n.includes("Network request failed")?jl(`Cannot connect to API server. Please ensure the API server is running at ${t.mtxApiHost||"configured API server"}. Error: ${n}`,e):jl(`Widget validation failed: ${n}`,e)}(ko,e)}if(!r.length)throw new Error("Widget not found or invalid credentials");const o=r.find(e=>"active"===e.status);if(!o){const e=r.map(e=>e.status).join(", ");throw new Error(`Found widget(s) but none are active. Current status(es): ${e}. Please activate the widget in the dashboard.`)}if(!o.application_id)throw new Error("Widget missing application_id");try{await oa.applicationGet({application_id:o.application_id})}catch(ko){throw jl(`Failed to validate application: ${Fl(ko)}`,ko)}let i;try{i=await oa.widgetDefaultGet({type:"widget"})}catch(ko){throw jl(`Failed to fetch widget settings from API: ${Fl(ko)}`,ko)}const s=Gs.safeParse({...i,...o.settings});if(!s.success)throw new Error(Dl(s.error));return{...$l(s.data,e),mtxId:t,mtxKey:n,mtxApp:o.application_id}}function Wl(){}var Bl=Object.freeze([]),Hl=Object.freeze({});function Zl(t){e.useEffect(t,Bl)}var ql={};function Vl(t,n){const r=e.useRef(ql);return r.current===ql&&(r.current=t(n)),r}var Yl="undefined"!=typeof document?e.useLayoutEffect:()=>{};var Kl,Jl,Xl=(Kl="https://base-ui.com/production-error",Jl="Base UI",function(e,...t){const n=new URL(Kl);return n.searchParams.set("code",e.toString()),t.forEach(e=>n.searchParams.append("args[]",e)),`${Jl} error #${e}; visit ${n} for the full message.`}),Gl=/*#__PURE__*/e.createContext(void 0);function Ql(){const t=e.useContext(Gl);if(!t)throw new Error(Xl(73));return t}var eu=parseInt(e.version,10);function tu(e){return eu>=e}var nu=[];var ru,ou=tu(19)?function(t,n,r,o,i){const s=void 0;if(!s)return function(t,n,r,o,i){const s=e.useCallback(()=>n(t.getSnapshot(),r,o,i),[t,n,r,o,i]);return h(t.subscribe,s,s)}(t,n,r,o,i);const a=s.syncIndex;let c;s.syncIndex+=1,s.didInitialize?(c=s.syncHooks[a],c.store===t&&c.selector===n&&Object.is(c.a1,r)&&Object.is(c.a2,o)&&Object.is(c.a3,i)||(c.store!==t&&(s.didChangeStore=!0),c.store=t,c.selector=n,c.a1=r,c.a2=o,c.a3=i,c.value=n(t.getSnapshot(),r,o,i))):(c={store:t,selector:n,a1:r,a2:o,a3:i,value:n(t.getSnapshot(),r,o,i)},s.syncHooks.push(c));return c.value}:function(e,t,n,r,o){return function(){throw new Error("React 19 uses its native useSyncExternalStore")}(e.subscribe,e.getSnapshot,e.getSnapshot)};function iu(e,t,n,r,o){return ou(e,t,n,r,o)}ru={before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let n=0;n<e.syncHooks.length;n+=1){const r=e.syncHooks[n],o=r.selector(r.store.state,r.a1,r.a2,r.a3);Object.is(r.value,o)||(t=!0,r.value=o)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const n=/* @__PURE__ */new Set;for(const o of e.syncHooks)n.add(o.store);const r=[];for(const e of n)r.push(e.subscribe(t));return()=>{for(const e of r)e()}}),h(e.subscribe,e.getSnapshot,e.getSnapshot))}},nu.push(ru);var su=class{constructor(e){this.state=e,this.listeners=/* @__PURE__ */new Set,this.updateTick=0}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.state;setState(e){if(this.state===e)return;this.state=e,this.updateTick+=1;const t=this.updateTick;for(const n of this.listeners){if(t!==this.updateTick)return;n(e)}}update(e){for(const t in e)if(!Object.is(this.state[t],e[t]))return void this.setState({...this.state,...e})}set(e,t){Object.is(this.state[e],t)||this.setState({...this.state,[e]:t})}notifyAll(){const e={...this.state};this.setState(e)}use(e,t,n,r){return iu(this,e,t,n,r)}},au={...e},cu=au.useInsertionEffect,lu=cu&&cu!==au.useLayoutEffect?cu:e=>e();function uu(e){const t=Vl(du).current;return t.next=e,lu(t.effect),t.trampoline}function du(){const e={next:void 0,callback:pu,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function pu(){}var hu=class extends su{constructor(e,t={},n){super(e),this.context=t,this.selectors=n}useSyncedValue(t,n){e.useDebugValue(t);const r=this;Yl(()=>{r.state[t]!==n&&r.set(t,n)},[r,t,n])}useSyncedValueWithCleanup(e,t){const n=this;Yl(()=>(n.state[e]!==t&&n.set(e,t),()=>{n.set(e,void 0)}),[n,e,t])}useSyncedValues(e){const t=this,n=Object.values(e);Yl(()=>{t.update(e)},[t,...n])}useControlledProp(t,n){e.useDebugValue(t);const r=this,o=void 0!==n;Yl(()=>{o&&!Object.is(r.state[t],n)&&r.setState({...r.state,[t]:n})},[r,t,n,o])}select(e,t,n,r){return(0,this.selectors[e])(this.state,t,n,r)}useState(t,n,r,o){return e.useDebugValue(t),iu(this,this.selectors[t],n,r,o)}useContextCallback(t,n){e.useDebugValue(t);const r=uu(n??Wl);this.context[t]=r}useStateSetter(t){const n=e.useRef(void 0);return void 0===n.current&&(n.current=e=>{this.set(t,e)}),n.current}observe(e,t){let n;n="function"==typeof e?e:this.selectors[e];let r=n(this.state);return t(r,r,this),this.subscribe(e=>{const o=n(e);if(!Object.is(r,o)){const e=r;r=o,t(o,e,this)}})}};function fu(){return"undefined"!=typeof window}function mu(e){return yu(e)?(e.nodeName||"").toLowerCase():"#document"}function gu(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function yu(e){return!!fu()&&(e instanceof Node||e instanceof gu(e).Node)}function vu(e){return!!fu()&&(e instanceof Element||e instanceof gu(e).Element)}function bu(e){return!!fu()&&(e instanceof HTMLElement||e instanceof gu(e).HTMLElement)}function wu(e){return!(!fu()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof gu(e).ShadowRoot)}function xu(e){return/^(html|body|#document)$/.test(mu(e))}function Su(e){return gu(e).getComputedStyle(e)}function ku(e){if("html"===mu(e))return e;const t=e.assignedSlot||e.parentNode||wu(e)&&e.host||function(e){var t;return null==(t=(yu(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}(e);return wu(t)?t.host:t}function _u(...e){return()=>{for(let t=0;t<e.length;t+=1){const n=e[t];n&&n()}}}function Eu(e){return e?.ownerDocument||document}function Cu(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}var Iu=null;globalThis.requestAnimationFrame;var Tu=new class{callbacks=[];callbacksCount=0;nextId=1;startId=1;isScheduled=!1;tick=e=>{this.isScheduled=!1;const t=this.callbacks,n=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,n>0)for(let r=0;r<t.length;r+=1)t[r]?.(e)};request(e){const t=this.nextId;return this.nextId+=1,this.callbacks.push(e),this.callbacksCount+=1,this.isScheduled||(requestAnimationFrame(this.tick),this.isScheduled=!0),t}cancel(e){const t=e-this.startId;t<0||t>=this.callbacks.length||(this.callbacks[t]=null,this.callbacksCount-=1)}},Mu=class e{static create(){return new e}static request(e){return Tu.request(e)}static cancel(e){return Tu.cancel(e)}currentId=Iu;request(e){this.cancel(),this.currentId=Tu.request(()=>{this.currentId=Iu,e()})}cancel=()=>{this.currentId!==Iu&&(Tu.cancel(this.currentId),this.currentId=Iu)};disposeEffect=()=>this.cancel};function Ou(){const e=Vl(Mu.create).current;return Zl(e.disposeEffect),e}var Ru=class e{static create(){return new e}currentId=0;start(e,t){this.clear(),this.currentId=setTimeout(()=>{this.currentId=0,t()},e)}isStarted(){return 0!==this.currentId}clear=()=>{0!==this.currentId&&(clearTimeout(this.currentId),this.currentId=0)};disposeEffect=()=>this.clear};function zu(){const e=Vl(Ru.create).current;return Zl(e.disposeEffect),e}var Au=0;function Pu(e,t){if("string"==typeof e)return{description:e};if("function"==typeof e){const n=e(t);return"string"==typeof n?{description:n}:n}return e}var{userAgent:Nu,platform:Du,maxTouchPoints:$u}="undefined"==typeof navigator?{userAgent:"",platform:"",maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??0},Lu=Nu.toLowerCase(),Fu=Du.toLowerCase(),ju=/^i(os$|p)/.test(Fu)||"macintel"===Fu&&$u>1,Uu="android",Wu=Fu===Uu||Lu.includes(Uu),Bu=!ju&&Fu.startsWith("mac"),Hu=(Fu.startsWith("win"),!Wu&&/^(linux|chrome os)/.test(Fu),Bu||ju),Zu="undefined"!=typeof CSS&&!!CSS.supports?.("-webkit-backdrop-filter:none"),qu=(!Zu&&Lu.includes("firefox"),!Zu&&Lu.includes("chrom"),Hu),Vu=/jsdom|happydom/.test(Lu),Yu="data-base-ui-focusable";function Ku(e){let t=e.activeElement;for(;null!=t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function Ju(e,t){if(!e||!t)return!1;const n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&wu(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function Xu(e){return"composedPath"in e?e.composedPath()[0]:e.target}function Gu(e,t){if(null==t)return!1;if("composedPath"in e)return e.composedPath().includes(t);const n=e;return null!=n.target&&t.contains(n.target)}function Qu(e){return bu(e)&&e.matches("input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])")}function ed(e){return!!e&&("combobox"===e.getAttribute("role")&&Qu(e))}function td(e){if(!e||Vu)return!0;try{return e.matches(":focus-visible")}catch(t){return!0}}function nd(e){return e?e.hasAttribute("data-base-ui-focusable")?e:e.querySelector("[data-base-ui-focusable]")||e:null}function rd(e,t,n=!0){return e.filter(e=>e.parentId===t).flatMap(t=>[...!n||t.context?.open?[t]:[],...rd(e,t.id,n)])}function od(e,t){let n=[],r=e.find(e=>e.id===t)?.parentId;for(;r;){const t=e.find(e=>e.id===r);r=t?.parentId,t&&(n=n.concat(t))}return n}function id(e,t){return t<0||t>=e.length}function sd(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:o=1}={}){let i=t;do{i+=n?-o:o}while(i>=0&&i<=e.length-1&&ad(e,i,r));return i}function ad(e,t,n){if("function"==typeof n?n(t):n?.includes(t))return!0;const r=e[t];return!!r&&(!cd(r)||(!!r.matches(":disabled")||!n&&(r.hasAttribute("disabled")||"true"===r.getAttribute("aria-disabled"))))}function cd(e,t=(e?Su(e):null)){return!(!(e&&e.isConnected&&t)||function(e){return"hidden"===e.visibility||"collapse"===e.visibility}(t))&&("function"==typeof e.checkVisibility?e.checkVisibility():"none"!==t.display&&"contents"!==t.display)}function ld(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const n=e.getRootNode();return wu(n)?n.host:null}function ud(e){for(const t of Array.from(e.children))if("summary"===mu(t))return t;return null}function dd(e,t){const n=ud(t);return!!n&&(e===n||Ju(n,e))}function pd(e){const t=e?mu(e):"";return null!=e&&e.matches('a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]')&&("summary"!==t||null!=e.parentElement&&"details"===mu(e.parentElement)&&ud(e.parentElement)===e)&&("details"!==t||null==ud(e))&&("input"!==t||"hidden"!==e.type)}function hd(e){if(!pd(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=ld(t)){const n=t!==e,r="slot"===mu(t);if(t.hasAttribute("inert"))return!1;if(n&&"details"===mu(t)&&!t.open&&!dd(e,t)||t.hasAttribute("hidden")||!r&&!fd(t,n))return!1}return!0}function fd(e,t){const n=Su(e);return t?"none"!==n.display:cd(e,n)}function md(e){const t=e.tabIndex;if(t<0){const t=mu(e);if("details"===t||"audio"===t||"video"===t||bu(e)&&e.isContentEditable)return 0}return t}function gd(e){if("input"!==mu(e))return null;const t=e;return"radio"===t.type&&""!==t.name?t:null}function yd(e){if(bu(e)&&"slot"===mu(e)){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return bu(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function vd(e,t){yd(e).forEach(e=>{pd(e)&&t.push(e),vd(e,t)})}function bd(e,t,n){yd(e).forEach(e=>{bu(e)&&e.matches(t)&&n.push(e),bd(e,t,n)})}function wd(e){return hd(e)&&md(e)>=0}function xd(e){const t=[];return vd(e,t),t.filter(hd)}function Sd(e){const t=xd(e);return t.filter(e=>md(e)>=0&&function(e,t){const n=gd(e);if(!n)return!0;const r=t.find(e=>{const t=gd(e);return t?.name===n.name&&t.form===n.form&&t.checked});return r?r===n:t.find(e=>{const t=gd(e);return t?.name===n.name&&t.form===n.form})===n}(e,t))}function kd(e,t){const n=Sd(e),r=n.length;if(0===r)return;const o=Ku(Eu(e)),i=n.indexOf(o);return n[-1===i?1===t?0:r-1:i+t]}function _d(e){return kd(Eu(e).body,1)||e}function Ed(e){return kd(Eu(e).body,-1)||e}function Cd(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!Ju(n,r)}function Id(e){const t=[];bd(e,"[data-tabindex]",t),t.forEach(e=>{const t=e.dataset.tabindex;delete e.dataset.tabindex,t?e.setAttribute("tabindex",t):e.removeAttribute("tabindex")})}function Td(e){const t=/* @__PURE__ */new Map;let n=0,r=0;return e.forEach((e,o)=>{const i="ending"===e.transitionStatus;t.set(e.id,{value:e,domIndex:o,visibleIndex:i?-1:n,offsetY:r}),r+=e.height||0,i||(n+=1)}),t}function Md(e,t){let n=0;return e.map(e=>{if("ending"===e.transitionStatus)return e;const r=n>=t;return n+=1,e.limited===r?e:{...e,limited:r}})}var Od={toasts:e=>e.toasts,isEmpty:e=>0===e.toasts.length,toast:(e,t)=>e.toastMetadata.get(t)?.value,toastIndex:(e,t)=>e.toastMetadata.get(t)?.domIndex??-1,toastOffsetY:(e,t)=>e.toastMetadata.get(t)?.offsetY??0,toastVisibleIndex:(e,t)=>e.toastMetadata.get(t)?.visibleIndex??-1,focused:e=>e.focused,expanded:e=>e.hovering||e.focused,expandedOrOutOfFocus:e=>e.hovering||e.focused||!e.isWindowFocused,prevFocusElement:e=>e.prevFocusElement},Rd=class extends hu{timers=/* @__PURE__ */new Map;areTimersPaused=!1;constructor(e){super({...e,toastMetadata:Td(e.toasts)},{},Od)}setViewport=e=>{this.set("viewport",e)};syncProviderProps(e,t){const n=this.state.limit!==t;if(this.state.timeout===e&&!n)return;const r={timeout:e,limit:t};if(n){const e=Md(this.state.toasts,t);r.toasts=e,r.toastMetadata=Td(e)}this.update(r)}disposeEffect=()=>()=>{this.timers.forEach(e=>{e.timeout?.clear()}),this.timers.clear()};removeToast(e,t=!1){const n=Od.toastIndex(this.state,e);if(-1===n)return;const r=this.state.toasts[n];t||r?.onRemove?.();const o=[...this.state.toasts];o.splice(n,1),this.setToasts(o)}addToast=e=>{const{timeout:t,limit:n}=this.state,r=e.id||function(e){return Au+=1,`${e}-${Math.random().toString(36).slice(2,6)}-${Au}`}("toast");if(e.id){const t=Od.toast(this.state,e.id);if(t){if("ending"!==t.transitionStatus){const{id:t,transitionStatus:n,...r}=e;return this.updateToastInternal(e.id,r,!0,!0),e.id}this.removeToast(e.id,!0)}}const o={...e,id:r,updateKey:0,transitionStatus:"starting"},i=[o,...this.state.toasts];this.setToasts(Md(i,n));const s=o.timeout??t;return"loading"!==o.type&&s>0&&this.scheduleTimer(r,s,()=>this.closeToast(r)),Od.expandedOrOutOfFocus(this.state)&&this.pauseTimers(),r};updateToast=(e,t)=>{this.updateToastInternal(e,t,!1,!0)};updateToastInternal=(e,t,n=!1,r=!1)=>{const{timeout:o,toasts:i}=this.state,s=Od.toast(this.state,e);if(!s)return;if("ending"===s.transitionStatus)return;const a={...s,...t,...r&&{updateKey:s.updateKey+1}};this.setToasts(i.map(t=>t.id===e?a:t));const c=a.timeout??o,l=s.timeout??o,u=Object.hasOwn(t,"timeout"),d="ending"!==a.transitionStatus&&"loading"!==a.type&&c>0,p=this.timers.has(e),h=l!==c,f="loading"===s.type;d||!p?d&&(!p||h||u||f||n)&&(this.clearTimer(e),this.scheduleTimer(e,c,()=>this.closeToast(e)),Od.expandedOrOutOfFocus(this.state)&&this.pauseTimers()):this.clearTimer(e)};closeToast=e=>{const t=void 0===e,{limit:n,toasts:r}=this.state;let o;if(t)o=r,this.clearTimers();else{const t=Od.toast(this.state,e);if(!t)return;o=[t],this.clearTimer(e)}const i=Md(r.map(n=>t||n.id===e?{...n,transitionStatus:"ending",height:0}:n),n);this.setToasts(i,!i.some(e=>"ending"!==e.transitionStatus)),o.forEach(e=>{"ending"!==e.transitionStatus&&e.onClose?.()}),this.handleFocusManagement(e)};promiseToast=(e,t)=>{const n=Pu(t.loading),r=this.addToast({...n,type:"loading"}),o=e.then(e=>{const n=Pu(t.success,e);return this.updateToast(r,{...n,type:"success",timeout:n.timeout}),e}).catch(e=>{const n=Pu(t.error,e);return this.updateToast(r,{...n,type:"error",timeout:n.timeout}),Promise.reject(e)});return{}.hasOwnProperty.call(t,"setPromise")&&t.setPromise(o),o};pauseTimers(){this.areTimersPaused||(this.areTimersPaused=!0,this.timers.forEach(e=>{e.timeout&&(e.timeout.clear(),e.remaining=Math.max(e.remaining-(Date.now()-e.start),0))}))}resumeTimers(){this.areTimersPaused&&(this.areTimersPaused=!1,this.timers.forEach((e,t)=>{e.remaining=e.remaining>0?e.remaining:e.delay,e.timeout??=Ru.create(),e.timeout.start(e.remaining,()=>{this.handleTimerFired(t),e.callback()}),e.start=Date.now()}))}restoreFocusToPrevElement(){this.state.prevFocusElement?.focus({preventScroll:!0})}handleDocumentPointerDown=e=>{if("touch"!==e.pointerType)return;const t=Xu(e);Ju(this.state.viewport,t)||(this.resumeTimers(),this.update({hovering:!1,focused:!1}))};scheduleTimer(e,t,n){const r=Date.now(),o=Od.expandedOrOutOfFocus(this.state)?void 0:Ru.create();o?.start(t,()=>{this.handleTimerFired(e),n()}),this.timers.set(e,{timeout:o,start:r,delay:t,remaining:t,callback:n})}clearTimers(){this.timers.forEach(e=>{e.timeout?.clear()}),this.timers.clear(),this.areTimersPaused=!1}clearTimer(e){this.timers.get(e)?.timeout?.clear(),this.timers.delete(e),this.resetPausedStateIfNoTimersRemain()}handleTimerFired(e){this.timers.delete(e),this.resetPausedStateIfNoTimersRemain()}resetPausedStateIfNoTimersRemain(){0===this.timers.size&&(this.areTimersPaused=!1)}setToasts(e,t=0===e.length){const n={toasts:e,toastMetadata:Td(e)};t&&(n.hovering=!1,n.focused=!1),this.update(n)}handleFocusManagement(e){const t=Ku(Eu(this.state.viewport));if(!this.state.viewport||!Ju(this.state.viewport,t)||!td(t))return;if(void 0===e)return void this.restoreFocusToPrevElement();const n=Od.toasts(this.state),r=Od.toastIndex(this.state,e),o=(e,t)=>{for(let r=e;r>=0&&r<n.length;r+=t)if("ending"!==n[r].transitionStatus)return n[r];return null},i=o(r+1,1)??o(r-1,-1);i?i.ref?.current?.focus():this.restoreFocusToPrevElement()}},zd=function(t){const{children:n,timeout:r=5e3,limit:o=3,toastManager:i}=t,s=Vl(()=>new Rd({timeout:r,limit:o,viewport:null,toasts:[],hovering:!1,focused:!1,isWindowFocused:!0,prevFocusElement:null})).current;return Zl(s.disposeEffect),e.useEffect(function(){if(i)return i[" subscribe"](({action:e,options:t})=>{const n=t.id;"promise"===e&&t.promise?s.promiseToast(t.promise,t):"update"===e&&n?s.updateToast(n,t):"close"===e?s.closeToast(n):s.addToast(t)})},[s,i]),/*#__PURE__*/v(Gl.Provider,{value:s,children:[/*#__PURE__*/y(Ad,{store:s,timeout:r,limit:o}),n]})};function Ad(e){const{store:t,timeout:n,limit:r}=e;return Yl(()=>{t.syncProviderProps(n,r)},[t,n,r]),null}var Pd={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1},Nd={...Pd,position:"fixed",top:0,left:0},Dd=/*#__PURE__*/e.forwardRef(function(t,n){const[r,o]=e.useState();Yl(()=>{qu&&Zu&&o("button")},[]);/*#__PURE__*/
3
- return y("span",{...t,ref:n,style:Nd,"aria-hidden":!r||void 0,...{tabIndex:0,role:r},"data-base-ui-focus-guard":""})});function $d(e,t,n,r){const o=Vl(Ld).current;return function(e,t,n,r,o){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==o}(o,e,t,n,r)&&Fd(o,[e,t,n,r]),o.callback}function Ld(){return{callback:null,cleanup:null,refs:[]}}function Fd(e,t){e.refs=t,t.every(e=>null==e)?e.callback=null:e.callback=n=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),null!=n){const r=Array(t.length).fill(null);for(let e=0;e<t.length;e+=1){const o=t[e];if(null!=o)switch(typeof o){case"function":{const t=o(n);"function"==typeof t&&(r[e]=t);break}case"object":o.current=n}}e.cleanup=()=>{for(let e=0;e<t.length;e+=1){const n=t[e];if(null!=n)switch(typeof n){case"function":{const t=r[e];"function"==typeof t?t():n(null);break}case"object":n.current=null}}}}}}function jd(t){if(!/*#__PURE__*/e.isValidElement(t))return null;const n=t,r=n.props;return(tu(19)?r?.ref:n.ref)??null}function Ud(e,t){return e&&!t?e:!e&&t?t:e||t?{...e,...t}:void 0}var Wd={};function Bd(e,t,n,r,o){if(!(n||r||o||e))return Hd(t);let i=Hd(e);return t&&(i=Zd(i,t)),n&&(i=Zd(i,n)),r&&(i=Zd(i,r)),o&&(i=Zd(i,o)),i}function Hd(e){return Vd(e)?{...Yd(e,Wd)}:function(e){const t={...e};for(const n in t){const e=t[n];qd(n,e)&&(t[n]=Jd(e))}return t}(e)}function Zd(e,t){return Vd(t)?Yd(t,e):function(e,t){if(!t)return e;for(const n in t){const r=t[n];switch(n){case"style":e[n]=Ud(e.style,r);break;case"className":e[n]=Gd(e.className,r);break;default:qd(n,r)?e[n]=Kd(e[n],r):e[n]=r}}return e}(e,t)}function qd(e,t){const n=e.charCodeAt(0),r=e.charCodeAt(1),o=e.charCodeAt(2);return 111===n&&110===r&&o>=65&&o<=90&&("function"==typeof t||void 0===t)}function Vd(e){return"function"==typeof e}function Yd(e,t){return Vd(e)?e(t):e??Wd}function Kd(e,t){return t?e?(...n)=>{const r=n[0];if(Qd(r)){const o=r;Xd(o);const i=t(...n);return o.baseUIHandlerPrevented||e?.(...n),i}const o=t(...n);return e?.(...n),o}:Jd(t):e}function Jd(e){return e?(...t)=>{const n=t[0];return Qd(n)&&Xd(n),e(...t)}:e}function Xd(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function Gd(e,t){return t?e?t+" "+e:t:e}function Qd(e){return null!=e&&"object"==typeof e&&"nativeEvent"in e}function ep(t,n,o={}){const i=n.render,s=function(e,t={}){const{className:n,style:r,render:o}=e,{state:i=Hl,ref:s,props:a,stateAttributesMapping:c,enabled:l=!0}=t,u=l?function(e,t){return"function"==typeof e?e(t):e}(n,i):void 0,d=l?function(e,t){return"function"==typeof e?e(t):e}(r,i):void 0,p=l?function(e,t){const n={};for(const r in e){const o=e[r];if(t?.hasOwnProperty(r)){const e=t[r](o);null!=e&&Object.assign(n,e);continue}!0===o?n[`data-${r.toLowerCase()}`]="":o&&(n[`data-${r.toLowerCase()}`]=o.toString())}return n}(i,c):Hl,h=l&&a?function(e){return Array.isArray(e)?function(e){if(0===e.length)return Wd;if(1===e.length)return Hd(e[0]);let t=Hd(e[0]);for(let n=1;n<e.length;n+=1)t=Zd(t,e[n]);return t}(e):Bd(void 0,e)}(a):void 0,f=l?Ud(p,h)??{}:Hl;"undefined"!=typeof document&&(l?Array.isArray(s)?f.ref=function(e){const t=Vl(Ld).current;return function(e,t){return e.refs.length!==t.length||e.refs.some((e,n)=>e!==t[n])}(t,e)&&Fd(t,e),t.callback}([f.ref,jd(o),...s]):f.ref=$d(f.ref,jd(o),s):$d(null,null));if(!l)return Hl;void 0!==u&&(f.className=Gd(f.className,u));void 0!==d&&(f.style=Ud(f.style,d));return f}(n,o);return!1===o.enabled?null:function(t,n,o,i){if(n){if("function"==typeof n)return n(o,i);const t=Bd(o,n.props);t.ref=o.ref;let r=n;return r?.$$typeof===tp&&(r=e.Children.toArray(n)[0]),/*#__PURE__*/e.cloneElement(r,t)}if(t&&"string"==typeof t)return function(t,n){return"button"===t?/*#__PURE__*/r("button",{type:"button",...n,key:n.key}):"img"===t?/*#__PURE__*/r("img",{alt:"",...n,key:n.key}):/*#__PURE__*/e.createElement(t,n)}(t,o);throw new Error(Xl(8))}(t,i,s,o.state??Hl)}var tp=Symbol.for("react.lazy");var np=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,children:s,...a}=t,c=Ql(),l=zu(),u=e.useRef(!1),d=e.useRef(!1),p=e.useRef(!1),h=c.useState("isEmpty"),f=c.useState("toasts"),m=c.useState("focused"),g=c.useState("expanded"),b=c.useState("prevFocusElement"),w=f[0]?.height,x=f.some(e=>"ending"===e.transitionStatus),S=f.filter(e=>"high"===e.priority);function k(){c.state.toasts.some(e=>"ending"===e.transitionStatus)||p.current||!d.current||(c.state.isWindowFocused&&c.resumeTimers(),c.set("hovering",!1),d.current=!1)}function _(){c.pauseTimers(),c.set("hovering",!0),d.current=!1}function E(e){"touch"===e.pointerType&&(p.current=!1,k())}function C(){u.current?u.current=!1:m||td(Ku(Eu(c.state.viewport)))&&(c.set("focused",!0),c.pauseTimers())}e.useEffect(()=>{const e=c.state.viewport;if(!e||h)return;const t=gu(e),n=Eu(e);return _u(Cu(t,"keydown",function(t){"F6"===t.key&&Xu(t)!==e&&(t.preventDefault(),c.set("prevFocusElement",Ku(n)),e?.focus({preventScroll:!0}),c.pauseTimers(),c.set("focused",!0))}),Cu(t,"blur",function(e){Xu(e)===t&&(c.set("isWindowFocused",!1),c.pauseTimers())},!0),Cu(t,"focus",function(n){if(n.relatedTarget)return;const r=Xu(n),o=Ku(Eu(e));r!==t&&Ju(e,r)&&td(o)||c.resumeTimers(),l.start(0,()=>c.set("isWindowFocused",!0))},!0),Cu(n,"pointerdown",c.handleDocumentPointerDown,!0))},[c,l,h]),e.useEffect(k,[x,c]);const I={tabIndex:-1,role:"region","aria-live":"polite","aria-atomic":!1,"aria-relevant":"additions text","aria-label":"Notifications",onMouseEnter:_,onMouseMove:_,onMouseLeave:function(){d.current=!0,k()},onFocus:C,onBlur:function(e){m&&!Ju(c.state.viewport,e.relatedTarget)&&(c.set("focused",!1),c.state.isWindowFocused&&c.resumeTimers())},onKeyDown:function(e){"Tab"===e.key&&e.shiftKey&&Xu(e.nativeEvent)===c.state.viewport&&(e.preventDefault(),c.restoreFocusToPrevElement())},onClick:C,onPointerDown:function(e){"touch"===e.pointerType&&(p.current=!0)},onPointerUp:E,onPointerCancel:E,style:{"--toast-frontmost-height":w?`${w}px`:void 0}},T={expanded:g},M=!h&&b&&/*#__PURE__*/y(Dd,{onFocus:function(e){u.current=!0;const t=e.relatedTarget===c.state.viewport?f.find(e=>"ending"!==e.transitionStatus&&!e.limited):void 0;t?t.ref?.current?.focus():c.restoreFocusToPrevElement()}}),O=ep("div",t,{ref:[n,c.setViewport],state:T,props:[I,a,{children:/*#__PURE__*/v(e.Fragment,{children:[M,s,M]})}]});/*#__PURE__*/
4
- return v(e.Fragment,{children:[M,O,!m&&S.length>0&&/*#__PURE__*/y("div",{style:Nd,children:S.map(e=>/*#__PURE__*/v("div",{role:"alert","aria-atomic":!0,children:[/*#__PURE__*/y("div",{children:e.title}),/*#__PURE__*/y("div",{children:e.description})]},e.id))})]})});function rp(e){return tu(19)?e:e?"true":void 0}var op=/*#__PURE__*/e.createContext(void 0);function ip(){const t=e.useContext(op);if(!t)throw new Error(Xl(66));return t}var sp=/*#__PURE__*/function(e){return e.startingStyle="data-starting-style",e.endingStyle="data-ending-style",e}({}),ap={"data-starting-style":""},cp={"data-ending-style":""},lp={transitionStatus:e=>"starting"===e?ap:"ending"===e?cp:null};function up(e){return null==e?e:"current"in e?e.current:e}function dp(t){const{enabled:n=!0,open:r,ref:o,onComplete:i}=t,s=uu(i),a=function(e,t=!1){const n=Ou();return uu((r,o=null)=>{n.cancel();const i=up(e);if(null==i)return;const s=i,a=()=>{m.flushSync(r)};if("function"!=typeof s.getAnimations||globalThis.BASE_UI_ANIMATIONS_DISABLED)r();else{if(t){const e="data-starting-style";if(!s.hasAttribute(e))return void n.request(c);const t=new MutationObserver(()=>{s.hasAttribute(e)||(t.disconnect(),c())});return t.observe(s,{attributes:!0,attributeFilter:[e]}),void o?.addEventListener("abort",()=>t.disconnect(),{once:!0})}n.request(c)}function c(){Promise.all(s.getAnimations().map(e=>e.finished)).then(()=>{o?.aborted||a()},()=>{o?.aborted||(s.getAnimations().some(e=>e.pending||"finished"!==e.playState)?c():a())})}})}(o,r);e.useEffect(()=>{if(!n)return;const e=new AbortController;return a(s,e.signal),()=>{e.abort()}},[n,r,s,a])}var pp={clipPath:"inset(50%)",position:"fixed",top:0,left:0};function hp(e,t,n){switch(e){case"up":return-n;case"down":return n;case"left":return-t;case"right":return t;default:return 0}}var fp={...lp,swipeDirection:e=>e?{"data-swipe-direction":e}:null},mp=/*#__PURE__*/e.forwardRef(function(t,n){const{toast:r,render:o,className:i,swipeDirection:s=["down","right"],style:a,...c}=t,l=void 0!==r.positionerProps?.anchor;let u=[];l||(u=Array.isArray(s)?s:[s]);const d=u.length>0,p=Ql(),[h,f]=e.useState(void 0),[g,v]=e.useState(!1),[b,w]=e.useState(!1),[x,S]=e.useState({x:0,y:0}),[k,_]=e.useState({x:0,y:0,scale:1}),[E,C]=e.useState(),[I,T]=e.useState(),[M,O]=e.useState(null),R=e.useRef(null),z=e.useRef(void 0),A=e.useRef({x:0,y:0}),P=e.useRef({x:0,y:0,scale:1}),N=e.useRef(void 0),D=e.useRef(0),$=e.useRef(!1),L=e.useRef({x:0,y:0}),F=e.useRef(!1),j=e.useRef({x:0,y:0}),U=e.useRef(null),W=e.useRef(null),B=p.useState("toastIndex",r.id),H=p.useState("toastVisibleIndex",r.id),Z=p.useState("toastOffsetY",r.id),q=p.useState("focused"),V=p.useState("expanded");dp({open:"ending"!==r.transitionStatus,ref:R,onComplete(){"ending"===r.transitionStatus&&p.removeToast(r.id)}});const Y=uu((e=!1)=>{const t=R.current;if(!t)return;const n=t.style.height;t.style.height="auto";const o=t.offsetHeight;function i(){p.updateToastInternal(r.id,{ref:R,height:o,transitionStatus:void 0})}t.style.height=n,e?m.flushSync(i):i()});function K(e){j.current=e,S(e)}Yl(()=>{const e=z.current;"starting"!==r.transitionStatus&&e===r.id||(void 0!==e&&(f(void 0),_({x:0,y:0,scale:1}),K({x:0,y:0})),z.current=r.id,Y())},[Y,r.id,r.transitionStatus]),Yl(()=>()=>{W.current?.abort()},[]);const J=uu(e=>{if(e.pointerId!==U.current)return;U.current=null,W.current?.abort(),W.current=null,v(!1),w(!1),O(null);const t=P.current;if("pointercancel"===e.type||$.current)return K({x:t.x,y:t.y}),void f(void 0);const n=j.current,o=n.x-t.x,i=n.y-t.y;let s;for(const r of u)if(hp(r,o,i)>40){s=r;break}s?(f(s),p.closeToast(r.id)):(K({x:t.x,y:t.y}),f(void 0))});e.useEffect(()=>{const e=R.current;if(d&&e)return Cu(e,"touchmove",function(t){null!==U.current&&Ju(e,Xu(t))&&t.preventDefault()},{passive:!1})},[d]);const X="high"===r.priority,G={role:X?"alertdialog":"dialog",tabIndex:0,"aria-modal":!1,"aria-labelledby":E,"aria-describedby":I,"aria-hidden":!(!X||q)||void 0,onPointerDown:d?function(e){if(0!==e.button)return;if("touch"===e.pointerType&&p.pauseTimers(),Xu(e.nativeEvent)?.closest('button,a,input,textarea,[role="button"],[data-base-ui-swipe-ignore],[data-swipe-ignore]'))return;$.current=!1,N.current=void 0,D.current=0,U.current=e.pointerId,A.current={x:e.clientX,y:e.clientY},L.current=A.current;const t=e.currentTarget,n=function(e){const t=gu(e).getComputedStyle(e).transform;let n=0,r=0,o=1;if(t&&"none"!==t){const e=t.match(/matrix(?:3d)?\(([^)]+)\)/);if(e){const t=e[1].split(", ").map(parseFloat);6===t.length?(n=t[4],r=t[5],o=Math.sqrt(t[0]*t[0]+t[1]*t[1])):16===t.length&&(n=t[12],r=t[13],o=t[0])}}return{x:n,y:r,scale:o}}(t);P.current=n,_(n),K({x:n.x,y:n.y}),p.set("hovering",!0),v(!0),w(!1),O(null),F.current=!0,W.current?.abort();const r=new AbortController;W.current=r;const o=Eu(t);o.addEventListener("pointerup",J,{signal:r.signal}),o.addEventListener("pointercancel",J,{signal:r.signal}),t.setPointerCapture?.(e.pointerId)}:void 0,onPointerMove:d?function(e){if(e.pointerId!==U.current)return;e.preventDefault(),F.current&&(A.current={x:e.clientX,y:e.clientY},F.current=!1);const{clientY:t,clientX:n,movementX:r,movementY:o}=e;(o<0&&t>L.current.y||o>0&&t<L.current.y)&&(L.current={x:L.current.x,y:t}),(r<0&&n>L.current.x||r>0&&n<L.current.x)&&(L.current={x:n,y:L.current.y});const i=n-A.current.x,s=t-A.current.y,a=t-L.current.y,c=n-L.current.x;let l,d=M;if(!b&&Math.sqrt(i*i+s*s)>=1){w(!0);const e=u.includes("left")||u.includes("right"),t=u.includes("up")||u.includes("down");e&&t&&(d=Math.abs(i)>Math.abs(s)?"horizontal":"vertical",O(d))}if(N.current){const e=N.current,t=hp(e,c,a);t>40?($.current=!1,f(e)):u.includes("left")&&u.includes("right")||u.includes("up")&&u.includes("down")||!(D.current-t>=10)||($.current=!0)}else"vertical"===d?s>0?l="down":s<0&&(l="up"):"horizontal"===d?i>0?l="right":i<0&&(l="left"):l=Math.abs(i)>=Math.abs(s)?i>0?"right":"left":s>0?"down":"up",l&&u.includes(l)&&(N.current=l,D.current=hp(l,i,s),f(l));const p=function(e,t){const n=e=>e>0?e**.5:-(Math.abs(e)**.5),r=e>0&&!u.includes("right")||e<0&&!u.includes("left"),o=t>0&&!u.includes("down")||t<0&&!u.includes("up");return{x:r?n(e):e,y:o?n(t):t}}(i,s);let h=P.current.x,m=P.current.y;const g=u.includes("left")||u.includes("right"),y=u.includes("up")||u.includes("down");"vertical"!==d&&g&&(h+=p.x),"horizontal"!==d&&y&&(m+=p.y),K({x:h,y:m})}:void 0,onPointerUp:d?J:void 0,onPointerCancel:d?J:void 0,onKeyDown:function(e){if("Escape"===e.key){if(!R.current||!Ju(R.current,Ku(Eu(R.current))))return;p.closeToast(r.id)}},inert:rp(r.limited),style:{...function(){const e=x.x-k.x,t=x.y-k.y;return{transition:g?"none":void 0,transform:g?`translateX(${x.x}px) translateY(${x.y}px) scale(${k.scale})`:void 0,"--toast-swipe-movement-x":`${e}px`,"--toast-swipe-movement-y":`${t}px`}}(),"--toast-index":"ending"===r.transitionStatus?B:H,"--toast-offset-y":`${Z}px`,"--toast-height":r.height?`${r.height}px`:void 0}},Q=e.useMemo(()=>({toast:r,setTitleId:C,setDescriptionId:T,recalculateHeight:Y,visibleIndex:H,expanded:V}),[r,C,T,Y,H,V]),ee={transitionStatus:r.transitionStatus,expanded:V,limited:r.limited||!1,type:r.type,swiping:g,swipeDirection:h},te=ep("div",t,{ref:[n,R],state:ee,stateAttributesMapping:fp,props:[G,c]});/*#__PURE__*/
5
- return y(op.Provider,{value:Q,children:te})}),gp=0;var yp=au.useId;function vp(t,n){if(void 0!==yp){const e=yp();return t??(n?`${n}-${e}`:e)}return function(t,n="mui"){const[r,o]=e.useState(t),i=t||r;return e.useEffect(()=>{null==r&&o(`${n}-${gp+=1}`)},[r,n]),i}(t,n)}function bp(e){return null!=e&&"boolean"!=typeof e&&""!==e&&(!Array.isArray(e)||e.some(bp))}function wp(t){/*#__PURE__*/
6
- return e.isValidElement(t)&&bp(t.props.children)}function xp(e,t,n){const{toast:r,setTitleId:o,setDescriptionId:i}=ip(),s="title"===n?o:i,a=t??("title"===n?r.title:r.description);return{id:vp(e),children:a,type:r.type,setId:s}}function Sp(e,t,n){const r=wp(e);return Yl(()=>{if(r)return n(t),()=>{n(e=>e===t?void 0:e)}},[r,t,n]),r?e:null}var kp=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,children:s,...a}=e,{id:c,children:l,type:u,setId:d}=xp(i,s,"description");return Sp(ep("p",e,{ref:t,state:{type:u},props:{...a,id:c,children:l}}),c,d)}),_p=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,children:s,...a}=e,{id:c,children:l,type:u,setId:d}=xp(i,s,"title");return Sp(ep("h2",e,{ref:t,state:{type:u},props:{...a,id:c,children:l}}),c,d)}),Ep=/*#__PURE__*/e.createContext(void 0);function Cp(t=!1){const n=e.useContext(Ep);if(void 0===n&&!t)throw new Error(Xl(16));return n}function Ip(e,t,{detail:n=0}={}){e.dispatchEvent(new(gu(e).PointerEvent)("click",{bubbles:!0,cancelable:!0,composed:!0,detail:n,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function Tp(t={}){const{disabled:n=!1,focusableWhenDisabled:r,tabIndex:o=0,native:i=!0,composite:s}=t,a=e.useRef(null),c=Cp(!0),l=s??void 0!==c,{props:u}=function(t){const{focusableWhenDisabled:n,disabled:r,composite:o=!1,tabIndex:i=0,isNativeButton:s}=t,a=o&&!1!==n,c=o&&!1===n;return{props:e.useMemo(()=>{const e={onKeyDown(e){r&&n&&"Tab"!==e.key&&e.preventDefault()}};return o||(e.tabIndex=i,!s&&r&&(e.tabIndex=n?i:-1)),(s&&(n||a)||!s&&r)&&(e["aria-disabled"]=r),!s||n&&!c||(e.disabled=r),e},[o,r,n,a,c,s,i])}}({focusableWhenDisabled:r,disabled:n,composite:l,tabIndex:o,isNativeButton:i}),d=e.useCallback(()=>{const e=a.current;Mp(e)&&l&&n&&void 0===u.disabled&&e.disabled&&(e.disabled=!1)},[n,u.disabled,l]);return Yl(d,[d]),{getButtonProps:e.useCallback((e={})=>{const{onClick:t,onMouseDown:r,onKeyUp:o,onKeyDown:s,onPointerDown:a,...c}=e;return Bd({onClick(e){n?e.preventDefault():t?.(e)},onMouseDown(e){n||r?.(e)},onKeyDown(e){if(n)return;if(Xd(e),s?.(e),e.baseUIHandlerPrevented)return;const t=e.target===e.currentTarget,r=e.currentTarget,o=Mp(r),a=!i&&(bu(c=r)&&"A"===c.tagName&&Boolean(c.href));var c;const u=t&&(i?o:!a),d="Enter"===e.key,p=" "===e.key,h=r.getAttribute("role"),f=h?.startsWith("menuitem")||"option"===h||"gridcell"===h;if(t&&l&&p){if(e.defaultPrevented&&f)return;return e.preventDefault(),void(i&&!o||(e.preventBaseUIHandler(),Ip(r,e)))}u&&!i&&(p||d)?e.defaultPrevented||(e.preventDefault(),d&&(e.preventBaseUIHandler(),Ip(r,e))):t&&a&&p&&e.preventDefault()},onKeyUp(e){n||(Xd(e),o?.(e),e.target===e.currentTarget&&i&&l&&Mp(e.currentTarget)&&" "===e.key?e.preventDefault():e.baseUIHandlerPrevented||e.target!==e.currentTarget||i||l||e.defaultPrevented||" "!==e.key||(e.preventBaseUIHandler(),Ip(e.currentTarget,e)))},onPointerDown(e){n?e.preventDefault():a?.(e)}},i?{type:"button"}:{role:"button"},u,c)},[n,u,l,i]),buttonRef:uu(e=>{a.current=e,d()})}}function Mp(e){return bu(e)&&"BUTTON"===e.tagName}var Op=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,disabled:s,nativeButton:a=!0,...c}=t,l=Ql(),{toast:u,expanded:d}=ip(),[p,h]=e.useState(!1),{getButtonProps:f,buttonRef:m}=Tp({disabled:s,native:a});return ep("button",t,{ref:[n,m],state:{type:u.type},props:[{"aria-hidden":!d&&!p,onClick(){l.closeToast(u.id)},onFocus(){h(!0)},onBlur(){h(!1)}},c,f]})}),Rp=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,disabled:i,nativeButton:s=!0,...a}=e,{toast:c}=ip(),l=c.actionProps?.children??a.children,{getButtonProps:u,buttonRef:d}=Tp({disabled:i,native:s}),p=ep("button",e,{ref:[t,d],state:{type:c.type},props:[a,c.actionProps,u,{children:l}]});return wp(p)?p:null}),zp="none",Ap="missing",Pp="initial";function Np(e,t,n,r){let o=!1,i=!1;const s=r??Hl;return{reason:e,event:t??new Event("base-ui"),cancel(){o=!0},allowPropagation(){i=!0},get isCanceled(){return o},get isPropagationAllowed(){return i},trigger:n,...s}}function Dp(e){return`data-base-ui-${e}`}var $p=/*#__PURE__*/e.createContext(null),Lp=()=>e.useContext($p),Fp=Dp("portal");function jp(t={}){const{ref:n,container:r,componentProps:o=Hl,elementProps:i}=t,s=vp(),a=Lp()?.portalNode,[c,l]=e.useState(null),[u,d]=e.useState(null),p=uu(e=>{null!==e&&d(e)}),h=e.useRef(null);Yl(()=>{if(null===r)return void(h.current&&(h.current=null,d(null),l(null)));const e=(r&&(yu(r)?r:r.current))??a??document.body;null!=e?h.current!==e&&(h.current=e,d(null),l(e)):h.current&&(h.current=null,d(null),l(null))},[r,a]);const f=ep("div",o,{ref:[n,p],props:[{id:s,[Fp]:""},i]}),g=c&&f?/*#__PURE__*/m.createPortal(f,c):null;return{node:u,nodeId:/*#__PURE__*/e.isValidElement(f)?f.props.id:void 0,subtree:g}}var Up=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,children:s,container:a,...c}=t,{node:l,nodeId:u,subtree:d}=jp({container:a,ref:n,componentProps:t,elementProps:c}),p=e.useRef(null),h=e.useRef(null),f=e.useRef(null),g=e.useRef(null),[b,w]=e.useState(null),x=e.useRef(!1),S=b?.modal,k=b?.open,_=!!b&&!b.modal&&b.open&&!!l;e.useEffect(()=>{if(l&&!S)return _u(Cu(l,"focusin",e,!0),Cu(l,"focusout",e,!0));function e(e){l&&e.relatedTarget&&Cd(e)&&("focusin"===e.type?x.current&&(Id(l),x.current=!1):(!function(e){Sd(e).forEach(e=>{e.dataset.tabindex=e.getAttribute("tabindex")||"",e.setAttribute("tabindex","-1")})}(l),x.current=!0))}},[l,S]),Yl(()=>{l&&!0===k&&x.current&&(Id(l),x.current=!1)},[k,l]);const E=e.useMemo(()=>({beforeOutsideRef:p,afterOutsideRef:h,beforeInsideRef:f,afterInsideRef:g,portalNode:l,setFocusManagerState:w}),[l]);/*#__PURE__*/
7
- return v(e.Fragment,{children:[d,/*#__PURE__*/v($p.Provider,{value:E,children:[_&&l&&/*#__PURE__*/y(Dd,{"data-type":"outside",ref:p,onFocus:e=>{if(Cd(e,l))f.current?.focus();else{const e=b?b.domReference:null;Ed(e)?.focus()}}}),_&&l&&/*#__PURE__*/y("span",{"aria-owns":u,style:pp}),l&&/*#__PURE__*/m.createPortal(s,l),_&&l&&/*#__PURE__*/y(Dd,{"data-type":"outside",ref:h,onFocus:e=>{if(Cd(e,l))g.current?.focus();else{const t=b?b.domReference:null;_d(t)?.focus(),b?.closeOnFocusOut&&b?.onOpenChange(!1,Np("focus-out",e.nativeEvent))}}})]})]})}),Wp=/*#__PURE__*/e.forwardRef(function(t,n){const{children:r,container:o,className:i,render:s,style:a,...c}=t,{node:l,subtree:u}=jp({container:o,ref:n,componentProps:t,elementProps:c});return u||l?/*#__PURE__*/v(e.Fragment,{children:[u,l&&/*#__PURE__*/m.createPortal(r,l)]}):null}),Bp=/*#__PURE__*/e.forwardRef(function(e,t){/*#__PURE__*/
8
- return y(Wp,{ref:t,...e})});function Hp(e){const t=Vl(Zp,e).current;return t.next=e,Yl(t.effect),t}function Zp(e){const t={current:e,next:e,effect:()=>{t.current=t.next}};return t}var qp=0;function Vp(e,t={}){const{preventScroll:n=!1,sync:r=!1,shouldFocus:o}=t;function i(){o&&!o()||e?.focus({preventScroll:n})}if(cancelAnimationFrame(qp),r)return i(),Wl;const s=requestAnimationFrame(i);return qp=s,()=>{qp===s&&(cancelAnimationFrame(s),qp=0)}}var Yp={inert:/* @__PURE__ */new WeakMap,"aria-hidden":/* @__PURE__ */new WeakMap},Kp="data-base-ui-inert",Jp={inert:/* @__PURE__ */new WeakSet,"aria-hidden":/* @__PURE__ */new WeakSet},Xp=/* @__PURE__ */new WeakMap,Gp=0;function Qp(e){return e?wu(e)?e.host:Qp(e.parentNode):null}var eh=(e,t)=>t.map(t=>{if(e.contains(t))return t;const n=Qp(t);return e.contains(n)?n:null}).filter(e=>null!=e),th=e=>{const t=/* @__PURE__ */new Set;return e.forEach(e=>{let n=e;for(;n&&!t.has(n);)t.add(n),n=n.parentNode}),t},nh=(e,t,n)=>{const r=[],o=e=>{e&&!n.has(e)&&Array.from(e.children).forEach(e=>{"script"!==mu(e)&&(t.has(e)?o(e):r.push(e))})};return o(e),r};function rh(e,t,n,r,{mark:o=!0}){let i=null;r?i="inert":n&&(i="aria-hidden");let s=null,a=null;const c=eh(t,e),l=o?nh(t,th(c),new Set(c)):[],u=[],d=[];if(i){const e=Yp[i],n=function(e){return Jp[e]}(i);a=n,s=e;const r=eh(t,Array.from(t.querySelectorAll("[aria-live]"))),o=c.concat(r);nh(t,th(o),new Set(o)).forEach(t=>{const r=t.getAttribute(i),o=null!==r&&"false"!==r,s=(e.get(t)||0)+1;e.set(t,s),u.push(t),1===s&&o&&n.add(t),o||t.setAttribute(i,"inert"===i?"":"true")})}return o&&l.forEach(e=>{const t=(Xp.get(e)||0)+1;Xp.set(e,t),d.push(e),1===t&&e.setAttribute(Kp,"")}),Gp+=1,()=>{s&&u.forEach(e=>{const t=(s.get(e)||0)-1;s.set(e,t),t||(!a?.has(e)&&i&&e.removeAttribute(i),a?.delete(e))}),o&&d.forEach(e=>{const t=(Xp.get(e)||0)-1;Xp.set(e,t),t||e.removeAttribute(Kp)}),(Gp-=1)||(Yp.inert=/* @__PURE__ */new WeakMap,Yp["aria-hidden"]=/* @__PURE__ */new WeakMap,Jp.inert=/* @__PURE__ */new WeakSet,Jp["aria-hidden"]=/* @__PURE__ */new WeakSet,Xp=/* @__PURE__ */new WeakMap)}}function oh(e,t={}){const{ariaHidden:n=!1,inert:r=!1,mark:o=!0}=t;return rh(e,Eu(e[0]).body,n,r,{mark:o})}function ih(){const e=/* @__PURE__ */new Map;return{emit(t,n){e.get(t)?.forEach(e=>e(n))},on(t,n){e.has(t)||e.set(t,/* @__PURE__ */new Set),e.get(t).add(n)},off(t,n){e.get(t)?.delete(n)}}}var sh=/*#__PURE__*/e.createContext(null),ah=/*#__PURE__*/e.createContext(null),ch=t=>{const n=e.useContext(ah);return t??n};var lh=[];function uh(){lh=lh.filter(e=>e.deref()?.isConnected)}function dh(e){uh(),e&&"body"!==mu(e)&&(lh.push(new WeakRef(e)),lh.length>20&&(lh=lh.slice(-20)))}function ph(){return uh(),lh[lh.length-1]?.deref()}function hh(e){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex"))return;if(!e.getAttribute("role")?.includes("dialog"))return;const t=xd(e).filter(e=>{const t=e.getAttribute("data-tabindex")||"";return wd(e)||e.hasAttribute("data-tabindex")&&!t.startsWith("-")}),n=e.getAttribute("tabindex");0===t.length?"0"!==n&&(e.setAttribute("tabindex","0"),e.setAttribute("data-tabindex","0")):("-1"!==n||e.hasAttribute("data-tabindex")&&"-1"!==e.getAttribute("data-tabindex"))&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function fh(t){const{context:n,children:r,disabled:o=!1,initialFocus:i=!0,returnFocus:s=!0,restoreFocus:a=!1,modal:c=!0,closeOnFocusOut:l=!0,openInteractionType:u="",nextFocusableElement:d,previousFocusableElement:p,beforeContentFocusGuardRef:h,externalTree:f,getInsideElements:m}=t,g="rootStore"in n?n.rootStore:n,b=g.useState("open"),w=g.useState("domReferenceElement"),x=g.useState("floatingElement"),{events:S,dataRef:k}=g.context,_=uu(()=>k.current.floatingContext?.nodeId),E=!1===i,C=ed(w)&&E,I=Hp(i),T=Hp(s),M=Hp(u),O=Hp(b),R=ch(f),z=Lp(),A=e.useRef(!1),P=e.useRef(!1),N=e.useRef(!1),D=e.useRef(null),$=e.useRef(""),L=e.useRef(""),F=e.useRef(null),j=e.useRef(null),U=$d(F,h,z?.beforeInsideRef),W=$d(j,z?.afterInsideRef),B=zu(),H=zu(),Z=Ou(),q=null!=z,V=nd(x),Y=uu((e=V)=>e?Sd(e):[]),K=uu(()=>m?.().filter(e=>null!=e)??[]);e.useEffect(()=>{if(o||!c)return;return Cu(Eu(V),"keydown",function(e){"Tab"===e.key&&Ju(V,Ku(Eu(V)))&&0===Y().length&&!C&&function(e){e.preventDefault(),e.stopPropagation()}(e)})},[o,V,c,C,Y]),e.useEffect(()=>{if(o||!b)return;const e=Eu(V);function t(){N.current=!1}return _u(Cu(e,"pointerdown",function(e){const t=Xu(e),n=K(),r=Ju(x,t)||Ju(w,t)||Ju(z?.portalNode,t)||n.some(e=>e===t||Ju(e,t));N.current=!r,L.current=e.pointerType||"keyboard",t?.closest("[data-base-ui-click-trigger]")&&(P.current=!0,H.start(0,()=>{P.current=!1}))},!0),Cu(e,"pointerup",t,!0),Cu(e,"pointercancel",t,!0),Cu(e,"keydown",function(){L.current="keyboard"},!0),t)},[o,x,w,V,b,z,H,K]),e.useEffect(()=>{if(o||!l)return;const e=Eu(V);function t(t){const n=t.relatedTarget,r=t.currentTarget,o=Xu(t);c&&null==n&&null!=o&&Ju(x,o)&&dh(o),queueMicrotask(()=>{const i=_(),s=g.context.triggerElements,l=K(),u=n?.hasAttribute(Dp("focus-guard"))&&[F.current,j.current,z?.beforeInsideRef.current,z?.afterInsideRef.current,z?.beforeOutsideRef.current,z?.afterOutsideRef.current,up(p),up(d)].includes(n),h=!(Ju(w,n)||Ju(x,n)||Ju(n,x)||Ju(z?.portalNode,n)||l.some(e=>e===n||Ju(e,n))||s.hasMatchingElement(e=>Ju(e,n))||u||R&&(rd(R.nodesRef.current,i).find(e=>Ju(e.context?.elements.floating,n)||Ju(e.context?.elements.domReference,n))||od(R.nodesRef.current,i).find(e=>[e.context?.elements.floating,nd(e.context?.elements.floating)].includes(n)||e.context?.elements.domReference===n)));if(r===w&&V&&hh(V),a&&r!==w&&!cd(o)&&Ku(e)===e.body){if(bu(V)&&(V.focus(),"popup"===a))return void Z.request(()=>{V.focus()});const e=Y(),t=D.current,n=(t&&e.includes(t)?t:null)||e[e.length-1]||V;bu(n)&&n.focus()}k.current.insideReactTree?k.current.insideReactTree=!1:!C&&c||!n||!h||P.current||!C&&n===ph()||(A.current=!0,g.setOpen(!1,Np("focus-out",t)))})}const n=bu(w)?w:null;return x||n?_u(n&&Cu(n,"focusout",t),n&&Cu(n,"pointerdown",function(){P.current=!0,H.start(0,()=>{P.current=!1})}),x&&Cu(x,"focusin",function(e){const t=Xu(e);wd(t)&&(D.current=t)}),x&&Cu(x,"focusout",t),x&&z&&Cu(x,"focusout",function(){N.current||(k.current.insideReactTree=!0,B.start(0,()=>{k.current.insideReactTree=!1}))},!0)):void 0},[o,w,x,V,c,R,z,g,l,a,Y,C,_,k,B,H,Z,d,p,K]),e.useEffect(()=>{if(o||!x||!b)return;const e=Array.from(z?.portalNode?.querySelectorAll(`[${Dp("portal")}]`)||[]),t=(R?od(R.nodesRef.current,_()):[]).find(e=>ed(e.context?.elements.domReference||null))?.context?.elements.domReference,n=oh([x,...e,F.current,j.current,z?.beforeOutsideRef.current,z?.afterOutsideRef.current,...K(),t,up(p),up(d),C?w:null].filter(e=>null!=e),{ariaHidden:c||C,mark:!1}),r=oh([x,...e].filter(e=>null!=e));return()=>{r(),n()}},[b,o,w,x,c,z,C,R,_,d,p,K]),Yl(()=>{if(!b||o||!bu(V))return;$.current="",L.current="";const e=Eu(V),t=Ku(e);queueMicrotask(()=>{const n=I.current,r="function"==typeof n?n(M.current||""):n;if(void 0===r||!1===r)return;if(Ju(V,t))return;let o=null;const i=()=>(null==o&&(o=Y(V)),o[0]||V);let s;s=!0===r||null===r?i():up(r),s=s||i();const a=Ju(V,Ku(e));Vp(s,{preventScroll:s===V,shouldFocus(){if(!O.current)return!1;if(a)return!0;const t=Ku(e);return!(t!==s&&Ju(V,t))}})})},[o,b,V,Y,I,M,O]),Yl(()=>{if(o||!V)return;const e=Eu(V),t=Ku(e),n=null==M.current;function r(e){var t;if(e.open||($.current=function(e,t){const n=gu(Xu(e));return e instanceof n.KeyboardEvent?"keyboard":e instanceof n.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof n.MouseEvent?t||(0===e.detail?"keyboard":"mouse"):""}(e.nativeEvent,L.current)),"trigger-hover"===e.reason&&"mouseleave"===e.nativeEvent.type&&(A.current=!0),"outside-press"===e.reason)if(e.nested)A.current=!1;else if(""===(t=e.nativeEvent).pointerType&&t.isTrusted||(Wu&&t.pointerType?"click"===t.type&&1===t.buttons:0===t.detail&&!t.pointerType)||function(e){return!Vu&&(!Wu&&0===e.width&&0===e.height||Wu&&1===e.width&&1===e.height&&0===e.pressure&&0===e.detail&&"mouse"===e.pointerType||e.width<1&&e.height<1&&0===e.pressure&&0===e.detail&&"touch"===e.pointerType)}(e.nativeEvent))A.current=!1;else{let e=!1;Eu(V).createElement("div").focus({get preventScroll(){return e=!0,!1}}),A.current=!e}}return dh(t),S.on("openchange",r),()=>{S.off("openchange",r);const o=Ku(e),i=K(),s=Ju(x,o)||i.some(e=>e===o||Ju(e,o))||R&&rd(R.nodesRef.current,_(),!1).some(e=>Ju(e.context?.elements.floating,o)),a=T.current,c=$.current,l=function(e){const r=T.current;let o="function"==typeof r?r(e):r;if(void 0===o||!1===o)return null;null===o&&(o=!0);const i=w?.isConnected?w:null,s=t?.isConnected&&"body"!==mu(t)?t:null;let a=n?s||i:i||s;return a||(a=ph()||null),"boolean"==typeof o?a:up(o)||a||null}(c);queueMicrotask(()=>{const t=(n=l)?wd(n)?n:Sd(n)[0]||n:null;var n;const r="boolean"!=typeof a;if(a&&!A.current&&bu(t)&&(r||t===o||o===e.body||s)){const e={preventScroll:!0};"keyboard"===c&&(e.focusVisible=!0),t.focus(e)}A.current=!1})}},[o,x,V,T,M,S,R,w,_,K]),Yl(()=>{if(!Zu||b||!x)return;const e=Ku(Eu(x));bu(e)&&Qu(e)&&Ju(x,e)&&e.blur()},[b,x]),Yl(()=>{if(!o&&z)return z.setFocusManagerState({modal:c,closeOnFocusOut:l,open:b,onOpenChange:g.setOpen,domReference:w}),()=>{z.setFocusManagerState(null)}},[o,z,c,b,g,l,w]),Yl(()=>{if(!o&&V)return hh(V),()=>{queueMicrotask(uh)}},[o,V]);const J=!o&&(!c||!C)&&(q||c);/*#__PURE__*/
9
- return v(e.Fragment,{children:[J&&/*#__PURE__*/y(Dd,{"data-type":"inside",ref:U,onFocus:e=>{if(c){const e=Y();Vp(e[e.length-1])}else z?.portalNode&&(A.current=!1,Cd(e,z.portalNode)?_d(w)?.focus():up(p??z.beforeOutsideRef)?.focus())}}),r,J&&/*#__PURE__*/y(Dd,{"data-type":"inside",ref:W,onFocus:e=>{c?Vp(Y()[0]):z?.portalNode&&(l&&(A.current=!0),Cd(e,z.portalNode)?Ed(w)?.focus():up(d??z.afterOutsideRef)?.focus())}})]})}function mh(){return!1}function gh(t,n={}){const{enabled:r=!0,escapeKey:o=!0,outsidePress:i=!0,outsidePressEvent:s="sloppy",referencePress:a=mh,bubbles:c,externalTree:l}=n,u="rootStore"in t?t.rootStore:t,d=u.useState("open"),p=u.useState("floatingElement"),{dataRef:h}=u.context,f=ch(l),m=uu("function"==typeof i?i:()=>!1),g="function"==typeof i?m:i,y=!1!==g,v=uu(()=>s),{escapeKey:b,outsidePress:w}={escapeKey:"boolean"==typeof(x=c)?x:x?.escapeKey??!1,outsidePress:"boolean"==typeof x?x:x?.outsidePress??!0};var x;const S=e.useRef(!1),k=e.useRef(!1),_=e.useRef(!1),E=e.useRef(!1),C=e.useRef(""),I=e.useRef(null),T=zu(),M=zu(),O=uu(()=>{M.clear(),h.current.insideReactTree=!1}),R=uu(e=>{const t=h.current.floatingContext?.nodeId;return(f?rd(f.nodesRef.current,t):[]).some(t=>t.context?.open&&!t.context.dataRef.current[e])}),z=uu(e=>Gu(e,u.select("floatingElement"))||Gu(e,u.select("domReferenceElement"))),A=uu(e=>{a()&&u.setOpen(!1,Np("trigger-press",e.nativeEvent))}),P=uu(e=>{if(!d||!r||!o||"Escape"!==e.key)return;if(E.current)return;if(!b&&R("__escapeKeyBubbles"))return;const t=Np("escape-key",function(e){return"nativeEvent"in e}(e)?e.nativeEvent:e);u.setOpen(!1,t),t.isCanceled||e.preventDefault(),b||t.isPropagationAllowed||e.stopPropagation()}),N=uu(()=>{h.current.insideReactTree=!0,M.start(0,O)}),D=uu(e=>{if(!d||!r||0!==e.button)return;const t=Xu(e.nativeEvent);Ju(u.select("floatingElement"),t)&&(S.current||(S.current=!0,k.current=!1))}),$=uu(e=>{d&&r&&(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&S.current&&(k.current=!0)});e.useEffect(()=>{if(!d||!r)return O;h.current.__escapeKeyBubbles=b,h.current.__outsidePressBubbles=w;const e=new Ru,t=new Ru;function n(){_.current=!0,t.start(0,()=>{_.current=!1})}function i(){S.current=!1,k.current=!1}function s(){const e=C.current,t="pen"!==e&&e?e:"mouse",n=v(),r="function"==typeof n?n():n;return"string"==typeof r?r:r[t]}function a(e){const t=h.current.floatingContext?.nodeId,n=f&&rd(f.nodesRef.current,t).some(t=>Gu(e,t.context?.elements.floating));return z(e)||n}function c(e){if(function(e){const t=s();return"intentional"===t&&"click"!==e.type||"sloppy"===t&&"click"===e.type}(e))return"click"===e.type||z(e)||(t.clear(),_.current=!1),void O();if(h.current.insideReactTree)return void O();const n=Xu(e),r=`[${Dp("inert")}]`,o=vu(n)?n.getRootNode():null,i=Array.from((wu(o)?o:Eu(u.select("floatingElement"))).querySelectorAll(r)),c=u.context.triggerElements;if(n&&(c.hasElement(n)||c.hasMatchingElement(e=>Ju(e,n))))return;let l=vu(n)?n:null;for(;l&&!xu(l);){const e=ku(l);if(xu(e)||!vu(e))break;l=e}if(!i.length||!vu(n)||n.matches("html,body")||Ju(n,u.select("floatingElement"))||!i.every(e=>!Ju(l,e))){if(bu(n)&&!("touches"in e)){const t=xu(n),r=Su(n),o=/auto|scroll/,i=t||o.test(r.overflowX),s=t||o.test(r.overflowY),a=i&&n.clientWidth>0&&n.scrollWidth>n.clientWidth,c=s&&n.clientHeight>0&&n.scrollHeight>n.clientHeight,l="rtl"===r.direction,u=c&&(l?e.offsetX<=n.offsetWidth-n.clientWidth:e.offsetX>n.clientWidth),d=a&&e.offsetY>n.clientHeight;if(u||d)return}if(!a(e))return"intentional"===s()&&_.current?(t.clear(),void(_.current=!1)):void(("function"!=typeof g||g(e))&&(R("__outsidePressBubbles")||(u.setOpen(!1,Np("outside-press",e)),O())))}}function l(e){if("sloppy"!==s()||!u.select("open")||!r||z(e))return;const t=e.touches[0];t&&(I.current={startTime:Date.now(),startX:t.clientX,startY:t.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},T.start(1e3,()=>{I.current&&(I.current.dismissOnTouchEnd=!1,I.current.dismissOnMouseDown=!1)}))}function m(e,t){const n=Xu(e);if(!n)return;const r=Cu(n,e.type,()=>{t(e),r()})}function x(e){T.clear(),"pointerdown"===e.type&&(C.current=e.pointerType),"mousedown"===e.type&&I.current&&!I.current.dismissOnMouseDown||m(e,e=>{"pointerdown"===e.type?function(e){"sloppy"===s()&&"touch"!==e.pointerType&&u.select("open")&&r&&!z(e)&&c(e)}(e):c(e)})}function M(e){if(!S.current)return;const r=k.current;i(),"intentional"===s()&&("pointercancel"!==e.type?a(e)||(r?n():("function"!=typeof g||g(e))&&(t.clear(),_.current=!0,O())):r&&n())}function A(e){if("sloppy"!==s()||!I.current||z(e))return;const t=e.touches[0];if(!t)return;const n=Math.abs(t.clientX-I.current.startX),r=Math.abs(t.clientY-I.current.startY),o=Math.sqrt(n*n+r*r);o>5&&(I.current.dismissOnTouchEnd=!0),o>10&&(c(e),T.clear(),I.current=null)}function N(e){"sloppy"===s()&&I.current&&!z(e)&&(I.current.dismissOnTouchEnd&&c(e),T.clear(),I.current=null)}const D=Eu(p),$=_u(o&&_u(Cu(D,"keydown",P),Cu(D,"compositionstart",function(){e.clear(),E.current=!0}),Cu(D,"compositionend",function(){e.start(Zu?5:0,()=>{E.current=!1})})),y&&_u(Cu(D,"click",x,!0),Cu(D,"pointerdown",x,!0),Cu(D,"pointerup",M,!0),Cu(D,"pointercancel",M,!0),Cu(D,"mousedown",x,!0),Cu(D,"mouseup",M,!0),Cu(D,"touchstart",function(e){C.current="touch",m(e,l)},!0),Cu(D,"touchmove",function(e){m(e,A)},!0),Cu(D,"touchend",function(e){m(e,N)},!0)));return()=>{$(),e.clear(),t.clear(),i(),_.current=!1,O()}},[h,p,o,y,g,d,r,b,w,P,O,v,R,z,f,u,T]);const L=e.useMemo(()=>({onKeyDown:P,onPointerDown:A,onClick:A}),[P,A]),F=e.useMemo(()=>({onKeyDown:P,onPointerDown:$,onMouseDown:$,onClickCapture:N,onMouseDownCapture(e){N(),D(e)},onPointerDownCapture(e){N(),D(e)},onMouseUpCapture:N,onTouchEndCapture:N,onTouchMoveCapture:N}),[P,N,D,$]);return e.useMemo(()=>r?{reference:L,floating:F,trigger:L}:{},[r,L,F])}var yh={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId},vh=class extends hu{constructor(e){const{syncOnly:t,nested:n,onOpenChange:r,triggerElements:o,...i}=e;super({...i,positionReference:i.referenceElement,domReferenceElement:i.referenceElement},{onOpenChange:r,dataRef:{current:{}},events:ih(),nested:n,triggerElements:o},yh),this.syncOnly=t}syncOpenEvent=(e,t)=>{(!e||!this.state.open||null!=t&&function(e){const t=e.type;return"click"===t||"mousedown"===t||"keydown"===t||"keyup"===t}(t))&&(this.context.dataRef.current.openEvent=e?t:void 0)};dispatchOpenChange=(e,t)=>{this.syncOpenEvent(e,t.event);const n={open:e,reason:t.reason,nativeEvent:t.event,nested:this.context.nested,triggerElement:t.trigger};this.context.events.emit("openchange",n)};setOpen=(e,t)=>{this.syncOnly||this.dispatchOpenChange(e,t),this.context.onOpenChange?.(e,t)}};function bh(t,n=!1,r=!1){const[o,i]=e.useState(t&&n?"idle":void 0),[s,a]=e.useState(t);return t&&!s&&(a(!0),i("starting")),t||!s||"ending"===o||r||i("ending"),t||s||"ending"!==o||i(void 0),Yl(()=>{if(!t&&s&&"ending"!==o&&r){const e=Mu.request(()=>{i("ending")});return()=>{Mu.cancel(e)}}},[t,s,o,r]),Yl(()=>{if(!t||n)return;const e=Mu.request(()=>{i(void 0)});return()=>{Mu.cancel(e)}},[n,t]),Yl(()=>{if(!t||!n)return;t&&s&&"idle"!==o&&i("starting");const e=Mu.request(()=>{i("idle")});return()=>{Mu.cancel(e)}},[n,t,s,o]),{mounted:s,setMounted:a,transitionStatus:o}}var wh={tabIndex:-1,[Yu]:""};function xh(t,n=!1){const r=vp(),o=null!=(e.useContext(sh)?.id||null),i=Vl(()=>t(r,o)).current;return function(t){const{popupStore:n,treatPopupAsFloatingElement:r=!1,floatingRootContext:o,floatingId:i,nested:s,onOpenChange:a}=t,c=n.useState("open"),l=n.useState("activeTriggerElement"),u=n.useState(r?"popupElement":"positionerElement"),d=n.context.triggerElements,p=a,h=e.useRef(null);void 0===o&&null===h.current&&(h.current=new vh({open:c,transitionStatus:void 0,referenceElement:l,floatingElement:u,triggerElements:d,onOpenChange:p,floatingId:i,syncOnly:!0,nested:s}));const f=o??h.current;n.useSyncedValue("floatingId",i),Yl(()=>{const e={open:c,floatingId:i,referenceElement:l,floatingElement:u};vu(l)&&(e.domReferenceElement=l),f.state.positionReference===f.state.referenceElement&&(e.positionReference=l),f.update(e)},[c,i,l,u,f]),f.context.onOpenChange=p,f.context.nested=s}({popupStore:i,treatPopupAsFloatingElement:n,floatingRootContext:i.state.floatingRootContext,floatingId:r,nested:o,onOpenChange:i.setOpen}),i}function Sh({handle:e,store:t}){return Yl(()=>e.attachStore(t),[e,t]),null}var kh=class{constructor(){this.idMap=/* @__PURE__ */new Map}add(e,t){this.idMap.set(e,t)}delete(e){this.idMap.delete(e)}hasElement(e){for(const t of this.idMap.values())if(t===e)return!0;return!1}hasMatchingElement(e){for(const t of this.idMap.values())if(e(t))return!0;return!1}getById(e){return this.idMap.get(e)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}};function _h(){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new vh({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new kh,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0}),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:Hl,inactiveTriggerProps:Hl,popupProps:Hl}}var Eh=e=>e.triggerIdProp??e.activeTriggerId,Ch=e=>e.openProp??e.open,Ih=e=>(e.popupElement?.id??e.floatingId)||void 0;function Th(e,t){return void 0!==t&&Ch(e)&&Eh(e)===t}var Mh={open:Ch,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:Eh,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:Ih,isTriggerActive:(e,t)=>void 0!==t&&Eh(e)===t,isOpenedByTrigger:(e,t)=>Th(e,t),isMountedByTrigger:(e,t)=>void 0!==t&&Eh(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>function(e,t){return!!Th(e,t)||void 0!==t&&Ch(e)&&null==Eh(e)&&1===e.triggerCount}(e,t)?Ih(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement},Oh=/*#__PURE__*/e.createContext(void 0);!function(e){e.open="data-open",e.closed="data-closed",e[e.startingStyle=sp.startingStyle]="startingStyle",e[e.endingStyle=sp.endingStyle]="endingStyle",e.anchorHidden="data-anchor-hidden",e.side="data-side",e.align="data-align"}({});var Rh={"data-open":""},zh={"data-closed":""},Ah={"data-anchor-hidden":""},Ph={open:e=>e?Rh:zh,anchorHidden:e=>e?Ah:null},Nh={...Ph,...lp};function Dh(){const t=Ql(),n=t.useState("toasts");return e.useMemo(()=>({toasts:n,add:t.addToast,close:t.closeToast,update:t.updateToast,promise:t.promiseToast}),[n,t])}var $h="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%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",Lh={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)"},Fh={none:"0",sm:"calc(var(--radius) - 4px)",md:"calc(var(--radius) - 2px)",lg:"var(--radius)",xl:"calc(var(--radius) + 4px)",theme:"var(--radius)",pill:"9999px",circle:"9999px"},jh={default:"var(--foreground)",muted:"var(--foreground-muted)",faint:"var(--foreground-faint)",primary:"var(--primary)",inherit:"inherit"},Uh={tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625"},Wh={info:{background:"#f0f9ff",border:"1px solid #bae6fd",titleColor:"#0c4a6e",bodyColor:"#0369a1",closeColor:"#7dd3fc",actionBackground:"#e0f2fe"},error:{background:"#fef2f2",border:"1px solid #fecaca",titleColor:"#b91c1c",bodyColor:"#b91c1c",closeColor:"#f87171",actionBackground:"#fee2e2"},neutral:{background:"rgba(255, 255, 255, 0.95)",border:"1px solid rgba(255, 255, 255, 0.2)",titleColor:"#1f2937",bodyColor:"#1f2937",closeColor:"#6b7280",actionBackground:"transparent"}};function Bh(e){if(e&&"none"!==e)return{boxShadow:Lh[e]}}var Hh=2147483001,Zh=2147483002,qh=2147483003,Vh=2147483004,Yh={none:"0","2xs":"2px",xs:"4px",sm:"6px",md:"8px",lg:"12px",xl:"16px","2xl":"24px"},Kh={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch",baseline:"baseline"},Jh={start:"flex-start",center:"center",end:"flex-end",between:"space-between",around:"space-around"},Xh={spin:"mtx-spin 1s linear infinite",ping:"mtx-ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"mtx-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",fadeIn:"mtx-fade-in 0.5s ease-out"},Gh={top:"borderTopWidth",bottom:"borderBottomWidth",left:"borderLeftWidth",right:"borderRightWidth"},Qh=/* @__PURE__ */new Set(["padding","paddingX","paddingY","paddingTop","paddingBottom","gap","align","justify","grow","shrink","position","inset","overflow","overflowY","width","height","minWidth","border","rounded","animate","hidden","as","style"]);function ef(e){const t={};return void 0!==e.padding&&(t.padding=Yh[e.padding]),void 0!==e.paddingX&&(t.paddingLeft=Yh[e.paddingX],t.paddingRight=Yh[e.paddingX]),void 0!==e.paddingY&&(t.paddingTop=Yh[e.paddingY],t.paddingBottom=Yh[e.paddingY]),void 0!==e.paddingTop&&(t.paddingTop=Yh[e.paddingTop]),void 0!==e.paddingBottom&&(t.paddingBottom=Yh[e.paddingBottom]),void 0!==e.gap&&(t.gap=Yh[e.gap]),void 0!==e.align&&(t.alignItems=Kh[e.align]),void 0!==e.justify&&(t.justifyContent=Jh[e.justify]),!0===e.grow&&(t.flex="1 1 0%"),!1===e.shrink&&(t.flexShrink=0),void 0!==e.position&&(t.position=e.position),void 0!==e.inset&&(t.inset="0"===e.inset?"0":Yh[e.inset]),void 0!==e.overflow&&(t.overflow=e.overflow),void 0!==e.overflowY&&(t.overflowY=e.overflowY),void 0!==e.width&&(t.width="full"===e.width?"100%":"auto"),void 0!==e.height&&(t.height="full"===e.height?"100%":"auto"),"0"===e.minWidth&&(t.minWidth=0),void 0!==e.border&&!1!==e.border&&(t.borderColor="var(--border)",t.borderStyle="solid",!0===e.border?t.borderWidth="1px":t[Gh[e.border]]="1px"),void 0!==e.rounded&&!1!==e.rounded&&(!0===e.rounded?t.borderRadius=Fh.theme:"full"===e.rounded?t.borderRadius=Fh.pill:t.borderRadius=Fh[e.rounded]),void 0!==e.animate&&"none"!==e.animate&&(t.animation=Xh[e.animate]),!0===e.hidden&&(t.display="none"),t}var tf={sm:20,md:32,lg:48};function nf(e){const{src:t,alt:n,elevation:r,fit:o="contain",size:i="md",rounded:s,className:a,style:c,ref:l,...u}=e,d="string"==typeof i?tf[i]:i;/* @__PURE__ */
10
- return y("img",{...u,ref:l,alt:n,className:a?`mtx-avatar ${a}`:"mtx-avatar",src:t,style:{objectFit:o,width:d,height:d,...ef({rounded:s}),...Bh(r),...c}})}var rf=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,disabled:o=!1,focusableWhenDisabled:i=!1,nativeButton:s=!0,style:a,...c}=e,{getButtonProps:l,buttonRef:u}=Tp({disabled:o,focusableWhenDisabled:i,native:s});return ep("button",e,{state:{disabled:o},ref:[t,u],props:[c,l]})}),of={default:Fh.lg,theme:Fh.theme,pill:Fh.pill};function sf({active:e=!1,className:t,disabled:n,elevation:r,full:o,shape:i="default",size:s="md",stacked:a=!1,type:c="button",variant:l="primary",style:u,ref:d,...p}){/* @__PURE__ */
11
- return y(rf,{...p,ref:d,className:t?`mtx-button ${t}`:"mtx-button","data-active":e?"true":"false","data-disabled":n?"true":"false","data-full":o?"true":"false","data-size":s,"data-stacked":a?"true":"false","data-variant":l,disabled:n,style:{borderRadius:of[i],...Bh(r),...u},type:c})}var af={default:{},card:{backgroundColor:"var(--card)",color:"var(--card-foreground)"}},cf={none:{},card:{padding:"8px 12px"},toast:{padding:"8px 12px 8px 8px"}},lf=o(function(e,t){const{as:n="div",background:r="default",className:o,elevation:i,paddingPreset:s="none",style:a,...c}=e,l=function(e){const t={};for(const n in e)Qh.has(n)||(t[n]=e[n]);return t}(c);/* @__PURE__ */
12
- return y(n,{...l,ref:t,className:o,style:{...af[r],...cf[s],...Bh(i),...ef(e),...a}})}),uf=o(function(e,t){const{direction:n,hidden:r,style:o,...i}=e;/* @__PURE__ */
13
- return y(lf,{...i,ref:t,hidden:r,style:{display:!0===r?"none":"flex",..."column"===n&&{flexDirection:"column"},...o}})}),df=(e,t=2)=>({d:e,stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round"}),pf={checkCircle:{viewBox:"0 0 512 512",paths:[{d:"M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z",fill:"currentColor"}]},circle:{viewBox:"0 0 512 512",paths:[{d:"M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z",fill:"currentColor"}]},exclamationCircle:{viewBox:"0 0 512 512",paths:[{d:"M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z",fill:"currentColor"}]},arrowUp:{viewBox:"0 0 448 512",paths:[{d:"M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z",fill:"currentColor"}]},arrowDown:{viewBox:"0 0 448 512",paths:[{d:"M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z",fill:"currentColor"}]},chatBubble:{viewBox:"0 0 512 512",paths:[{d:"M87.48 380c1.2-4.38-1.43-10.47-3.94-14.86a42.63 42.63 0 0 0-2.54-3.8 199.81 199.81 0 0 1-33-110C47.64 139.09 140.72 48 255.82 48 356.2 48 440 117.54 459.57 209.85a199 199 0 0 1 4.43 41.64c0 112.41-89.49 204.93-204.59 204.93-18.31 0-43-4.6-56.47-8.37s-26.92-8.77-30.39-10.11a31.14 31.14 0 0 0-11.13-2.07 30.7 30.7 0 0 0-12.08 2.43L81.5 462.78a15.92 15.92 0 0 1-4.66 1.22 9.61 9.61 0 0 1-9.58-9.74 15.85 15.85 0 0 1 .6-3.29z",fill:"none",stroke:"currentColor",strokeWidth:32,strokeLinecap:"round"},{d:"M160 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0",fill:"currentColor"},{d:"M256 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0",fill:"currentColor"},{d:"M352 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0",fill:"currentColor"}]},stop:{viewBox:"0 0 512 512",paths:[{d:"M392 432H120a40 40 0 0 1-40-40V120a40 40 0 0 1 40-40h272a40 40 0 0 1 40 40v272a40 40 0 0 1-40 40z",fill:"currentColor"}]},mousePointerClick:{viewBox:"0 0 24 24",paths:[df("M14 4.1 12 6"),df("m5.1 8-2.9-.8"),df("m6 12-1.9 2"),df("M7.2 2.2 8 5.1"),df("M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z")]},ticktick:{viewBox:"0 0 24 24",paths:[{d:"M12 0C5.383 0 0 5.383 0 12s5.383 12 12 12 12-5.383 12-12h-2.7c0 5.128-4.172 9.3-9.3 9.3-5.128 0-9.3-4.172-9.3-9.3 0-5.128 4.172-9.3 9.3-9.3V0Zm7.4 2.583-7.505 9.371L8.388 9.08l-2.002 2.436 4.741 3.888a1.573 1.573 0 0 0 2.231-.233l8.504-10.617L19.4 2.583Z",fill:"currentColor"}]},home:{viewBox:"0 0 24 24",paths:[df("M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6")]},chat:{viewBox:"0 0 24 24",paths:[df("M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z")]},send:{viewBox:"0 0 24 24",paths:[df("M5 12h14m-7-7l7 7-7 7")]},closeSmall:{viewBox:"0 0 12 12",paths:[df("M9 3L3 9M3 3l6 6",1.5)]},close:{viewBox:"0 0 20 20",paths:[{d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd"}]},chevronDown:{viewBox:"0 0 24 24",paths:[df("M19 9l-7 7-7-7",2.5)]},screenShare:{viewBox:"0 0 24 24",paths:[df("M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z")]},alertCircle:{viewBox:"0 0 24 24",paths:[df("M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z")]}};function hf({name:e,size:t=16,className:n,ref:r,...o}){const i=pf[e];return i?/* @__PURE__ */y("svg",{...o,ref:r,"aria-hidden":"true",className:n?`mtx-icon ${n}`:"mtx-icon",fill:"none",height:t,viewBox:i.viewBox,width:t,xmlns:"http://www.w3.org/2000/svg",children:i.paths.map((e,t)=>/* @__PURE__ */y("path",{clipRule:e.clipRule,d:e.d,fill:e.fill??(e.stroke?"none":"currentColor"),fillRule:e.fillRule,stroke:e.stroke,strokeLinecap:e.strokeLinecap,strokeLinejoin:e.strokeLinejoin,strokeMiterlimit:e.strokeMiterlimit,strokeWidth:e.strokeWidth},t))}):null}function ff({variant:e="ghost",size:t="sm",tone:n,label:r,disabled:o,children:i,style:s,ref:a,...c}){/* @__PURE__ */
14
- return y("button",{...c,ref:a,type:"button",disabled:o,"aria-label":r,className:"mtx-icon-button","data-disabled":o?"true":"false","data-size":t,"data-variant":e,style:n?{color:jh[n],...s}:s,children:i})}var mf=o(function(e,t){/* @__PURE__ */
15
- return y(uf,{...e,ref:t,direction:"column"})}),gf={xxs:"10px",xs:"0.75rem",sm:"0.875rem",lg:"1.125rem"},yf={normal:400,medium:500,semibold:600},vf={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function bf({as:e="span",block:t=!1,inheritColor:n=!1,italic:r=!1,leading:o,variant:i="default",size:s,weight:a,truncate:c,align:l,className:u,ref:d,style:p,...h}){/* @__PURE__ */
16
- return y(e,{...h,ref:d,className:u,style:{color:jh[n?"inherit":i],...s&&{fontSize:gf[s]},...a&&{fontWeight:yf[a]},...l&&{textAlign:l},...o&&{lineHeight:Uh[o]},...t&&{display:"block"},...r&&{fontStyle:"italic"},...c&&vf,...p}})}var wf=()=>{const{toasts:e}=Dh();return e.map(e=>{const t=Wh[n=e.type,"error"===n||"info"===n?n:"neutral"];var n;/* @__PURE__ */
17
- return v(mp,{toast:e,className:"mtx-toast",render:/* @__PURE__ */y(uf,{align:"center",gap:"md",rounded:"pill",paddingPreset:"toast",elevation:"panel",style:{backgroundColor:t.background,border:t.border}}),children:[
18
- /* @__PURE__ */y(nf,{src:$h,alt:"",size:28,rounded:"full"}),
19
- /* @__PURE__ */v(mf,{grow:!0,minWidth:"0",children:[/* @__PURE__ */y(_p,{render:/* @__PURE__ */y(bf,{as:"span",block:!0,inheritColor:!0,weight:"medium",style:{fontSize:"13px",color:t.titleColor,whiteSpace:e.actionProps?"normal":"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})}),null!=e.description&&/* @__PURE__ */y(kp,{render:/* @__PURE__ */y(bf,{as:"span",block:!0,inheritColor:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})})]}),e.actionProps&&/* @__PURE__ */y(Rp,{render:/* @__PURE__ */y(sf,{type:"button",variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
20
- /* @__PURE__ */y(Op,{render:/* @__PURE__ */y(ff,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */y(hf,{name:"closeSmall",size:12})})]},e.id)})},xf=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(zd,{children:[e,/* @__PURE__ */y(Bp,{container:t??void 0,children:/* @__PURE__ */y(np,{className:"mtx-toast-viewport",style:{zIndex:Vh,bottom:`${n}px`},children:/* @__PURE__ */y(wf,{})})})]}),Sf=Dh,kf=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Sf();return a(()=>{if(null!=e)return s({id:"error",type:"error",title:e,timeout:0,priority:"high",onClose:t,...n&&{actionProps:{children:"Retry",onClick:n}}}),()=>c("error")},[e,n,s,c,t]),a(()=>{if(r)return s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}),()=>c("greeting")},[r,o,s,c,i]),null};function _f(e){const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}}function Ef({videoStream:e,...t}){const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screenshare ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}}var Cf=new class{restore(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=ua.getContext();return{...o,messages:r.map(_f)}}persist(e){ua.updateContext({...e,messages:e.messages.map(Ef)})}};function If(e,t,n,r={}){return{id:`${e}-${Date.now()}`,content:n,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Tf=(e,t,n="user-message")=>If(n,"user",e.trim(),{mode:t}),Mf=e=>If("agent-message","agent",e.trim()),Of=(e,t,n,r)=>If(r,n,e,{mode:t,isSystemMessage:!0});async function Rf(e,t,n,r){const o=await da.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:ua.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString(),marketrix_id:e.mtxId,marketrix_key:e.mtxKey};e.userId&&(r.user_id=e.userId),oa.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>console.warn("[API Service] Failed to log widget question:",e))}(e,t,n);const i={type:`chat/${n}`,request_id:r,content:t},s=Pl.getInstance();await s.ready(o),await s.send(i)}var zf={show:"Show",tell:"Tell",do:"Do"},Af=e=>zf[e],Pf=e=>(e??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});function Nf(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function Df({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest,o=e=>e.isPlaceholder&&void 0===e.mode||e.mode===n,i=[];!t||"show"!==n&&"do"!==n||i.push(e=>r(e)&&o(e)&&!!e.isPlaceholder,e=>r(e)&&o(e)),i.push(e=>r(e)&&!!e.isPlaceholder,r);for(const s of i){const t=Nf(e,s);if(t>=0)return{index:t,message:e[t]}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var $f=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys"]),Lf=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function Ff(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var jf=(e,t)=>e.parts.findIndex(e=>(e=>"progress"===e.type&&"in_progress"===e.status)(e)&&e.browserToolName===t);var Uf=/* @__PURE__ */new Map([["navigate","Navigating"],["search","Searching"],["click_element","Clicking element"],["type_text","Typing text"],["scroll","Scrolling"],["scroll_to_text","Scrolling to text"],["send_keys","Pressing key"],["extract","Extracting content"],["get_dropdown_options","Reading dropdown options"],["select_dropdown_option","Selecting option"],["go_back","Going back"],["wait","Waiting"],["close_tab","Closing tab"],["done","Done"],["get_html","Reading the page"],["get_screenshot","Taking screenshot"]]),Wf=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*Bf(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function Hf(e){if(!(e instanceof Element))return!1;try{if(!function(e){const t=e.tagName.toLowerCase();return"button"===t||"input"===t||"textarea"===t||"select"===t||"a"===t&&e.hasAttribute("href")||Wf.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0}(e))return!1;if(!0===e.disabled)return!1;if("true"===e.getAttribute("aria-disabled"))return!1;for(const r of Bf(e))if(r instanceof HTMLElement&&r.inert)return!1;const t=window.getComputedStyle(e);if("none"===t.display||"none"===t.pointerEvents)return!1;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;for(const r of Bf(e))if(r!==e){const e=window.getComputedStyle(r).overflow;if("hidden"===e||"clip"===e){const e=r.getBoundingClientRect();if(n.right<e.left||n.left>e.right||n.bottom<e.top||n.top>e.bottom)return!1}if(r===document.body)break}for(let r=e.getRootNode();r instanceof ShadowRoot;r=r.host.getRootNode()){const e=r.host.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1}return!0}catch(ko){return console.error("[isInteractable] Unexpected error:",ko),!1}}var Zf=["id","type","role","aria-label","name","href"],qf=new class{index=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;generateAnchoredSelector(e){const t=[];let n=e;for(;n!==document.body;){const e=n.id?`#${CSS.escape(n.id)}`:"";if(e&&1===document.querySelectorAll(e).length)return t.unshift(e),t.join(" > ");const r=n.parentElement;if(!r)break;const o=n.tagName,i=Array.from(r.children).filter(e=>e.tagName===o),s=i.length>1?`:nth-of-type(${i.indexOf(n)+1})`:"";t.unshift(o.toLowerCase()+s),n=r}return["body",...t].join(" > ")}staleReason(e){return document.contains(e.element)?Zf.some((t,n)=>e.element.getAttribute(t)!==e.identity[n])?"has changed":null:"no longer exists"}indexInteractableElements(){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;for(;t;){const r=t instanceof HTMLElement?t:null;if(r){const e=r.matches('a[href], button, input, textarea, select, [role="button"]'),t=r.classList.contains("cursor-pointer")||r.classList.contains("clickable"),o="function"==typeof r.onclick;(e||t||o||Hf(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:Zf.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,{selector:r}]of this.index.entries())try{e.querySelector(r)?.setAttribute("data-id",n.toString())}catch(t){console.warn(`[DomService] Failed to tag index ${n}:`,t)}return e.outerHTML}getSequenceForElement(e){return this.elementToSequence.get(e)}clearIndex(){this.index.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap}checkElementInteractable(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`;const o=r.left+r.width/2,i=r.top+r.height/2,s=document.elementFromPoint(o,i);if(s&&s!==e&&!e.contains(s)&&!s.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=s.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${s.className?`${e}.${s.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}getValidatedElement(e){const t=this.index.get(e);if(!t)return{element:null,error:`Element ${e} not found`};const n=this.staleReason(t);if(n)return{element:null,error:`DOM_CHANGED: Element at index ${e} ${n}. Call get_html to get updated indices.`};const r=this.checkElementInteractable(t.element,e);return r?{element:null,error:r}:{element:t.element}}},Vf=null;function Yf(){return Vf?.active&&"live"===Vf.getVideoTracks()[0]?.readyState?Vf:(Vf=null,null)}async function Kf(){if(!1===ua.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=Yf();if(e)return e;const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!t||0===t.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return Vf=t,t.getVideoTracks()[0].addEventListener("ended",()=>{Vf=null}),t}var Jf=["scroll","resize","touchmove","wheel"],Xf=320,Gf=new class{currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;visibilityCheckInterval=null;async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:o}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===o&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),this.createHighlight(t),this.createPopup(n,r),this.setupPositionUpdates(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})),this.currentPromise}cleanup(){if(this.takeSettlers().reject?.(/* @__PURE__ */new Error("Cancelled by cleanup")),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler){for(const e of Jf)window.removeEventListener(e,this.scrollHandler,{capture:!0});this.scrollHandler=null}this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.currentPopup?.remove(),this.currentHighlight?.remove(),document.getElementById("marketrix-show-popup")?.remove(),document.getElementById("marketrix-show-highlight")?.remove(),this.currentPopup=null,this.currentHighlight=null,this.currentElement=null,this.currentOptions=null,this.currentPromise=null}completeAction(){this.takeSettlers().resolve?.(),this.cleanup()}takeSettlers(){const e={resolve:this.resolvePromise,reject:this.rejectPromise};return this.resolvePromise=null,this.rejectPromise=null,e}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>`,n.style.cssText="position: fixed; width: 320px; background: white; border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 2147483646; padding: 16px;",document.body.appendChild(n),this.currentPopup=n,t||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.scrollHandler=()=>{if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();Object.assign(this.currentHighlight.style,{top:`${e.top}px`,left:`${e.left}px`,width:`${e.width}px`,height:`${e.height}px`}),this.updatePopupPosition()};for(const e of Jf)window.addEventListener(e,this.scrollHandler,{capture:!0,passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=120,n=10,r=e.left+e.width/2,o=e.top+e.height/2,i=[{left:e.right+20,top:o-60},{left:e.left-Xf-20,top:o-60},{left:r-160,top:e.top-t-20},{left:r-160,top:e.bottom+20}];let s=i[0];for(const a of i)if(a.left>=n&&a.left+Xf<=window.innerWidth-n&&a.top>=n&&a.top+t<=window.innerHeight-n){s=a;break}this.currentPopup.style.left=`${Math.max(n,Math.min(s.left,window.innerWidth-Xf-n))}px`,this.currentPopup.style.top=`${Math.max(n,Math.min(s.top,window.innerHeight-t-n))}px`}setupClickHandler(){this.clickHandler=e=>{this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)&&(e.preventDefault(),e.stopPropagation(),this.completeAction())},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{e.querySelector("#marketrix-show-continue")?.addEventListener("click",e=>{e.stopPropagation(),this.completeAction()})})}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{const e=this.currentElement;if(!e)return;const t=e.getBoundingClientRect();if(t.bottom<0||t.top>window.innerHeight||t.right<0||t.left>window.innerWidth)return void this.failShowAction("ELEMENT_OFF_SCREEN: The highlighted element scrolled out of view");const n=qf.getSequenceForElement(e)??-1,r=qf.checkElementInteractable(e,n);r&&this.failShowAction(r)},200)}failShowAction(e){this.takeSettlers().reject?.(new Error(e)),this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}},Qf=e=>({success:!0,data:{text:e}}),em=e=>({success:!0,data:e}),tm=e=>({success:!1,data:{text:""},error:e}),nm=e=>({success:!1,data:{options:[]},error:e});var rm=new class{async executeTool(e,t,n="do",r=""){const o=t;try{if("show"===n&&$f.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=qf.getValidatedElement(t);if(!n)return tm(o||`Element ${t} not found`);await Gf.showToolAction({element:n,explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e})}}switch(e){case"navigate":return this.navigate(o);case"search":return this.search(o);case"click_element":return await this.clickElement(o);case"type_text":return this.typeText(o);case"scroll":return this.scroll(o);case"scroll_to_text":return this.scrollToText(o);case"extract":return this.extract(o);case"go_back":return this.goBack();case"wait":return await this.wait(o);case"select_dropdown_option":return this.selectDropdownOption(o);case"get_dropdown_options":return this.getDropdownOptions(o);case"send_keys":return this.sendKeys(o);case"close_tab":return this.closeTab();case"done":return this.done(o);case"get_html":return this.getHtml();case"get_screenshot":return await this.getScreenshot();default:return tm(`Unknown tool: ${e}`)}}catch(ko){return tm(ko instanceof Error?ko.message:String(ko))}}navigate(e){if(!e.url)return tm("URL is required");if(e.new_tab)return window.open(e.url,"_blank")?Qf(`Opened ${e.url} in new tab`):tm("The browser blocked opening a new tab");const t=e.url;return{...Qf(`Navigating to ${t}`),afterResponseAttempt:()=>{window.location.href=t}}}search(e){if(!e.query)return tm("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}`),{...Qf(`Searching for "${e.query}" on ${t}`),afterResponseAttempt:()=>{window.location.href=r}}}async clickElement(e){if(void 0===e.index)return tm("Index required");const{element:t,error:n}=qf.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),{...Qf(`Clicked element ${e.index}`),afterResponseAttempt:()=>t.click()}):tm(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return tm("Index and text required");const t=!1!==e.clear,{element:n,error:r}=qf.getValidatedElement(e.index);if(!n)return tm(r||`Element ${e.index} not found`);if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)n.focus(),this.setNativeValue(n,t?e.text:n.value+e.text),n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}));else if(n.isContentEditable){n.focus();const r=window.getSelection();if(t?r?.selectAllChildren(n):r?.collapse(n,n.childNodes.length),!document.execCommand("insertText",!1,e.text))return tm(`Could not insert text into element ${e.index}`)}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(o){return tm(`Failed to set value on element: ${o instanceof Error?o.message:String(o)}`)}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(o){return tm(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return Qf(`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 tm("Invalid direction")}return Qf(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return tm("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"}),Qf(`Scrolled to "${e.text}"`);return tm(`Text "${e.text}" not found`)}extract(e){const t=!1!==e.extract_links,n={title:document.title,url:window.location.href,text:document.body.innerText.slice(0,1e4),links:t?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]};return em(n)}goBack(){return window.history.length<=1?tm("No history"):{...Qf("Navigated back"),afterResponseAttempt:()=>window.history.back()}}async wait({seconds:e}){return void 0===e?tm("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),Qf(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return tm("Index/Option required");const{element:t,error:n}=qf.getValidatedElement(e.index);if(!t)return tm(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return tm(`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})),Qf(`Selected ${e.option}`)):tm(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return nm("Index required");const{element:n,error:r}=qf.getValidatedElement(t);if(!n)return nm(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return nm(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return em({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return tm("Index/Keys required");const{element:t,error:n}=qf.getValidatedElement(e.index);if(!t)return tm(n||`Element ${e.index} not found`);t.focus(),t.dispatchEvent(new KeyboardEvent("keydown",{key:e.keys,bubbles:!0,cancelable:!0})),t.dispatchEvent(new KeyboardEvent("keyup",{key:e.keys,bubbles:!0,cancelable:!0}));const r=this.simulateKeyAction(t,e.keys);return Qf(r||`Sent keys ${e.keys}`)}simulateKeyAction(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=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),o=r.indexOf(e),i=-1===o?void 0:r[o+n];return i?(i.focus(),`${t}: moved focus to ${i.tagName.toLowerCase()}${i.id?`#${i.id}`:""}`):`${t}: no ${n>0?"next":"previous"} focusable element`}case"Enter":if(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";const n=e.selectionStart??t.length,r=e.selectionEnd??t.length;let o,i;if(n===r&&n>0)o=t.slice(0,n-1)+t.slice(r),i=n-1;else{if(n===r)return"Backspace: cursor at start, nothing to delete";o=t.slice(0,n)+t.slice(r),i=n}return this.setValueAndCaret(e,o,i),`Backspace: deleted character, value is now "${o}"`}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 o;if(t===n&&t<r.length)o=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";o=r.slice(0,t)+r.slice(n)}return this.setValueAndCaret(e,o,t),`Delete: deleted character, value is now "${o}"`}return"Delete: dispatched event";default:return null}}setNativeValue(e,t){const n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;n?n.call(e,t):e.value=t}setValueAndCaret(e,t,n){this.setNativeValue(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}closeTab(){return window.close(),window.closed?Qf("Tab closed"):tm("The browser refused to close a tab this script did not open")}done(e){return Qf(e.message||"Task ended")}getHtml(){try{const e=qf.reindexAndSnapshot();return Qf(e)}catch(ko){return tm(String(ko))}}async getScreenshot(){const e=document.createElement("video");try{e.srcObject=await Kf(),e.autoplay=!0,e.style.display="none",document.body.appendChild(e),await function(e,t){return new Promise((n,r)=>{const o=setTimeout(()=>r(/* @__PURE__ */new Error("Screen capture produced no frame")),t);e.onloadeddata=()=>{clearTimeout(o),n()},e.onerror=()=>{clearTimeout(o),r(/* @__PURE__ */new Error("Screen capture failed"))}})}(e,5e3);const t=document.createElement("canvas");return t.width=e.videoWidth,t.height=e.videoHeight,t.getContext("2d")?.drawImage(e,0,0),Qf(t.toDataURL("image/jpeg",.75))}catch(ko){return tm(String(ko))}finally{e.remove()}}},om=e=>({state:e,effects:[]});function im(e,t,n,r,o,i,s){const a=Df({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=jf(e,t);if(r<0)return e;const o=Lf(e.parts[r].content),i=Lf(n);return Ff(e,r,{status:"failed",content:i?`${o} (${i})`:o})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=Lf(n),o=jf(e,t);return o>=0?Ff(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>Uf.get(e)??e)(r)):((e,t)=>Ff(e,jf(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&$f.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var sm=e=>({...e,isPlaceholder:!1});function am(e,t,n){const r=Df({messages:e.messages,isTaskRunning:e.task.isTaskRunning,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=sm(n(r.message))),{messages:o,task:{isTaskRunning:!1}}}var cm={completed:"done",failed:"failed",stopped:"stopped"};function lm(e,t,n,r){const o=e.messages.map(e=>{if(e.id!==t)return e;const o=[...e.parts],i=o[o.length-1],s="text"===i?.type&&!0===i.streaming,a=r&&s?i.content+n:n,c={type:"text",content:a,...r&&{streaming:!0}};return s?o[o.length-1]=c:o.push(c),{...e,content:a,isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var um=(e,t)=>({...e,content:t,parts:[...e.parts,{type:"text",content:t}]}),dm=(e,t)=>({...sm(um(e,t)),placeholderState:void 0});function pm(e,t,n){const r=e.messages.map(e=>e.id===t?dm(e,n):e);return{...e,messages:r}}var hm=n(void 0),fm=({children:e})=>{const[t,n]=p({isOpen:!1,activeView:"home",currentMode:"tell"}),r=u(()=>({setActiveView:e=>n(t=>({...t,activeView:e})),toggleWidget:()=>n(e=>({...e,isOpen:!e.isOpen})),closeWidget:()=>n(e=>({...e,isOpen:!1})),setMode:e=>n(t=>({...t,currentMode:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]);/* @__PURE__ */
21
- return y(hm.Provider,{value:{uiState:t,uiActions:r},children:e})},mm=()=>{const e=s(hm);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},gm=n(void 0),ym=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=mm(),[o,s]=p(()=>({messages:[],task:{isTaskRunning:!1}})),c=d(o),l=d(n.currentMode);l.current=n.currentMode;const h=d(/* @__PURE__ */new Set),f=i(e=>{const t=c.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(c.current=n,s(n))},[]),m=i(e=>{f(t=>({...t,messages:[...t.messages,e]}))},[f]),g=i((e,t)=>{f(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[f]),v=i(e=>{f(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[f]),b=i(e=>{f(t=>({...t,messages:e}))},[f]),w=i(()=>{f(e=>({...e,messages:[]}))},[f]),x=i(e=>{f(t=>({...t,task:{isTaskRunning:e}}))},[f]),S=o.messages.filter(e=>e.isPlaceholder).map(e=>e.id).join(" ");a(()=>{const e=S.split(" ").filter(Boolean).map(e=>setTimeout(()=>f(t=>function(e,t,n){return e.task.isTaskRunning?e:e.messages.find(e=>e.id===t)?.isPlaceholder?pm(e,t,n):e}(t,e,"This is taking longer than expected. Please try again.")),12e4));return()=>e.forEach(clearTimeout)},[S,f]);const k=i(async(e,n,r)=>{const o=n??l.current;if(t)return r||m(Tf(e,o)),void m(Mf("This is a preview. In production, I'll respond to your messages here."));const i=ua.getCredentialedConfig();if(!i)return console.error("Config not loaded or incomplete"),void m(Mf("Configuration error: Missing API credentials. Please check your widget settings."));r||m(Tf(e,o));const s=`temp-${globalThis.crypto.randomUUID()}`;m({id:s,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:o,isPlaceholder:!0,placeholderState:"thinking",parts:[]});try{await Rf(i,e,o,s)}catch(ko){console.error("Failed to send message:",ko),f(e=>pm(e,s,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=Pl.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await rm.executeTool(r,o,i,s),c=a.success?void 0:a.error??"Tool execution failed";f(e=>function(e,t,n,r,o,i){return{...e,messages:im(e.messages,e.task.isTaskRunning,o,t,n,r,i)}}(e,r,s,c?"failed":"completed",l.current,c)),c||"done"!==r||f(e=>function(e,t){return am(e,t,e=>({...e,taskStatus:"done"}))}(e,l.current)),await e.send({type:"tool/response",tool_call_id:n,success:a.success,data:JSON.stringify(a.data),error:c}).catch(e=>console.error("Failed to send tool response:",e)),a.afterResponseAttempt?.()},o={onMessage:e=>{if("tool/call"===e.type){const t=e.tool_call_id;if(h.current.has(t))return;h.current.add(t),h.current.size>1e3&&(h.current=new Set([...h.current].slice(-500)))}else"task/status"===e.type&&e.status in cm&&h.current.clear();let t=[];f(n=>{const r=function(e,t,n){switch(t.type){case"tool/call":{const r=e.task.isTaskRunning?e.task:{isTaskRunning:!0},o=t.explanation||"";return{state:{messages:im(e.messages,r.isTaskRunning,n,t.browser_tool,o,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:t.mode||n,explanation:o}]}}case"task/status":{if("running"===t.status)return om(e);const r=t.status,o=e=>t.message?um(e,t.message):e;return{state:am(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:cm[r]})),effects:[]}}case"chat/delta":return{state:lm(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:lm(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:pm(e,t.request_id,`Error: ${t.error}`),effects:[]};default:return om(e)}}(n,e,l.current);return t=r.effects,r.state});for(const r of t)n(r).catch(e=>console.error("[Widget] Tool call failed:",e))},onError:e=>{r.setError(e.message),e instanceof Al&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?dm(e,t):e),task:{isTaskRunning:!1}}}(t,e.message))}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[t,f,r]);const _=i(async()=>{f(e=>function(e,t){return am(e,t,e=>({...e,taskStatus:"stopped"}))}(e,l.current)),t||Pl.getInstance().send({type:"chat/stop"}).catch(e=>{console.error("Failed to stop task remotely:",e),r.setError("Could not stop the assistant — it may still be working.")})},[t,f,r]),E=u(()=>({addMessage:m,updateMessage:g,removeMessage:v,setMessages:b,clearMessages:w,messageDispatch:k}),[m,g,v,b,w,k]),C=u(()=>({setTaskState:x,stopTask:_}),[x,_]);/* @__PURE__ */
22
- return y(gm.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:C},children:e})},vm=()=>{const e=s(gm);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},bm=n(null),wm=()=>{const{uiState:e}=mm(),{messages:t}=vm();return a(()=>{const{currentMode:n,isOpen:r}=e;Cf.persist({messages:t,currentMode:n,isOpen:r})},[t,e]),null},xm=({children:e,previewMode:t})=>{const{uiActions:n}=mm(),{chatActions:r}=vm(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const t=await da.getOrCreateChatId();if(e)return;const{messages:o,...s}=Cf.restore();n.applyState(s),r.setMessages(o),i(!0),Pl.getInstance().connect(t).catch(e=>console.error("Initial stream connection failed:",e))})().catch(t=>{e||(console.error("Widget initialization failed:",t),n.setError("Widget failed to initialise — please refresh the page."))}),()=>{e=!0}},[]),/* @__PURE__ */v(g,{children:[e,o&&/* @__PURE__ */y(wm,{})]})},Sm=({children:e,previewMode:t=!1})=>/* @__PURE__ */y(fm,{children:/* @__PURE__ */y(ym,{previewMode:t,children:/* @__PURE__ */y(xm,{previewMode:t,children:e})})});function km(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 _m(e){return function(e){const t=km(e);if(!t)return.5;const[n,r,o]=[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*o}(e)>.5?"#000000":"#ffffff"}function Em(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=km(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}var Cm={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"};function Im(e={}){const t=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e));return function(e){return{color:{background:e.widget_background_color,foreground:e.widget_text_color,foregroundMuted:Em(e.widget_text_color,.6),foregroundFaint:Em(e.widget_text_color,.4),border:e.widget_border_color,primary:e.widget_accent_color,primaryForeground:_m(e.widget_accent_color),primaryHover:Em(e.widget_accent_color,.85),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:Em(e.widget_secondary_color,.2),secondaryHover:Em(e.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}({...Cm,...t})}var Tm=n(null),Mm=()=>{const e=s(Tm);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},Om=()=>{const{uiState:e,uiActions:t}=mm(),{messages:n,chatActions:r,taskState:o,taskActions:s}=vm(),a=u(()=>({...e,...o,messages:n,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),c=i(()=>{r.clearMessages(),s.setTaskState(!1),t.setError(void 0)},[r,s,t]);return{state:a,actions:u(()=>({...t,...s,...r,clearChatHistory:c}),[t,s,r,c])}},Rm=20,zm={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},Am=Object.keys(zm),Pm=e=>zm[e],Nm=e=>{const{vertical:t,horizontal:n}=Pm(e);return{[t]:"20px",[n]:"20px"}},Dm=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Pm(e);return{x:"left"===s?Rm:t-Rm-r,y:"top"===i?Rm:n-Rm-o}},$m=class extends t.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`${this.props.label} Error Boundary caught error:`,e,t)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},Lm="cubic-bezier(0.16, 1, 0.3, 1)";function Fm({position:e,onPositionCommit:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=p(!1),[c,u]=p({w:56,h:56}),[,h]=p(0),f=d(null),m=d(null),g=d(null),y=d(0),v=d([]),b=d(0),w=()=>{null!==g.current&&window.cancelAnimationFrame(g.current),g.current=null};t.useEffect(()=>w,[]),t.useEffect(()=>{if(r)return;const e=()=>h(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[r]);const x=i(()=>{if(!o.current||"undefined"==typeof window)return;const e=o.current.getBoundingClientRect();u(t=>t.w===e.width&&t.h===e.height?t:{w:e.width,h:e.height})},[o]);l(()=>{x();const e="undefined"!=typeof window&&o.current?new ResizeObserver(x):null;return e&&o.current&&e.observe(o.current),()=>e?.disconnect()},[x,e,o]);const S="undefined"!=typeof window?window.innerWidth:0,k="undefined"!=typeof window?window.innerHeight:0,_=Dm(e,S,k,c.w,c.h),E=!r&&S>0&&k>0?{left:_.x,top:_.y}:void 0,C=(e,t=.999)=>e/1e3*t/(1-t),I=()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="")},T=i((e,t)=>{if(f.current)return;let r=!1;const i=()=>{r||(r=!0,f.current=null,t.style.transition="none",t.style.willChange="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))};f.current=i;const s=window.setTimeout(i,650);t.addEventListener("transitionend",function e(n){n.target===t&&"left"===n.propertyName&&(window.clearTimeout(s),t.removeEventListener("transitionend",e),i())})},[n,o]),M=i((t,r,i)=>{if(!o.current||!E)return I(),n(t),void a(!1);w();const s=o.current,l=Dm(e,S,k,c.w,c.h),u=Dm(t,S,k,c.w,c.h);s.style.transition="none",s.style.transform="none",s.style.willChange="left, top",s.style.left=`${l.x+r}px`,s.style.top=`${l.y+i}px`,requestAnimationFrame(()=>{s.style.transition=`left 600ms ${Lm}, top 600ms ${Lm}`,s.style.left=`${u.x}px`,s.style.top=`${u.y}px`}),T(t,s)},[T,n,E,e,S,k,c.w,c.h,o]),O=e=>{I(),m.current=null,a(!1),e.currentTarget.releasePointerCapture(e.pointerId)};return{isDragging:s,pixelPositionStyle:E,onPointerDown:e=>{m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragging:!1,lastX:0,lastY:0},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{const t=m.current;if(t?.pointerId!==e.pointerId)return;const n=e.clientX-t.startX,r=e.clientY-t.startY;if(!t.dragging&&Math.hypot(n,r)>5&&(t.dragging=!0,a(!0),v.current=[],b.current=0,o.current&&(o.current.style.willChange="transform",o.current.style.transition="none")),!t.dragging)return;t.lastX=n,t.lastY=r;const i=Date.now();i-b.current>=10&&(b.current=i,v.current=[...v.current.slice(-5),{x:e.clientX,y:e.clientY,t:i}]),null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null;const e=m.current,t=o.current;t&&e&&(t.style.transform=`translate3d(${e.lastX}px, ${e.lastY}px, 0)`)}))},onPointerUp:t=>{const n=m.current;if(n?.pointerId===t.pointerId){if(n.dragging){const r=(()=>{const e=v.current;if(e.length<2)return{x:0,y:0};const t=e[e.length-1].t-e[0].t;return t<=0?{x:0,y:0}:{x:(e[e.length-1].x-e[0].x)/t*1e3,y:(e[e.length-1].y-e[0].y)/t*1e3}})(),i=C(r.x),s=C(r.y),a={dx:n.lastX+i,dy:n.lastY+s},c=o.current?.getBoundingClientRect(),l=c?((e,t,n,r,o,i)=>{const s=Dm(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,u=1/0;for(const d of Am){const e=Dm(d,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<u&&(u=t,l=d)}return l})(a,e,window.innerWidth,window.innerHeight,c.width,c.height):e;return M(l,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}O(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&O(e)},suppressUntilRef:y}}var jm=({onPositionCommit:e})=>{const{isPreviewMode:t=!1,widget_accent_color:n,widget_background_color:r,widget_position:o,widget_position_z_index:i}=Mm(),{state:s,actions:a}=Om(),c=s.isOpen,l=s.isTaskRunning,u=!!s.error,p=!c&&(s.isAwaitingReply||l),h=!c&&l,f=u?"marketrix-widget-button-error-glow":"marketrix-widget-button-processing-glow",m=u?"marketrix-widget-button-error-activity-ring":"marketrix-widget-button-processing-activity-ring",g=d(null),{isDragging:b,pixelPositionStyle:w,onPointerDown:x,onPointerMove:S,onPointerUp:k,onPointerCancel:_,suppressUntilRef:E}=Fm({position:o,onPositionCommit:e,isPreviewMode:t,wrapperRef:g});/* @__PURE__ */
23
- return y(lf,{ref:g,className:"mtx-fab-anchor","data-animated":b?"false":"true","data-preview":t?"true":"false",style:{zIndex:i,pointerEvents:c?"none":"auto",...Nm(o),...w},children:/* @__PURE__ */v(lf,{className:"mtx-fab","data-open":c?"true":"false",children:[p&&/* @__PURE__ */y(lf,{className:f,"aria-hidden":!0}),h&&!b&&/* @__PURE__ */y(sf,{type:"button",variant:"secondary",size:"sm",className:"mtx-fab-stop","data-side":o.includes("left")?"left":"right",onClick:e=>{e.preventDefault(),e.stopPropagation(),a.stopTask()},children:"Stop"}),
24
- /* @__PURE__ */y(sf,{type:"button",variant:"bare",onClick:()=>{Date.now()<E.current||a.toggleWidget()},onDragStart:e=>e.preventDefault(),onPointerDown:x,onPointerMove:S,onPointerUp:k,onPointerCancel:_,className:"mtx-fab-trigger",style:{touchAction:"none",cursor:b?"grabbing":"grab",userSelect:"none",WebkitUserSelect:"none"},"aria-label":c?"Close":"Open","aria-live":"polite",children:/* @__PURE__ */y(uf,{className:"mtx-fab-center",children:/* @__PURE__ */v(lf,{className:"mtx-fab-badge",style:{borderRadius:"12px",backgroundColor:c?r:n,boxShadow:Lh.fab},children:[p&&/* @__PURE__ */y("svg",{className:m,viewBox:"0 0 54 54",fill:"none","aria-hidden":!0,children:/* @__PURE__ */y("rect",{x:"1.25",y:"1.25",width:"51.5",height:"51.5",rx:13,ry:13})}),
25
- /* @__PURE__ */y(uf,{className:"mtx-fab-icon-layer",style:{transform:c?"rotate(30deg) scale(0)":"rotate(0deg) scale(1)",opacity:c?0:1,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":c,children:/* @__PURE__ */y(nf,{src:$h,alt:"",className:"mtx-fab-avatar",draggable:!1,onDragStart:e=>e.preventDefault(),style:{borderRadius:"12px",border:"none",outline:"none",backgroundColor:"transparent",pointerEvents:"none",userSelect:"none"}})}),
26
- /* @__PURE__ */y(uf,{className:"mtx-fab-icon-layer",style:{transform:c?"rotate(0deg) scale(1)":"rotate(-30deg) scale(0)",opacity:c?1:0,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":!c,children:/* @__PURE__ */y(hf,{name:"chevronDown",size:24,className:"mtx-fab-chevron"})})]})})})]})})};var Um=/*#__PURE__*/e.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function Wm(t){const{children:n,elementsRef:r,labelsRef:o,onMapChange:i}=t,s=uu(i),[,a]=e.useState(!1),c=Vl(Hm).current,l=Vl(Bm).current,u=e.useRef(0),d=e.useRef(!0),p=e.useRef([]),h=e.useRef(null),f=uu(()=>{d.current||(d.current=!0,a(e=>!e))}),m=uu((e,t)=>{l.set(e,t),f()}),g=uu(e=>{l.delete(e),f()}),v=uu(e=>{const t=/* @__PURE__ */new Map;return r.current.length=0,o&&(o.current.length=0),e.forEach(e=>{t.set(e.element,{...e.registration.metadata??{},index:e.index}),r.current[e.index]=e.element,o&&(o.current[e.index]=void 0!==e.registration.label?e.registration.label:e.registration.textRef?.current?.textContent??e.element.textContent)}),u.current=r.current.length,t});const b=uu(()=>{const[e,t]=function(e){const t=/* @__PURE__ */new Set,n=[],r=[];e.forEach((e,o)=>{if(!o.isConnected)return;const i=e.index,s={index:i??-1,element:o,registration:e};null===i?r.push(s):i>=0&&(t.add(i),n.push(s))});let o=0;r.sort((e,t)=>qm(e.element,t.element)),r.forEach(e=>{for(;t.has(o);)o+=1;e.index=o,n.push(e),o+=1}),t.size>0&&n.sort((e,t)=>e.index-t.index);return[n,r.map(e=>e.element)]}(l),n=v(e);!function(e){if(h.current?.disconnect(),h.current=null,"function"!=typeof MutationObserver||e.length<2)return;const t=new MutationObserver(n=>{if(!function(e){for(const t of e)for(let e=0;e<t.removedNodes.length;e+=1)if(t.removedNodes[e].isConnected)return!0;return!1}(n))return;let r=null;for(const o of e)if(o.isConnected){if(r&&qm(r,o)>0)return t.disconnect(),void f();r=o}});h.current=t;const n=/* @__PURE__ */new Set;for(let r=1;r<e.length;r+=1){const t=Zm(e[r-1],e[r]);t&&n.add(t)}n.forEach(e=>t.observe(e,{childList:!0}))}(t),p.current=e,d.current=!1,c.forEach(e=>e(n)),s(n)});Yl(()=>(d.current||v(p.current),()=>{r.current=[],o&&(o.current=[])}),[r,o,v]),Yl(()=>{d.current&&b()}),Yl(()=>()=>{h.current?.disconnect(),d.current=!0},[]);const w=uu(e=>(c.add(e),()=>{c.delete(e)})),x=e.useMemo(()=>({register:m,unregister:g,subscribeMapChange:w,nextIndexRef:u}),[m,g,w,u]);/*#__PURE__*/
27
- return y(Um.Provider,{value:x,children:n})}function Bm(){/* @__PURE__ */
28
- return new Map}function Hm(){/* @__PURE__ */
29
- return new Set}function Zm(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function qm(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}var Vm=/*#__PURE__*/e.createContext(void 0);function Ym(){const t=e.useContext(Vm);if(void 0===t)throw new Error(Xl(64));return t}var Km={tabActivationDirection:e=>({"data-activation-direction":e})},Jm=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,defaultValue:o=0,onValueChange:i,orientation:s="horizontal",render:a,value:c,style:l,...u}=t,d=void 0!==t.defaultValue,p=e.useRef([]),[h,f]=e.useState(()=>/* @__PURE__ */new Map),[m,g]=function({controlled:t,default:n,name:r,state:o="value"}){const{current:i}=e.useRef(void 0!==t),[s,a]=e.useState(n);return[i?t:s,e.useCallback(e=>{i||a(e)},[])]}({controlled:c,default:o,name:"Tabs",state:"value"}),v=void 0!==c,[b,w]=e.useState(()=>/* @__PURE__ */new Map),x=e.useRef(void 0),S=e.useCallback(e=>Xm(b,e),[b]),[k,_]=e.useState(()=>({previousValue:m,tabActivationDirection:"none"})),{previousValue:E,tabActivationDirection:C}=k;let I=C,T=!1;E!==m&&(I=Gm(E,m,s,b),T=null!=E&&null!=m&&null==S(m));const M=T?E:m,O=E!==M||C!==I;Yl(()=>{O&&_({previousValue:M,tabActivationDirection:I})},[M,O,I]);const R=uu((e,t)=>{t.activationDirection=Gm(m,e,s,b),i?.(e,t),t.isCanceled||g(e)}),z=uu((e,t)=>{i?.(e,Np(t,void 0,void 0,{activationDirection:"none"}))}),A=uu((e,t)=>(f(n=>{const r=new Map(n);return r.set(e,t),r}),()=>{f(n=>{if(n.get(e)!==t)return n;const r=new Map(n);return r.delete(e),r})})),P=e.useCallback(e=>h.get(e),[h]),N=e.useCallback(e=>{for(const t of b.values())if(e===t.value)return t.id},[b]),D=e.useMemo(()=>({getTabElementBySelectedValue:S,getTabIdByPanelValue:N,getTabPanelIdByValue:P,onValueChange:R,orientation:s,registerMountedTabPanel:A,setTabMap:w,tabActivationDirection:I,value:m}),[S,N,P,R,s,A,w,I,m]),$=e.useMemo(()=>{for(const e of b.values())if(e.value===m)return e},[b,m]),L=e.useMemo(()=>{for(const e of b.values())if(!e.disabled)return e.value},[b]),F=e.useRef(!d),j=e.useRef(o),U=e.useRef(d),W=e.useRef(!1);Yl(()=>{if(v)return;function e(e,t){g(e),_({previousValue:e,tabActivationDirection:"none"}),z(e,t),F.current=!1}if(0===b.size)return void(W.current&&null!==m&&!x.current?.isConnected&&e(null,Ap));W.current=!0,x.current=b.keys().next().value;const t=$?.disabled,n=null==$&&null!==m;if(t||m!==j.current||(U.current=!1),U.current&&t&&m===j.current)return;const r=F.current;if(t||n){const n=L??null;if(m===n)return void(F.current=!1);let o=Ap;return r?o=Pp:t&&(o="disabled"),void e(n,o)}r&&null!=$&&(z(m,Pp),F.current=!1)},[L,v,z,$,g,b,m]);const B=ep("div",t,{state:{orientation:s,tabActivationDirection:I},ref:n,props:u,stateAttributesMapping:Km});/*#__PURE__*/
30
- return y(Vm.Provider,{value:D,children:/*#__PURE__*/y(Wm,{elementsRef:p,children:B})})});function Xm(e,t){for(const[n,r]of e.entries())if(t===r.value)return n;return null}function Gm(e,t,n,r){if(null==e||null==t)return"none";const[o,i,s]="horizontal"===n?["left","left","right"]:["top","up","down"],a=Xm(r,e),c=Xm(r,t);if(null==a||null==c)return a===c||"number"!=typeof e&&"string"!=typeof e||typeof e!=typeof t?"none":t>e?s:i;const l=a.getBoundingClientRect()[o],u=c.getBoundingClientRect()[o];return u<l?i:u>l?s:"none"}function Qm(e){return vp(e,"base-ui")}var eg="data-composite-item-active";function tg(t={}){const{guess:n,label:r,metadata:o,textRef:i,index:s}=t,{register:a,unregister:c,subscribeMapChange:l,nextIndexRef:u}=e.useContext(Um),d=e.useRef(-1),[p,h]=e.useState(null==s&&n?()=>{if(-1===d.current){const e=u.current;u.current+=1,d.current=e}return d.current}:-1),f=s??p,m=e.useRef(null),g=e.useCallback(e=>{const t=m.current;t&&c(t),m.current=e,e&&a(e,{metadata:o??null,index:s??null,label:r,textRef:i})},[s,a,c,o,r,i]);return Yl(()=>{if(null==s)return l(e=>{const t=m.current?e.get(m.current)?.index:null;null!=t&&h(t)})},[s,l]),{ref:g,index:f}}var ng=/*#__PURE__*/e.createContext(void 0);var rg=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,disabled:o=!1,render:i,value:s,id:a,nativeButton:c=!0,style:l,...u}=t,{value:d,getTabPanelIdByValue:p,onValueChange:h,orientation:f,tabActivationDirection:m}=Ym(),{activateOnFocus:g,registerTabResizeObserverElement:y,tabsListElement:v}=function(){const t=e.useContext(ng);if(void 0===t)throw new Error(Xl(65));return t}(),{highlightedIndex:b,onHighlightedIndexChange:w}=Cp(),x=Qm(a),S=e.useMemo(()=>({disabled:o,id:x,value:s}),[o,x,s]),{compositeProps:k,compositeRef:_,index:E}=function(t={}){const{highlightItemOnHover:n,highlightedIndex:r,onHighlightedIndexChange:o}=Cp(),{ref:i,index:s}=tg(t),a=r===s,c=e.useRef(null),l=$d(i,c);return{compositeProps:{tabIndex:a?0:-1,onFocus(){o(s)},onMouseMove(){const e=c.current;if(!n||!e)return;const t=e.hasAttribute("disabled")||"true"===e.ariaDisabled;a||t||e.focus()}},compositeRef:l,index:s}}({metadata:S}),C=s===d,I=e.useRef(!1),T=e.useRef(null),M=uu(e=>{T.current?.(),T.current=e?y(e):null});Yl(()=>{if(I.current)return void(I.current=!1);if(!(C&&E>-1&&b!==E))return;const e=v;if(null!=e){const t=Ku(Eu(e));if(t&&Ju(e,t))return}o||w(E)},[C,E,b,w,o,v]);const{getButtonProps:O,buttonRef:R}=Tp({disabled:o,native:c,focusableWhenDisabled:!0}),z=p(s),A=e.useRef(!1),P=e.useRef(!1);function N(e){h(s,Np(zp,e.nativeEvent,void 0,{activationDirection:"none"}))}return ep("button",t,{state:{disabled:o,active:C,orientation:f,tabActivationDirection:m},ref:[n,R,_,M],props:[k,{role:"tab","aria-controls":z,"aria-selected":C,id:x,onClick:function(e){C||o||N(e)},onFocus:function(e){C||o||!g||A.current&&!P.current||N(e)},onPointerDown:function(e){if(C||o)return;A.current=!0,P.current=0===e.button;const t=Eu(e.currentTarget);function n(){A.current=!1,P.current=!1,t.removeEventListener("pointerup",n),t.removeEventListener("pointercancel",n)}t.addEventListener("pointerup",n),t.addEventListener("pointercancel",n)},[eg]:C?"":void 0,onKeyDownCapture(){I.current=!0}},u,O],stateAttributesMapping:Km})}),og={...Km,...lp},ig=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,value:o,render:i,keepMounted:s=!1,style:a,...c}=t,{value:l,getTabIdByPanelValue:u,orientation:d,tabActivationDirection:p,registerMountedTabPanel:h}=Ym(),f=Qm(),{ref:m,index:g}=tg(),y=o===l,{mounted:v,transitionStatus:b,setMounted:w}=bh(y),x=!v,S=u(o),k={hidden:x,orientation:d,tabActivationDirection:p,transitionStatus:b},_=e.useRef(null),E=ep("div",t,{state:k,ref:[n,m,_],props:[{"aria-labelledby":S,hidden:x,id:f,role:"tabpanel",tabIndex:y?0:-1,inert:rp(!y),"data-index":g},c],stateAttributesMapping:og});return dp({open:y,ref:_,onComplete(){y||w(!1)}}),Yl(()=>{if(null!=f&&(!x||s))return h(o,f)},[x,s,o,f,h]),s||v?E:null});var sg="ArrowUp",ag="ArrowDown",cg="ArrowLeft",lg="ArrowRight",ug=/* @__PURE__ */new Set([sg,ag,cg,lg,"Home","End"]),dg=["Shift","Control","Alt","Meta"];function pg(e){return!(!function(e){return bu(e)&&"INPUT"===e.tagName}(e)||null==e.selectionStart)||!(!bu(e)||"TEXTAREA"!==e.tagName)}function hg(e,t,n,r){if(!e||!t||!t.scrollTo)return;let o=e.scrollLeft,i=e.scrollTop;const s=e.clientWidth<e.scrollWidth,a=e.clientHeight<e.scrollHeight;if(s&&"vertical"!==r){const r=fg(e,t,"left"),i=mg(e),s=mg(t);"ltr"===n&&(r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight?o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight:r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft&&(o=r-s.scrollMarginLeft-i.scrollPaddingLeft)),"rtl"===n&&(r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft?o=r-s.scrollMarginLeft-i.scrollPaddingLeft:r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight&&(o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight))}if(a&&"horizontal"!==r){const n=fg(e,t,"top"),r=mg(e),o=mg(t);n-o.scrollMarginTop<e.scrollTop+r.scrollPaddingTop?i=n-o.scrollMarginTop-r.scrollPaddingTop:n+t.offsetHeight+o.scrollMarginBottom>e.scrollTop+e.clientHeight-r.scrollPaddingBottom&&(i=n+t.offsetHeight+o.scrollMarginBottom-e.clientHeight+r.scrollPaddingBottom)}e.scrollTo({left:o,top:i,behavior:"auto"})}function fg(e,t,n){const r="left"===n?"offsetLeft":"offsetTop";let o=0;for(;t.offsetParent&&(o+=t[r],t.offsetParent!==e);)t=t.offsetParent;return o}function mg(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}var gg=[];function yg(t){const{loopFocus:n=!0,orientation:r="both",grid:o,onLoop:i,direction:s,highlightedIndex:a,onHighlightedIndexChange:c,rootRef:l,enableHomeAndEndKeys:u=!1,stopEventPropagation:d,disabledIndices:p,modifierKeys:h=gg}=t,[f,m]=e.useState(0),g=null!=o,y=e.useRef(null),v=$d(y,l),b=e.useRef([]),w=e.useRef(!1),x=a??f,S=uu((e,t=!1)=>{if((c??m)(e),t){const t=b.current[e];hg(y.current,t,s,r)}}),k=uu(e=>{if(0===e.size||w.current)return;w.current=!0;const t=Array.from(e.keys()),n=t.find(e=>e?.hasAttribute("data-composite-item-active"))??null,o=n?e.get(n)?.index??-1:-1;if(-1!==o)S(o);else if(ad(t,x,p)){const e=sd(t,{disabledIndices:p});id(t,e)||S(e)}hg(y.current,n,s,r)});Yl(()=>{if(null==p||null!=a||!w.current)return;const e=b.current;if(ad(e,x,p)){const t=sd(e,{disabledIndices:p});id(e,t)||S(t)}},[p,a,x,b,S]);const _=uu((e,t,n)=>i?i(e,t,n,b):n),E=uu(e=>{const t="Home"===e.key||"End"===e.key;if(!ug.has(e.key)||!u&&t)return;if(function(e,t){for(const n of dg)if(!t.includes(n)&&e.getModifierState(n))return!0;return!1}(e,h))return;if(!y.current)return;const a="rtl"===s,c=a?cg:lg,l=a?lg:cg,f="vertical"===r?ag:c,m="vertical"===r?sg:l,v=Xu(e.nativeEvent);if(null!=v&&pg(v)&&(null!=(w=v)&&!w.hasAttribute("disabled")&&"true"!==w.getAttribute("aria-disabled"))){const t=v.selectionStart,n=v.selectionEnd,r=v.value;if(null==t||e.shiftKey||t!==n)return;if(e.key!==m&&t<r.length)return;if(e.key!==f&&t>0)return}var w;let k=x;const E=function(e,t){return sd(e.current,{disabledIndices:t})}(b,p),C=function(e,t){return sd(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}(b,p);null!=o&&(k=o({disabledIndices:p,elementsRef:b,event:e,highlightedIndex:x,loopFocus:n,maxIndex:C,minIndex:E,onLoop:_,orientation:r,rtl:a}));const I="vertical"!==r&&e.key===c||"horizontal"!==r&&"ArrowDown"===e.key,T="vertical"!==r&&e.key===l||"horizontal"!==r&&"ArrowUp"===e.key;u&&("Home"===e.key?k=E:"End"===e.key&&(k=C)),k===x&&(I||T)&&(n&&k===C&&I?(k=E,i&&(k=i(e,x,k,b))):n&&k===E&&T?(k=C,i&&(k=i(e,x,k,b))):k=sd(b.current,{startingIndex:k,decrement:T,disabledIndices:p})),k===x||id(b.current,k)||(d&&e.stopPropagation(),(g||t||I||T)&&e.preventDefault(),S(k,!0),queueMicrotask(()=>{b.current[k]?.focus()}))});return{props:{ref:v,onFocus(e){const t=y.current,n=Xu(e.nativeEvent);t&&null!=n&&pg(n)&&n.setSelectionRange(0,n.value.length)},onKeyDown:E},highlightedIndex:x,onHighlightedIndexChange:S,elementsRef:b,onMapChange:k,relayKeyboardEvent:E}}function vg(t){const{render:n,className:r,style:o,refs:i=Bl,props:s=Bl,state:a=Hl,stateAttributesMapping:c,highlightedIndex:l,onHighlightedIndexChange:u,orientation:d,grid:p,loopFocus:h,onLoop:f,enableHomeAndEndKeys:m,onMapChange:g,stopEventPropagation:v=!0,rootRef:b,disabledIndices:w,modifierKeys:x,highlightItemOnHover:S=!1,tag:k="div",..._}=t,E=e.useContext(Oh)?.direction??"ltr",{props:C,highlightedIndex:I,onHighlightedIndexChange:T,elementsRef:M,onMapChange:O,relayKeyboardEvent:R}=yg({grid:p,loopFocus:h,onLoop:f,orientation:d,highlightedIndex:l,onHighlightedIndexChange:u,rootRef:b,stopEventPropagation:v,enableHomeAndEndKeys:m,direction:E,disabledIndices:w,modifierKeys:x}),z=ep(k,t,{state:a,ref:i,props:[C,...s,_],stateAttributesMapping:c}),A=e.useMemo(()=>({highlightedIndex:I,onHighlightedIndexChange:T,highlightItemOnHover:S,relayKeyboardEvent:R}),[I,T,S,R]);/*#__PURE__*/
31
- return y(Ep.Provider,{value:A,children:/*#__PURE__*/y(Wm,{elementsRef:M,onMapChange:e=>{g?.(e),O(e)},children:z})})}var bg=/*#__PURE__*/e.forwardRef(function(t,n){const{activateOnFocus:r=!1,className:o,loopFocus:i=!0,render:s,style:a,...c}=t,{orientation:l,setTabMap:u,tabActivationDirection:d}=Ym(),[p,h]=e.useState(0),[f,m]=e.useState(null),g=e.useRef(/* @__PURE__ */new Set),v=e.useRef(/* @__PURE__ */new Set),b=e.useRef(null);Yl(()=>{if("undefined"==typeof ResizeObserver)return;const e=new ResizeObserver(()=>{g.current.forEach(e=>{e()})});return b.current=e,f&&e.observe(f),v.current.forEach(t=>{e.observe(t)}),()=>{e.disconnect(),b.current=null}},[f]);const w=uu(e=>(g.current.add(e),()=>{g.current.delete(e)})),x=uu(e=>(v.current.add(e),b.current?.observe(e),()=>{v.current.delete(e),b.current?.unobserve(e)})),S={orientation:l,tabActivationDirection:d},k={"aria-orientation":"vertical"===l?"vertical":void 0,role:"tablist"},_=e.useMemo(()=>({activateOnFocus:r,registerIndicatorUpdateListener:w,registerTabResizeObserverElement:x,tabsListElement:f}),[r,w,x,f]);/*#__PURE__*/
32
- return y(ng.Provider,{value:_,children:/*#__PURE__*/y(vg,{render:s,className:o,style:a,state:S,refs:[n,m],props:[k,c],stateAttributesMapping:Km,highlightedIndex:p,enableHomeAndEndKeys:!0,loopFocus:i,orientation:l,onHighlightedIndexChange:h,onMapChange:u,disabledIndices:Bl})})});function wg(e){const t=e.getRootNode();return(t instanceof ShadowRoot?t.activeElement:document.activeElement)??null}function xg(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!e.hasAttribute("aria-hidden"))}var Sg=360,kg=450;function _g(e,t,n){return Math.min(Math.max(e,t),n)}function Eg({width:e,height:t}){return{width:_g(e,280,600),height:_g(t,320,Math.floor(.85*window.innerHeight))}}function Cg(e,t){const n=/^\s*(\d+(?:\.\d+)?)px\s*$/.exec(e??"");return n?Number(n[1]):t}var Ig={"top-left":{growX:-1,growY:-1,cursor:"nwse-resize"},"top-right":{growX:1,growY:-1,cursor:"nesw-resize"},"bottom-left":{growX:-1,growY:1,cursor:"nesw-resize"},"bottom-right":{growX:1,growY:1,cursor:"nwse-resize"}};function Tg(e,t,n,r){const o=`marketrix_widget_size_${n}`,s=d(null),[a,c]=p(()=>function(e){try{const t=JSON.parse(aa(e)??"null");return"number"!=typeof t?.width||"number"!=typeof t?.height?null:Eg({width:t.width,height:t.height})}catch(ko){return console.warn("[useResize] Ignoring an unparseable stored size:",ko),null}}(o)??Eg({width:Cg(e,Sg),height:Cg(t,kg)})),l=d(a);l.current=a;const u=i(e=>t=>{if(t.preventDefault(),t.stopPropagation(),r)return;const n=t.clientX,i=t.clientY,a=l.current.width,u=l.current.height,{growX:d,growY:p,cursor:h}=Ig[e];s.current&&(s.current.dataset.resizing="true");const f=e=>{const t=Eg({width:a+(e.clientX-n)*d,height:u+(e.clientY-i)*p});l.current=t,s.current&&(s.current.style.width=`${t.width}px`,s.current.style.height=`${t.height}px`)},m=()=>{if(document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",m),document.body.style.cursor="",document.body.style.userSelect="",s.current&&delete s.current.dataset.resizing,c({...l.current}),!r){const{width:e,height:t}=l.current;ca(o,JSON.stringify({width:e,height:t}))}};document.body.style.cursor=h,document.body.style.userSelect="none",document.addEventListener("mousemove",f),document.addEventListener("mouseup",m)},[r,o]);return{widthPx:`${a.width}px`,heightPx:`${a.height}px`,onResizeStart:u,containerRef:s}}var Mg=({title:e,subtitle:t,onClose:n,controls:r})=>/* @__PURE__ */v(uf,{align:"center",justify:"between",paddingX:"lg",paddingY:"md",border:"bottom",shrink:!1,elevation:"section",children:[/* @__PURE__ */v(uf,{align:"center",gap:"md",minWidth:"0",grow:!0,children:[/* @__PURE__ */y(nf,{src:$h,alt:"",size:"md",rounded:"theme",elevation:"card"}),/* @__PURE__ */v(mf,{minWidth:"0",children:[/* @__PURE__ */y(bf,{size:"sm",weight:"semibold",truncate:!0,leading:"tight",children:e}),null!=t&&/* @__PURE__ */y(bf,{as:"p",size:"xs",variant:"muted",truncate:!0,children:t})]})]}),/* @__PURE__ */v(uf,{align:"center",gap:"2xs",shrink:!1,children:[r,/* @__PURE__ */y(ff,{size:"sm",label:"Close",onClick:n,children:/* @__PURE__ */y(hf,{name:"close",size:16})})]})]});function Og(e){const t=d(e);return t.current=e,t}function Rg({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,onAddMessage:r,onUpdateMessage:o,onRemoveMessage:i,onSendMessage:s,pendingMessage:l,setPendingMessage:u}){const[d,h]=p(!1),[f,m]=p(null),[g,y]=p(null),[v,b]=p(!1),w=Og(d),x=Og(f),S=Og(e),k=e=>{e&&i?.(e),r(Of("Stopped screenshare","show","user","stopped-sharing")),m(null)},_=Og(k);a(()=>{const e=()=>{const e=null!==Yf(),t=w.current,n=x.current;e!==t&&(w.current=e,h(e),S.current?.(e)),t&&!e&&n&&_.current(n)};e();const t=setInterval(e,1e3);return()=>clearInterval(t)},[]);const E=()=>{b(!0)},C=()=>{if(!l)return;const e=l;u(null),s(e.content,e.mode,e.alreadyAdded)},I=e=>{g&&(o(g,{screenShareStatus:e}),y(null))},T=async()=>{try{const t=await Kf();h(!0),e?.(!0),I("allowed"),r(Of("Started screenshare","show","user","started-screenshare"));const n=((e,t="show")=>If("screenshare","user","",{mode:t,videoStream:e}))(t,"show");m(n.id),r(n)}catch(ko){console.error("Failed to start screen sharing:",ko),h(!1),e?.(!1),I("denied")}C()},M=T,O=()=>{Vf&&(Vf.getTracks().forEach(e=>e.stop()),Vf=null),h(!1),e?.(!1),k(f)};return c(t,()=>E),c(n,()=>O),{isScreenSharing:d,isAwaitingScreenAccess:null!==g,showScreenAccessDialog:v,handleScreenAccessDialogAllow:async()=>{b(!1),await T()},handleScreenAccessDialogDismiss:()=>{b(!1)},handleScreenAccessRequestAllow:M,handleScreenAccessRequestDeny:()=>{I("denied"),C()},requestScreenAccess:e=>{if(g)return;const t=(e=>If("screen-access-request","agent","Can I take a look at your screen?",{mode:e,isScreenAccessRequest:!0}))(e);y(t.id),r(t)}}}function zg(...e){return t=>{e.forEach(e=>{"function"==typeof e?e(t):e&&(e.current=t)})}}function Ag({value:e,onChange:t,onSubmit:n,modes:r=[],activeMode:o,onModeChange:s,disabled:c=!1,taskRunning:l=!1,onStop:u,ref:p}){const h=d(null);a(()=>{const e=h.current;if(!e)return;e.style.height="auto";const{scrollHeight:t}=e;e.style.height=`${Math.min(t,66)}px`,e.style.overflowY=t>66?"auto":"hidden"},[e]);const f=i(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())},[n]),m=Boolean(e.trim())&&!c;/* @__PURE__ */
33
- return v(mf,{background:"card",rounded:"xl",border:!0,overflow:"hidden",className:"mtx-composer",children:[/* @__PURE__ */y("textarea",{ref:zg(h,p),value:e,onChange:e=>t(e.target.value),onKeyDown:f,placeholder:"Ask anything",disabled:c,rows:1,className:"mtx-composer-input",style:{lineHeight:"20px",paddingTop:"4px",paddingBottom:"2px",minHeight:"unset"}}),/* @__PURE__ */v(uf,{align:"center",justify:"between",paddingX:"sm",paddingTop:"xs",paddingBottom:"sm",children:[/* @__PURE__ */y(uf,{align:"center",gap:"xs",children:r.map(e=>{const t=o===e.id;/* @__PURE__ */
34
- return v("button",{type:"button",className:"mtx-mode-chip","data-active":t?"true":"false",onClick:t=>{t.preventDefault(),t.stopPropagation(),s?.(e.id)},children:[/* @__PURE__ */y(hf,{name:e.icon,size:12}),/* @__PURE__ */y(bf,{as:"span",inheritColor:!0,children:e.label})]},e.id)})}),/* @__PURE__ */y(ff,{variant:l?"secondary":"primary",size:"sm",disabled:!l&&!m,label:l?"Stop the assistant":"Send message",onClick:e=>{e.preventDefault(),e.stopPropagation(),l&&u?u():n()},children:/* @__PURE__ */y(hf,l?{name:"stop",size:14}:{name:"send",size:16})})]})]})}var Pg=/*#__PURE__*/e.createContext(void 0);function Ng(t){const n=e.useContext(Pg);if(!t&&void 0===n)throw new Error(Xl(27));return n}var Dg=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,forceRender:i=!1,...s}=e,a=Ng(),c=a.useState("open"),l=a.useState("nested"),u=a.useState("mounted");return ep("div",e,{state:{open:c,transitionStatus:a.useState("transitionStatus")},ref:[a.context.backdropRef,t],stateAttributesMapping:Nh,props:[{role:"presentation",hidden:!u,style:{userSelect:"none",WebkitUserSelect:"none"}},s],enabled:i||!l})}),$g=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=Ng(),c=Qm(i);return a.useSyncedValueWithCleanup("descriptionElementId",c),ep("p",e,{ref:t,props:[{id:c},s]})}),Lg=/*#__PURE__*/e.createContext(void 0);var Fg={...Ph,...lp,nestedDialogOpen:e=>e?{"data-nested-dialog-open":""}:null},jg=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,finalFocus:s,initialFocus:a,...c}=t,l=Ng(),u=l.useState("descriptionElementId"),d=l.useState("disablePointerDismissal"),p=l.useState("floatingRootContext"),h=l.useState("popupProps"),f=l.useState("modal"),m=l.useState("mounted"),g=l.useState("nested"),v=l.useState("nestedOpenDialogCount"),b=l.useState("open"),w=l.useState("openMethod"),x=l.useState("titleElementId"),S=l.useState("transitionStatus"),k=l.useState("role"),_=p.useState("floatingId");!function(){const t=e.useContext(Lg);if(void 0===t)throw new Error(Xl(26))}(),dp({open:b,ref:l.context.popupRef,onComplete(){b&&l.context.onOpenChangeComplete?.(!0)}});const E=void 0===a?(C=l.context.popupRef,e=>"touch"!==e||C.current):a;var C;const I=v>0,T=l.useStateSetter("popupElement"),M=ep("div",t,{state:{open:b,nested:g,transitionStatus:S,nestedDialogOpen:I},props:[h,{id:_,"aria-labelledby":x,"aria-describedby":u,role:k,...wh,hidden:!m,onKeyDown(e){ug.has(e.key)&&e.stopPropagation()},style:{"--nested-dialogs":v}},c],ref:[n,l.context.popupRef,T],stateAttributesMapping:Fg});/*#__PURE__*/
35
- return y(fh,{context:p,openInteractionType:w,disabled:!m,closeOnFocusOut:!d,initialFocus:E,returnFocus:s,modal:!1!==f,restoreFocus:"popup",children:M})}),Ug=/*#__PURE__*/e.forwardRef(function(e,t){const{cutout:n,...r}=e;let o;if(n){const e=n.getBoundingClientRect();o=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${e.left}px ${e.top}px,${e.left}px ${e.bottom}px,${e.right}px ${e.bottom}px,${e.right}px ${e.top}px,${e.left}px ${e.top}px)`}/*#__PURE__*/
36
- return y("div",{ref:t,role:"presentation","data-base-ui-inert":"",...r,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:o}})}),Wg=/*#__PURE__*/e.forwardRef(function(e,t){const{keepMounted:n=!1,...r}=e,o=Ng(),i=o.useState("mounted"),s=o.useState("modal"),a=o.useState("open");return i||n?/*#__PURE__*/y(Lg.Provider,{value:n,children:/*#__PURE__*/v(Up,{ref:t,...r,children:[i&&!0===s&&/*#__PURE__*/y(Ug,{ref:o.context.internalBackdropRef,inert:rp(!a)}),e.children]})}):null}),Bg={},Hg={},Zg="";function qg(e,t){return function(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Su(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==o&&"contents"!==o}(e)?e:t}function Vg(e,t,n){return/hidden|clip/.test(e.getComputedStyle(qg(t,n)).overflowY)}function Yg(e){const t=Eu(e),n=t.documentElement,r=t.body,o=gu(n);let i=0,s=0,a=!1;const c=Mu.create();if(Zu&&1!==(o.visualViewport?.scale??1))return()=>{};function l(){const t=o.getComputedStyle(n),c=o.getComputedStyle(r),l=(t.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";i=n.scrollTop,s=n.scrollLeft,Bg={scrollbarGutter:n.style.scrollbarGutter,overflowY:n.style.overflowY,overflowX:n.style.overflowX},Zg=n.style.scrollBehavior,Hg={position:r.style.position,height:r.style.height,width:r.style.width,boxSizing:r.style.boxSizing,overflowY:r.style.overflowY,overflowX:r.style.overflowX,scrollBehavior:r.style.scrollBehavior};const u=n.scrollHeight>n.clientHeight,d=n.scrollWidth>n.clientWidth,p="scroll"===t.overflowY||"scroll"===c.overflowY,h="scroll"===t.overflowX||"scroll"===c.overflowX,f=Math.max(0,o.innerWidth-r.clientWidth),m=Math.max(0,o.innerHeight-r.clientHeight),g=parseFloat(c.marginTop)+parseFloat(c.marginBottom),y=parseFloat(c.marginLeft)+parseFloat(c.marginRight),v=qg(n,r);if(a=function(e){if("undefined"==typeof CSS||!CSS.supports||!CSS.supports("scrollbar-gutter","stable")||"undefined"==typeof document)return!1;const t=Eu(e),n=t.documentElement,r=qg(n,t.body),o=r.style.overflowY,i=n.style.scrollbarGutter;n.style.scrollbarGutter="stable",r.style.overflowY="scroll";const s=r.offsetWidth;r.style.overflowY="hidden";const a=r.offsetWidth;return r.style.overflowY=o,n.style.scrollbarGutter=i,s===a}(e),a)return n.style.scrollbarGutter=l,v.style.overflowY="hidden",void(v.style.overflowX="hidden");Object.assign(n.style,{scrollbarGutter:l,overflowY:"hidden",overflowX:"hidden"}),(u||p)&&(n.style.overflowY="scroll"),(d||h)&&(n.style.overflowX="scroll"),Object.assign(r.style,{position:"relative",height:g||m?`calc(100dvh - ${g+m}px)`:"100dvh",width:y||f?`calc(100vw - ${y+f}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),r.scrollTop=i,r.scrollLeft=s,n.setAttribute("data-base-ui-scroll-locked",""),n.style.scrollBehavior="unset"}function u(){Object.assign(n.style,Bg),Object.assign(r.style,Hg),a||(n.scrollTop=i,n.scrollLeft=s,n.removeAttribute("data-base-ui-scroll-locked"),n.style.scrollBehavior=Zg)}l();const d=Cu(o,"resize",function(){u(),c.request(l)});return()=>{c.cancel(),u(),"function"==typeof o.removeEventListener&&d()}}var Kg=new class{lockCount=0;restore=null;timeoutLock=Ru.create();timeoutUnlock=Ru.create();acquire(e){return this.lockCount+=1,1===this.lockCount&&null===this.restore&&this.timeoutLock.start(0,()=>this.lock(e)),this.release}release=()=>{this.lockCount-=1,0===this.lockCount&&this.restore&&this.timeoutUnlock.start(0,this.unlock)};unlock=()=>{0===this.lockCount&&this.restore&&(this.restore?.(),this.restore=null)};lock(e){if(0===this.lockCount||null!==this.restore)return;const t=Eu(e),n=t.documentElement,r=t.body,o=gu(n);if(Vg(o,n,r)){const t=new o.MutationObserver(()=>{Vg(o,n,r)||(t.disconnect(),this.restore=null,this.lock(e))}),i={attributes:!0};return t.observe(n,i),t.observe(r,i),void(this.restore=()=>t.disconnect())}const i=ju||!function(e){if("undefined"==typeof document)return!1;const t=Eu(e);return gu(t).innerWidth-t.documentElement.clientWidth>0}(e);this.restore=i?function(e){const t=Eu(e),n=qg(t.documentElement,t.body),r={overflowY:n.style.overflowY,overflowX:n.style.overflowX};return Object.assign(n.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(n.style,r)}}(e):Yg(e)}};function Jg({store:t,parentContext:n,isDrawer:r}){const o=t.useState("open"),i=t.useState("disablePointerDismissal"),s=t.useState("modal"),a=t.useState("popupElement"),c=t.useState("floatingRootContext"),[l,u]=e.useState(0),[d,p]=e.useState(0),h=0===l,f=gh(c,{outsidePressEvent:()=>t.context.internalBackdropRef.current||t.context.backdropRef.current?"intentional":{mouse:"trap-focus"===s?"sloppy":"intentional",touch:"sloppy"},outsidePress(e){if(!t.context.outsidePressEnabledRef.current)return!1;if("button"in e&&0!==e.button)return!1;if("touches"in e)if("touchend"===e.type){if(1!==e.changedTouches.length||0!==e.touches.length)return!1}else if(1!==e.touches.length)return!1;const n=Xu(e);if(h&&!i){if(s){const e=t.context.internalBackdropRef.current,r=t.context.backdropRef.current;return!e&&!r||(e===n||r===n||Ju(n,a)&&!n?.hasAttribute("data-base-ui-portal"))}return!0}return!1},escapeKey:h});return function(e=!0,t=null){Yl(()=>{if(e)return Kg.acquire(t)},[e,t])}(o&&!0===s,a),t.useContextCallback("onNestedDialogOpen",(e,t)=>{u(e),p(t)}),Yl(()=>(n?.onNestedDialogOpen&&(o?n.onNestedDialogOpen(l+1,d+(r?1:0)):n.onNestedDialogOpen(0,0)),()=>{n?.onNestedDialogOpen&&o&&n.onNestedDialogOpen(0,0)}),[r,o,l,d,n]),function(e,t){e.useSyncedValues(t),Yl(()=>()=>{e.update({activeTriggerProps:Hl,inactiveTriggerProps:Hl,popupProps:Hl})},[e])}(t,{activeTriggerProps:f.reference,inactiveTriggerProps:f.trigger,popupProps:f.floating,nestedOpenDialogCount:l,nestedOpenDrawerCount:d}),null}var Xg={...Mh,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role},Gg=class extends hu{constructor(t,n,r){const o=new kh,i=function(e,t,n,r=!1){const o={..._h(),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e};return o.floatingRootContext=function(e,t,n=!1){return new vh({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:n,onOpenChange:void 0})}(t,n,r),o}(t,o,n,r);super(i,function(t){return{popupRef:/*#__PURE__*/e.createRef(),backdropRef:/*#__PURE__*/e.createRef(),internalBackdropRef:/*#__PURE__*/e.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:t,onOpenChange:void 0,onOpenChangeComplete:void 0}}(o),Xg)}setOpen=(e,t)=>{if(t.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},e||null!=t.trigger||null==this.state.activeTriggerId||(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);const n={open:e};!function(e,t,n,r=!1){t?e.preventUnmountingOnClose=!1:r&&(e.preventUnmountingOnClose=!0);const o=n?.id??null;(o||t)&&(e.activeTriggerId=o,e.activeTriggerElement=n??null)}(n,e,t.trigger),this.update(n)}};function Qg(t,n){const{children:r,open:o,defaultOpen:i=!1,onOpenChange:s,onOpenChangeComplete:a,disablePointerDismissal:c=!1,modal:l=!0,actionsRef:u,handle:d,triggerId:p,defaultTriggerId:h=null}=n,f="drawer"===t,m="alert-dialog"===t,g=!!m||l,b=m||c,w=m?"alertdialog":"dialog",x=Ng(!0),S={modal:g,disablePointerDismissal:b,nested:null!=x,role:w},k=xh((e,t)=>new Gg({open:i,openProp:o,activeTriggerId:h,triggerIdProp:p,...S},e,t),!0);k.useControlledProp("openProp",o),k.useControlledProp("triggerIdProp",p),k.useSyncedValues(S),k.useContextCallback("onOpenChange",s),k.useContextCallback("onOpenChangeComplete",a);const _=k.useState("open"),E=k.useState("mounted"),C=k.useState("payload");!function(e,t){Yl(()=>{t||null===e.state.openMethod||e.set("openMethod",null)},[t,e]),Yl(()=>()=>{null!==e.state.openMethod&&e.set("openMethod",null)},[e])}(k,_),function(t,n={}){const{closeOnActiveTriggerUnmount:r=!1}=n,o=e.useRef(null),i=t.useState("open"),s=t.useState("triggerCount"),a=t.useState("activeTriggerId"),c=t.useState("activeTriggerElement");Yl(()=>{if(!i)return o.current=null,void(0!==t.state.triggerCount&&t.set("triggerCount",0));const e=t.context.triggerElements.size,n={};t.state.triggerCount!==e&&(n.triggerCount=e);const s=t.select("activeTriggerId");let a=null;if(s){const e=t.context.triggerElements.getById(s);if(e)o.current=s,e!==t.state.activeTriggerElement&&(n.activeTriggerElement=e);else{for(const[e,r]of t.context.triggerElements.entries())if(r===t.state.activeTriggerElement){n.activeTriggerId=e,n.activeTriggerElement=r,o.current=e;break}void 0===n.activeTriggerId&&(o.current===s?a=s:o.current=null)}}else o.current=null;if(!a&&!s&&1===e){const e=t.context.triggerElements.entries().next();if(!e.done){const[t,r]=e.value;n.activeTriggerId=t,n.activeTriggerElement=r,o.current=t}}void 0===n.triggerCount&&void 0===n.activeTriggerId&&void 0===n.activeTriggerElement||t.update(n),a&&r&&queueMicrotask(()=>{if(t.select("open")&&t.select("activeTriggerId")===a&&!t.context.triggerElements.getById(a)){const e=Np(zp);t.setOpen(!1,e),e.isCanceled||t.update({activeTriggerId:null,activeTriggerElement:null})}})},[i,t,s,a,c,r])}(k);const{forceUnmount:I}=function(e,t,n){const{mounted:r,setMounted:o,transitionStatus:i}=bh(e),s=t.useState("preventUnmountingOnClose"),a=!e&&s;t.useSyncedValues({mounted:r,transitionStatus:i,preventUnmountingOnClose:a});const c=uu(()=>{o(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),n?.(),t.context.onOpenChangeComplete?.(!1)});return dp({enabled:r&&!e&&!a,open:e,ref:t.context.popupRef,onComplete(){e||c()}}),{forceUnmount:c,transitionStatus:i}}(_,k);e.useImperativeHandle(u,()=>({unmount:I,close:()=>k.setOpen(!1,Np("imperative-action"))}),[I,k]);const T=_||E;/*#__PURE__*/
37
- return v(Pg.Provider,{value:k,children:[d&&/*#__PURE__*/y(Sh,{handle:d,store:k}),T&&/*#__PURE__*/y(Jg,{store:k,parentContext:x?.context,isDrawer:f}),"function"==typeof r?r({payload:C}):r]})}function ey(e){return Qg("dialog",e)}var ty=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=Ng(),c=Qm(i);return a.useSyncedValueWithCleanup("titleElementId",c),ep("h2",e,{ref:t,props:[{id:c},s]})}),ny=({open:e,onClose:t,title:n,description:r,onConfirm:o,confirmLabel:i="Confirm",cancelLabel:a="Cancel",finalFocusRef:c})=>{const l=s(bm)??document.body;/* @__PURE__ */
38
- return y(ey,{open:e,onOpenChange:(e,n)=>{e||"none"===n.reason||t()},children:/* @__PURE__ */v(Wg,{container:l,children:[/* @__PURE__ */y(Dg,{className:"mtx-dialog-backdrop",style:{zIndex:qh}}),/* @__PURE__ */v(jg,{className:"mtx-dialog-popup",finalFocus:c,style:{...Bh("panel"),zIndex:qh},children:[
39
- /* @__PURE__ */y(ty,{className:"mtx-dialog-title",children:n}),null!=r&&/* @__PURE__ */y($g,{className:"mtx-dialog-description",children:r}),
40
- /* @__PURE__ */v(uf,{gap:"md",justify:"end",children:[/* @__PURE__ */y(sf,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),t()},children:a}),/* @__PURE__ */y(sf,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),o?.()},children:i})]})]})]})})},ry={sm:{width:"14px",height:"14px",borderWidth:"1.5px"},md:{width:"20px",height:"20px",borderWidth:"2px"},lg:{width:"24px",height:"24px",borderWidth:"2px"}};function oy({size:e="md",style:t,ref:n}){/* @__PURE__ */
41
- return v("div",{ref:n,"data-size":e,role:"status",style:{display:"inline-flex",alignItems:"center",gap:"6px",...t},children:[/* @__PURE__ */y("div",{"aria-hidden":"true",className:"mtx-spinner-ring",style:ry[e]}),/* @__PURE__ */y("span",{className:"mtx-visually-hidden",children:"Loading"})]})}var iy=({isWaitingForUser:e})=>/* @__PURE__ */v(uf,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */y(oy,{size:"sm"}),/* @__PURE__ */y(bf,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),sy=({message:e,isLastMessage:t})=>{const{isTaskRunning:n}=Om().state,r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return e.parts.length>0?/* @__PURE__ */v(mf,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */y(bf,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap",marginBottom:"4px"},children:e.content},`part-${t}`):null:"progress"===e.type?/* @__PURE__ */y(uf,{align:"start",gap:"md",children:/* @__PURE__ */y(bf,{as:"span",size:"xs",weight:"medium",style:{flex:1,whiteSpace:"pre-wrap"},children:e.content})},`part-${t}`):null),(e.isPlaceholder&&!e.parts.some(e=>"text"===e.type)||o)&&/* @__PURE__ */y(iy,{isWaitingForUser:r})]}):e.isPlaceholder||n&&t&&("show"===e.mode||"do"===e.mode)?/* @__PURE__ */y(iy,{isWaitingForUser:r}):e.content?/* @__PURE__ */y(bf,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap"},children:e.content}):/* @__PURE__ */y(lf,{})},ay={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},cy=({status:e})=>{const{name:t,opacity:n}=ay[e];/* @__PURE__ */
42
- return y(hf,{name:t,size:14,style:{color:Em(Mm().widget_accent_color,n),flexShrink:0}})},ly="8px 8px 0 0",uy=({label:e,children:t})=>/* @__PURE__ */y(uf,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"#111827",borderRadius:ly,zIndex:10},children:/* @__PURE__ */v(uf,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */y(bf,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),dy=({stream:e})=>{const t=d(null),n=d(null),[r,o]=p(!1),[i,s]=p(!1),c=()=>{n.current?.catch(()=>{}),n.current=null};return a(()=>{if(t.current&&e){const r=t.current;o(!1),s(!1),c(),r.srcObject=e;const i=()=>{o(!0)},a=()=>{s(!0),o(!1)};r.addEventListener("loadedmetadata",i),r.addEventListener("error",a);const l=r.play();return n.current=l,l.then(()=>{o(!0)}).catch(e=>{e instanceof Error&&"AbortError"!==e.name&&(console.error("Error playing video stream:",e),s(!0)),n.current=null}),()=>{r.removeEventListener("loadedmetadata",i),r.removeEventListener("error",a)}}return()=>{c(),t.current&&(t.current.srcObject=null),o(!1),s(!1)}},[e]),e?/* @__PURE__ */v(lf,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:ly,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&&!i&&/* @__PURE__ */y(uy,{label:"Loading stream...",children:/* @__PURE__ */y(oy,{size:"lg",style:{color:"white"}})}),i&&/* @__PURE__ */y(uy,{label:"Failed to load stream",children:/* @__PURE__ */y(hf,{name:"alertCircle",size:32,style:{color:"#9ca3af"}})}),
43
- /* @__PURE__ */y("video",{ref:t,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"auto",maxHeight:"192px",objectFit:"contain",borderRadius:ly,transition:"opacity 500ms",opacity:r?1:0,minHeight:"120px",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"}}),r&&!i&&/* @__PURE__ */v(uf,{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__ */v(uf,{position:"relative",align:"center",justify:"center",children:[/* @__PURE__ */y(lf,{position:"absolute",rounded:"full",animate:"ping",style:{width:"8px",height:"8px",backgroundColor:"white",opacity:.75}}),/* @__PURE__ */y(lf,{position:"relative",rounded:"full",style:{width:"6px",height:"6px",backgroundColor:"white"}})]}),/* @__PURE__ */y(bf,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
44
- /* @__PURE__ */y(uf,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:ly,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */y(lf,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */y(bf,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]}):null},py=({message:e,index:t,isLastMessage:n,onScreenAccessAllow:r,onScreenAccessDeny:o})=>{if(e.isSystemMessage)/* @__PURE__ */return y(uf,{justify:"center",align:"center",children:/* @__PURE__ */y(bf,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})},`message-${e.id}-${t}`);const i="user"===e.sender,s=i?"show"===e.mode||"do"===e.mode?"mousePointerClick":void 0:e.isScreenAccessRequest||"waiting-for-user"===e.placeholderState?"checkCircle":void 0;/* @__PURE__ */
45
- return v(mf,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":i?"You said…":"Agent says…",animate:n?"fadeIn":void 0,children:[/* @__PURE__ */v(uf,{align:"start",gap:"sm",width:"full",children:[
46
- /* @__PURE__ */y(uf,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!i&&/* @__PURE__ */y(nf,{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%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"}})}),
47
- /* @__PURE__ */v(mf,{grow:!0,position:"relative",rounded:"theme",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:i?"var(--primary)":void 0,color:i?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */y(dy,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */v(uf,{align:"start",gap:"sm",children:[/* @__PURE__ */y(uf,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */y(hf,{name:s,size:13})}),/* @__PURE__ */y(mf,{grow:!0,children:/* @__PURE__ */y(sy,{message:e,isLastMessage:n})})]}):/* @__PURE__ */y(sy,{message:e,isLastMessage:n})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */v(uf,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */y(sf,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"Yes"}),/* @__PURE__ */y(sf,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>o?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */y(bf,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"Check HTML Instead"}),!i&&e.taskStatus&&/* @__PURE__ */y(uf,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */y(cy,{status:e.taskStatus})})]}),
48
- /* @__PURE__ */y(uf,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */y(bf,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:Pf(e.timestamp)})]},`message-${e.id}-${t}`)},hy={boxShadow:Lh.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},fy=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=Mm(),{state:o,actions:i}=Om(),{messages:s}=o,c=r.isPreviewMode??!1,[l,h]=p(!1),[f,m]=p(!1),g=d(null),b=u(()=>({id:"welcome",content:r.widget_body,sender:"agent",timestamp:/* @__PURE__ */new Date,isPlaceholder:!1,parts:[]}),[r.widget_body]),w=u(()=>[b,...s],[b,s]),x=()=>{if(g.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=g.current;h(e>200);const r=Math.abs(t-e-n)<50;m(!r&&t>n)}};a(()=>{window.requestAnimationFrame(()=>{e.current&&(!c&&e.current.scrollIntoView({behavior:"auto"}),!c&&x())})},[s.length,c]);const S=s[s.length-1]?.content?.length??0;return a(()=>{const t=g.current;t&&!c&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[S,c,e]),/* @__PURE__ */v(lf,{position:"relative",height:"full",children:[
49
- /* @__PURE__ */v(lf,{ref:g,onScroll:x,role:"log","aria-relevant":"additions",height:"full",overflowY:"auto",paddingX:"lg",paddingY:"sm",style:{backgroundColor:r.widget_background_color.includes("gradient")?"transparent":r.widget_background_color,backgroundImage:r.widget_background_color.includes("gradient")?r.widget_background_color:`linear-gradient(135deg, ${r.widget_background_color} 0%, ${r.widget_background_color} 100%)`,scrollbarColor:`${Em(r.widget_border_color,.3)} ${Em(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[w.map((e,r)=>/* @__PURE__ */y(py,{message:e,index:r,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */y(uf,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */y(sf,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */y(bf,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
50
- /* @__PURE__ */y(lf,{ref:e},"scroll-anchor")]},"message-list-container"),l&&/* @__PURE__ */y(uf,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */y(ff,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{g.current?.scrollTo({top:0,behavior:"smooth"})},style:hy,children:/* @__PURE__ */y(hf,{name:"arrowUp",size:10,style:{color:r.widget_accent_color}})})}),f&&/* @__PURE__ */y(uf,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */y(ff,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{e.current&&!c&&e.current.scrollIntoView({behavior:"smooth"})},style:hy,children:/* @__PURE__ */y(hf,{name:"arrowDown",size:10,style:{color:r.widget_accent_color}})})})]})},my=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],gy=({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,messageInputRef:r})=>{const o=Mm(),{state:i,actions:s}=Om(),{currentMode:a,isTaskRunning:c,isAwaitingReply:l}=i,[u,h]=p(""),f=d(null),[m,g]=p(null),{isScreenSharing:b,isAwaitingScreenAccess:w,showScreenAccessDialog:x,handleScreenAccessDialogAllow:S,handleScreenAccessDialogDismiss:k,handleScreenAccessRequestAllow:_,handleScreenAccessRequestDeny:E,requestScreenAccess:C}=Rg({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,onAddMessage:s.addMessage,onUpdateMessage:s.updateMessage,onRemoveMessage:s.removeMessage,onSendMessage:s.messageDispatch,pendingMessage:m,setPendingMessage:g}),I=w||l;/* @__PURE__ */
51
- return v(mf,{height:"full",children:[x&&/* @__PURE__ */y(ny,{open:x,onClose:k,title:"Can I take a look at your screen?",description:"By allowing screen access, Marketrix can understand your current context to guide you better and complete tasks on your behalf.",onConfirm:S,confirmLabel:"Yes",cancelLabel:"No",finalFocusRef:r}),
52
- /* @__PURE__ */y(lf,{grow:!0,overflow:"hidden",paddingY:"2xs",style:{display:"flex",flexDirection:"column",minHeight:0},children:/* @__PURE__ */y($m,{label:"Chat",fallback:/* @__PURE__ */y(bf,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */y(fy,{messagesEndRef:f,onScreenAccessAllow:_,onScreenAccessDeny:E})})}),
53
- /* @__PURE__ */y(lf,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */y(Ag,{ref:r,value:u,onChange:h,onSubmit:()=>{if(!u.trim()||I)return;const e=u.trim();h(""),s.addMessage(Tf(e,a)),!1===o.use_screenshare||"show"!==a&&"do"!==a||b?s.messageDispatch(e,a,!0):(g({content:e,mode:a,alreadyAdded:!0}),C(a))},modes:my.filter(({flag:e})=>o[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:Af(e)})),activeMode:a,onModeChange:e=>{e!==a&&(s.addMessage(Of(`Switched to ${Af(e)} mode`,e,"agent","mode-change")),s.setMode(e))},disabled:I,taskRunning:c,onStop:()=>{Gf.cleanup(),s.stopTask()}})})]})},yy=[{id:"show-add-product",text:"Show me how to add a new product",type:"show"},{id:"show-login",text:"Show me how to login",type:"show"},{id:"do-login",text:"Do the login process for me",type:"do"},{id:"show-revenue",text:"Show me the revenue metrics",type:"show"},{id:"tell-conversion-rate",text:"What does my conversion rate mean and how can I improve it?",type:"tell"}];var vy=({actions:e,onActionClick:t})=>{const n=Mm();return 0===e.length?null:/* @__PURE__ */y(mf,{gap:"sm",children:e.map((e,r)=>/* @__PURE__ */y(sf,{elevation:"card",shape:"theme",size:"sm",variant:"chip",full:!0,onClick:n=>t(e,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */y(bf,{as:"span",weight:"normal",leading:"tight",children:"show"===e.type?/* @__PURE__ */v(g,{children:["Show me ",e.text.replace(/^Show me\s*/i,"")]}):"do"===e.type?/* @__PURE__ */v(g,{children:["Do ",e.text.replace(/^Do\s*/i,"")]}):e.text})},`welcome-chip-${e.id}-${r}`))})},by=({onNavigateToChat:e,onChipClick:t})=>{const n=Mm(),{messages:r}=Om().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>({id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:e.chip_text,type:e.chip_mode})):yy}(n);/* @__PURE__ */
54
- return v(mf,{height:"full",overflow:"hidden",children:[/* @__PURE__ */v(mf,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */v(lf,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */y(bf,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */y(bf,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */v(mf,{gap:"sm",children:[/* @__PURE__ */v(sf,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */y(hf,{name:"chat",size:16}),"Ask a question"]}),/* @__PURE__ */y(vy,{actions:o,onActionClick:async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)}})]})]}),r.length>0&&/* @__PURE__ */v(lf,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px"},children:[
55
- /* @__PURE__ */y(bf,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
56
- /* @__PURE__ */y(bf,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1].content||"Message"}),
57
- /* @__PURE__ */y(bf,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation →"})]})]})};function wy(e){const t=e.startsWith("top"),n=e.endsWith("left");return{position:"absolute",width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:t?"flex-start":"flex-end",justifyContent:n?"flex-start":"flex-end",cursor:Ig[e].cursor,top:t?0:void 0,bottom:t?void 0:0,left:n?0:void 0,right:n?void 0:0}}var xy=({onResizeStart:e})=>/* @__PURE__ */y(g,{children:Object.keys(Ig).map(t=>/* @__PURE__ */y("div",{role:"separator","aria-label":`Resize widget from ${t.replace("-"," ")}`,title:"Drag to resize",style:wy(t),onMouseDown:e(t)},t))}),Sy=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],ky=()=>/* @__PURE__ */y(bg,{render:/* @__PURE__ */y(uf,{align:"center",justify:"around",shrink:!1,border:"top"}),style:{height:48},children:Sy.map(e=>/* @__PURE__ */v(rg,{value:e.id,render:/* @__PURE__ */y(sf,{stacked:!0,variant:"tab"}),children:[
1
+ import*as e from"react";import t,{createContext as n,createElement as r,forwardRef as o,useCallback as i,useContext as s,useEffect as a,useImperativeHandle as c,useLayoutEffect as l,useMemo as d,useRef as u,useState as p,useSyncExternalStore as h}from"react";import{createRoot as f}from"react-dom/client";import*as m from"react-dom";import{Fragment as g,jsx as y,jsxs as b}from"react/jsx-runtime";function v(e){return Array.isArray(e)?e:null==e?[]:[e]}var w="orpc",x=class extends Error{constructor(...e){super(...e),this.name="AbortError"}};function S(e){let t;return()=>{if(t)return t.result;const n=e();return t={result:n},n}}function k(){return globalThis["__@orpc/shared@1.15.0/otel/config__"]}function C(e,t={},n){return(k()?.tracer)?.startSpan(e,t,n)}function E(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 I({name:e,context:t,...n},r){const o=k()?.tracer;if(!o)return r();const i=async e=>{try{return await r(e)}catch(t){throw E(e,t,n),t}finally{e.end()}};return t?o.startActiveSpan(e,n,t,i):o.startActiveSpan(e,n,i)}async function M(e,t){const n=k();if(!e||!n)return t();const r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function T(e){return!(!e||"object"!=typeof e)&&"next"in e&&"function"==typeof e.next&&Symbol.asyncIterator in e&&"function"==typeof e[Symbol.asyncIterator]}var R=Symbol.asyncDispose??Symbol.for("asyncDispose"),O=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[R](){this.#e=!0,this.#t||(this.#t=!0,await this.#n("dispose"))}[Symbol.asyncIterator](){return this}};function A({name:e,...t},n){let r;return new O(async()=>{r??=C(e);try{const e=await M(r,()=>n.next());return r?.addEvent(e.done?"completed":"yielded"),e}catch(o){throw E(r,o,t),o}},async e=>{try{"next"!==e&&await M(r,()=>n.return?.())}catch(o){throw E(r,o,t),o}finally{r?.end()}})}function _(e,t,n){const r=(t,o)=>{const i=e[o];return i?i({...t,next:(e=t)=>r(e,o+1)}):n(t)};return r(t,0)}function D(e){if(e)return JSON.parse(e)}function P(e){return JSON.stringify(e)}function L(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function N(e){return!!e&&("object"==typeof e||"function"==typeof e)}function F(e,...t){return"function"==typeof e?e(...t):e}function z(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)&&B.test(t.toString()));var t}))return Reflect.apply(t,n,r);let o=!0;r[0].call(n,z(new Proxy(e,{get:(e,t,n)=>{if(!o||"then"!==t)return Reflect.get(e,t,n);o=!1}})))}})}})}var $,B=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/,W=/* @__PURE__ */new Set(["bind","valueOf","toString","toJSON"]),U={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"}},H=class e extends Error{defined;code;status;data;static{const t=Symbol.for("__@orpc/client@1.15.0/error/ORPC_ERROR_CONSTRUCTORS__");globalThis[t]??=/* @__PURE__ */new WeakSet,($=globalThis[t]).add(e)}constructor(e,...t){const n=function(e){return e[0]??{}}(t);if(void 0!==n.status&&!j(n.status))throw new Error("[ORPCError] Invalid error status code.");const r=function(e,t){return t||U[e]?.message||e}(e,n.message);super(r,n),this.code=e,this.status=function(e,t){return t??U[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($.has(this)){const t=function(e){return N(e)?Object.getPrototypeOf(e)?.constructor:null}(e);if(t&&$.has(t))return!0}return super[Symbol.hasInstance](e)}};function j(e){return e<200||e>=400}function q(e){if(!L(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&&j(e.status)&&"message"in e&&"string"==typeof e.message}function V(e,t={}){return new H(e.code,{...t,...e})}var Y=class extends TypeError{},K=class extends TypeError{},X=class extends Error{data;constructor(e){super(e?.message??"An error event was received",e),this.data=e?.data}},G=/\r\n|\r(?!\n)|\n/,J=/(?:\r\n|\r(?!\n)|\n){2}/,Z=/(?:\r\n|\r(?!\n)|\n){2}/g;function Q(e){const t={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(const n of e.split(G)){if(""===n)continue;const e=n.indexOf(":"),r=-1===e?"":n.slice(32===n.charCodeAt(e+1)?e+2:e+1);if(0!==e)switch(-1===e?n:n.slice(0,e)){case"data":t.data=void 0===t.data?r:`${t.data}\n${r}`;break;case"event":t.event=r;break;case"id":t.id=r;break;case"retry":{const e=Number.parseInt(r,10);e>=0&&e.toString()===r&&(t.retry=e);break}}else t.comments.push(r)}return t}var ee=class{constructor(e={}){this.options=e}pending=[];tail="";discardLeadingLF=!1;feed(e){if(""===e)return;if(this.discardLeadingLF&&(this.discardLeadingLF=!1,10===e.charCodeAt(0)&&""===(e=e.slice(1))))return;const t=this.tail+e;if(!J.test(t))return this.pending.push(e),void(this.tail=t.slice(-3));this.pending.push(e);const n=1===this.pending.length?e:this.pending.join(""),r=n.length-t.length,o=[];let i=0;for(const a of t.matchAll(Z))o.push(n.slice(i,r+a.index)),i=r+a.index+a[0].length;const s=n.slice(i);this.pending.length=0,this.tail=s.slice(-3),""===s?this.discardLeadingLF=13===e.charCodeAt(e.length-1):this.pending.push(s);for(const a of o){const e=Q(a);this.options.onEvent&&this.options.onEvent(e)}}end(){if(0!==this.pending.length)throw new K("Event Iterator ended before complete")}},te=class extends TransformStream{constructor(){let e;super({start(t){e=new ee({onEvent:e=>{t.enqueue(e)}})},transform(t){e.feed(t)},flush(){e.end()}})}},ne=/\r\n|[\n\r]/,re=/\r\n|[\n\r]/g;function oe(e){return ne.test(e)}function ie(e){if(oe(e))throw new Y("Event's id must not contain a carriage return or newline character")}function se(e){if(!Number.isInteger(e)||e<0)throw new Y("Event's retry must be a integer and >= 0")}function ae(e){if(oe(e))throw new Y("Event's comment must not contain a carriage return or newline character")}function ce(e){let t="";var n;return t+=function(e){let t="";for(const n of e??[])ae(n),t+=`: ${n}\n`;return t}(e.comments),void 0!==e.event&&(function(e){if(oe(e))throw new Y("Event's event must not contain a carriage return or newline character")}(e.event),t+=`event: ${e.event}\n`),void 0!==e.retry&&(se(e.retry),t+=`retry: ${e.retry}\n`),void 0!==e.id&&(ie(e.id),t+=`id: ${e.id}\n`),t+=void 0===(n=e.data)?"":`data: ${n.replace(re,"\ndata: ")}\n`,t+="\n",t}var le=Symbol("ORPC_EVENT_SOURCE_META");function de(e,t){if(void 0===t.id&&void 0===t.retry&&!t.comments?.length)return e;if(void 0!==t.id&&ie(t.id),void 0!==t.retry&&se(t.retry),void 0!==t.comments)for(const n of t.comments)ae(n);return new Proxy(e,{get:(e,n,r)=>n===le?t:Reflect.get(e,n,r)})}function ue(e){return N(e)?Reflect.get(e,le):void 0}function pe(e,t){const n=async e=>{let n=await t.error(e);if(n!==e){const t=ue(e);t&&N(n)&&(n=de(n,t))}return n};return new O(async()=>{const{done:r,value:o}=await(async()=>{try{return await e.next()}catch(t){throw await n(t)}})();let i=await t.value(o,r);if(i!==o){const e=ue(o);e&&N(i)&&(i=de(i,e))}return{done:r,value:i}},async()=>{try{await(e.return?.())}catch(t){throw await n(t)}})}function he(e,t={}){const n=t.path??[];return z(new Proxy(async(...[t,r={}])=>await e.call(n,t,function(e){return{...e,context:e.context??{}}}(r)),{get:(r,o)=>"string"!=typeof o||W.has(o)?Reflect.get(r,o):he(e,{...t,path:[...n,o]})}))}function fe(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}var me=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)}},ge=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new me(n.plugins).init(n),this.interceptors=v(n.interceptors),this.clientInterceptors=v(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return I({name:`${w}.${e.join("/")}`,signal:n.signal},r=>(r?.setAttribute("rpc.system",w),r?.setAttribute("rpc.method",e.join(".")),T(t)&&(t=A({name:"consume_event_iterator_input",signal:n.signal},t)),_(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{const o=k();let i;const s=o?.trace.getActiveSpan()??r;s&&o&&(i=o?.trace.setSpan(o.context.active(),s));const a=await I({name:"encode_request",context:i},()=>this.codec.encode(e,t,n)),c=await _(this.clientInterceptors,{...n,input:t,path:e,request:a},({input:e,path:t,request:n,...r})=>I({name:"send_request",signal:r.signal,context:i},()=>this.sender.call(n,r,t,e))),l=await I({name:"decode_response",context:i},()=>this.codec.decode(c,n,e,t));return T(l)?A({name:"consume_event_iterator_output",signal:n.signal},l):l})))}},ye=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=[],o=[]){for(const i of this.customSerializers)if(i.condition(e)){const s=this.serialize(i.serialize(e),t,n,r,o);return n.push([i.type,...t]),s}if(e instanceof Blob)return r.push(t),o.push(e),[e,n,r,o];if("bigint"==typeof e)return n.push([0,...t]),[e.toString(),n,r,o];if(e instanceof Date)return n.push([1,...t]),Number.isNaN(e.getTime())?[null,n,r,o]:[e.toISOString(),n,r,o];if(Number.isNaN(e))return n.push([2,...t]),[null,n,r,o];if(e instanceof URL)return n.push([4,...t]),[e.toString(),n,r,o];if(e instanceof RegExp)return n.push([5,...t]),[e.toString(),n,r,o];if(e instanceof Set){const i=this.serialize(Array.from(e),t,n,r,o);return n.push([6,...t]),i}if(e instanceof Map){const i=this.serialize(Array.from(e.entries()),t,n,r,o);return n.push([7,...t]),i}if(Array.isArray(e))return[e.map((e,i)=>void 0===e?(n.push([3,...t,i]),null):this.serialize(e,[...t,i],n,r,o)[0]),n,r,o];if(L(e)){const i={};for(const s in e)"toJSON"===s&&"function"==typeof e[s]||(i[s]=this.serialize(e[s],[...t,s],n,r,o)[0]);return[i,n,r,o]}return[e,n,r,o]}deserialize(e,t,n,r){const o={data:e};n&&r&&n.forEach((e,t)=>{let n=o,i="data";e.forEach(e=>{if(n=n[i],i=e,!Object.hasOwn(n,i))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${i}`)}),n[i]=r(t)});for(const i of t){const e=i[0];let t=o,n="data";for(let r=1;r<i.length;r++)if(t=t[n],n=i[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 0:t[n]=BigInt(t[n]);break;case 1:t[n]=new Date(t[n]??"Invalid Date");break;case 2:t[n]=NaN;break;case 3:t[n]=void 0;break;case 4:t[n]=new URL(t[n]);break;case 5:{const[,e,r]=t[n].match(/^\/(.*)\/([a-z]*)$/);t[n]=new RegExp(e,r);break}case 6:t[n]=new Set(t[n]);break;case 7:t[n]=new Map(t[n])}}return o.data}},be=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?fe(e):e}(await F(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]=[...v(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 o=await F(this.expectedMethod,n,e,t),i=await F(this.baseUrl,n,e,t),s=new URL(i);s.pathname=`${s.pathname.replace(/\/$/,"")}${function(e){return`/${e.map(encodeURIComponent).join("/")}`}(e)}`;const a=this.serializer.serialize(t);if(!("GET"!==o||a instanceof FormData||T(a))){const i=await F(this.maxUrlLength,n,e,t),c=new URL(s);if(c.searchParams.append("data",P(a)),c.toString().length<=i)return{body:void 0,method:o,headers:r,url:c,signal:n.signal}}return{url:s,method:"GET"===o?this.fallbackMethod:o,headers:r,body:a,signal:n.signal}}async decode(e){const t=!j(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 V(n);throw new H((r=e.status,Object.entries(U).find(([,e])=>e.status===r)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"),{status:e.status,data:{...e,body:n}})}var r;return n}},ve=class{constructor(e){this.jsonSerializer=e}serialize(e){return T(e)?pe(e,{value:async e=>this.#o(e,!1),error:async e=>{return new X({data:this.#o((t=e,t instanceof H?t:new H("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:t})).toJSON(),!1),cause:e});var t}}):this.#o(e,!0)}#o(e,t){const[n,r,o,i]=this.jsonSerializer.serialize(e),s=0===r.length?void 0:r;if(!t||0===i.length)return{json:n,meta:s};const a=new FormData;return a.set("data",P({json:n,meta:s,maps:o})),i.forEach((e,t)=>{a.set(t.toString(),e)}),a}deserialize(e){return T(e)?pe(e,{value:async e=>this.#i(e),error:async e=>{if(!(e instanceof X))return e;const t=this.#i(e.data);return q(t)?V(t,{cause:e}):new X({data:t,cause:e})}}):this.#i(e)}#i(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()))}},we=class extends ge{constructor(e,t){const n=new ye(t),r=new ve(n);super(new be(r,t),e,t)}},xe=class extends me{initRuntimeAdapter(e){for(const t of this.plugins)t.initRuntimeAdapter?.(e)}},Se=class{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new xe(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=v(e.adapterInterceptors)}async call(e,t,n,r){const o=function(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=function(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:T(e)?(t.set("content-type","text/event-stream"),function(e,t={}){const n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5e3,o=t.eventIteratorKeepAliveComment??"",i=t.eventIteratorInitialCommentEnabled??!0,s=t.eventIteratorInitialComment??"";let a,c,l=!1;return new ReadableStream({start(e){c=C("stream_event_iterator"),i&&e.enqueue(ce({comments:[s]}))},async pull(t){try{n&&(a=setInterval(()=>{t.enqueue(ce({comments:[o]})),c?.addEvent("keepalive")},r));const i=await M(c,()=>e.next());if(clearInterval(a),l)return;const s=ue(i.value);if(!i.done||void 0!==i.value||void 0!==s){const e=i.done?"done":"message";t.enqueue(ce({...s,event:e,data:P(i.value)})),c?.addEvent(e)}i.done&&(t.close(),c?.end())}catch(i){if(clearInterval(a),l)return;i instanceof X?(t.enqueue(ce({...ue(i),event:"error",data:P(i.data)})),c?.addEvent("error"),t.close()):(E(c,i),t.error(i)),c?.end()}},async cancel(){try{l=!0,clearInterval(a),c?.addEvent("cancelled"),await M(c,()=>e.return?.())}catch(t){throw E(c,t),t}finally{c?.end()}}}).pipeThrough(new TextEncoderStream)}(e,n)):(t.set("content-type","application/json"),P(e)):void 0}(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}(e,this.toFetchRequestOptions);return function(e,t={}){return{body:S(()=>function(e,t={}){return I({name:"parse_standard_body",signal:t.signal},async()=>{const n=e.headers.get("content-disposition");if("string"==typeof n){const t=function(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}(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 D(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 te))?.getReader();let r,o=!1;return new O(async()=>{r??=C("consume_event_iterator_stream");try{for(;;){if(void 0===n)return{done:!0,value:void 0};const{done:e,value:t}=await M(r,()=>n.read());if(e){if(o)throw new x("Stream was cancelled");return{done:!0,value:void 0}}switch(t.event){case"message":{let e=D(t.data);return N(e)&&(e=de(e,t)),r?.addEvent("message"),{done:!1,value:e}}case"error":{let e=new X({data:D(t.data)});throw e=de(e,t),r?.addEvent("error"),e}case"done":{let e=D(t.data);return N(e)&&(e=de(e,t)),r?.addEvent("done"),{done:!0,value:e}}default:r?.addEvent("maybe_keepalive")}}}catch(e){throw e instanceof X||E(r,e,t),e}},async e=>{try{"next"!==e&&(o=!0,r?.addEvent("cancelled")),await M(r,()=>n?.cancel())}catch(i){throw E(r,i,t),i}finally{r?.end()}})}(e.body,t);if(r.startsWith("text/plain"))return await e.text();const o=await e.blob();return new File([o],"blob",{type:o.type})})}(e,t)),status:e.status,get headers(){const t=fe(e.headers);return Object.defineProperty(this,"headers",{value:t,writable:!0}),t},set headers(e){Object.defineProperty(this,"headers",{value:e,writable:!0})}}}(await _(this.adapterInterceptors,{...t,request:o,path:n,input:r,init:{redirect:"manual"}},({request:e,path:t,input:n,init:r,...o})=>this.fetch(e,r,o,t,n)),{signal:o.signal})}},ke=class extends we{constructor(e){super(new Se(e),e)}};function Ce(e){return he(new ke({url:e}))}var Ee="",Ie=Ce(""),Me=new Proxy({},{get:(e,t)=>Ie[t]}),Te="marketrix_chat_context",Re={chat_id:null,messages:[],currentMode:"tell",isOpen:!1,config:null,timestamp:0};function Oe(e){try{return"undefined"==typeof localStorage?null:localStorage.getItem(e)}catch(t){return console.warn("[StorageService] localStorage is unreadable:",t),null}}function Ae(e,t){try{"undefined"!=typeof localStorage&&localStorage.setItem(e,t)}catch(n){console.warn("[StorageService] localStorage is unwritable:",n)}}var _e,De=new class{context=function(){const e=Oe(Te);if(!e)return{...Re};try{const t={...Re,...JSON.parse(e)};if(Date.now()-t.timestamp<=6048e5)return t}catch(t){console.warn("[StorageService] Failed to parse the stored context:",t)}return{...Re}}();getContext(){return this.context}updateContext(e){this.context={...this.context,...e,timestamp:Date.now()},Ae(Te,JSON.stringify(this.context))}getChatId(){return this.context.chat_id}setChatId(e){this.updateContext({chat_id:e})}getCredentialedConfig(){const{config:e}=this.context;return e?.mtxId&&e.mtxKey?e:null}setConfig(e){this.updateContext({config:e})}},Pe=new class{creation=null;async getOrCreateChatId(){return De.getChatId()||(this.creation??=this.createChatId().finally(()=>{this.creation=null}),this.creation)}async createChatId(){const e=await Me.chatCreate(void 0);if(!e)throw new Error("API returned empty chat ID");return De.setChatId(e),e}},Le=Object.defineProperty,Ne=(e,t,n)=>((e,t,n)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n),Fe=/* @__PURE__ */(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e[e.Asset=7]="Asset",e))(Fe||{}),ze=/* @__PURE__ */(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(ze||{}),$e=/* @__PURE__ */(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))($e||{}),Be=/* @__PURE__ */(e=>(e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e))(Be||{}),We=/* @__PURE__ */(e=>(e[e["2D"]=0]="2D",e[e.WebGL=1]="WebGL",e[e.WebGL2=2]="WebGL2",e))(We||{}),Ue=/* @__PURE__ */(e=>(e[e.Play=0]="Play",e[e.Pause=1]="Pause",e[e.Seeked=2]="Seeked",e[e.VolumeChange=3]="VolumeChange",e[e.RateChange=4]="RateChange",e))(Ue||{}),He=/* @__PURE__ */(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(He||{}),je={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},qe={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Ve={},Ye={};function Ke(e){if(Ve[e])return Ve[e];const t=globalThis[e],n=t.prototype,r=e in je?je[e]:void 0,o=Boolean(r&&r.every(e=>{var t,r;return Boolean(null==(r=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:r.toString().includes("[native code]"))})),i=e in qe?qe[e]:void 0,s=Boolean(i&&i.every(e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))}));if(o&&s&&!globalThis.Zone)return Ve[e]=t.prototype,t.prototype;try{const r=document.createElement("iframe");r.style.display="none",document.body.appendChild(r);const o=r.contentWindow;if(!o)return t.prototype;const i=o[e].prototype;if(!i)return r.remove(),n;const s=navigator.userAgent;return s.includes("Safari")&&!s.includes("Chrome")?(r.classList.add("rr-block"),r.setAttribute("__rrwebUntaintedMutationObserver",""),Ye[e]=()=>r.remove()):r.remove(),Ve[e]=i}catch{return n}}var Xe={};function Ge(e,t,n){var r;const o=`${e}.${String(n)}`;if(Xe[o])return Xe[o].call(t);const i=Ke(e),s=null==(r=Object.getOwnPropertyDescriptor(i,n))?void 0:r.get;return s?(Xe[o]=s,s.call(t)):t[n]}var Je={};function Ze(e,t,n){const r=`${e}.${String(n)}`;if(Je[r])return Je[r].bind(t);const o=Ke(e)[n];return"function"!=typeof o?t[n]:(Je[r]=o,o.bind(t))}var Qe=Date.now;function et(e,t,n){try{if(!(t in e))return()=>{};const r=e[t],o=n(r);return"function"==typeof o&&(o.prototype=o.prototype||{},Object.defineProperties(o,{__rrweb_original__:{enumerable:!1,value:r}})),e[t]=o,()=>{e[t]=r}}catch{return()=>{}}}/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())||(Qe=()=>/* @__PURE__ */(new Date).getTime());var tt=function(e){return Ge("Node",e,"ownerDocument")},nt=function(e){return Ge("Node",e,"childNodes")},rt=function(e){return Ge("Node",e,"parentNode")},ot=function(e){return Ge("Node",e,"parentElement")},it=function(e){return Ge("Node",e,"textContent")},st=function(e,t){return Ze("Node",e,"contains")(t)},at=function(e){return Ze("Node",e,"getRootNode")()},ct=function(e){return e&&"host"in e?Ge("ShadowRoot",e,"host"):null},lt=function(e){return e&&"shadowRoot"in e?Ge("Element",e,"shadowRoot"):null};function dt(e){return e.nodeType===e.ELEMENT_NODE}function ut(e){const t=e&&"host"in e&&"mode"in e&&ct(e)||null;return Boolean(t&&"shadowRoot"in t&&lt(t)===e)}function pt(e){return"[object ShadowRoot]"===Object.prototype.toString.call(e)}function ht(e){try{const n=e.rules||e.cssRules;if(!n)return null;let r=e.href;return!r&&e.ownerNode&&(r=e.ownerNode.baseURI),(t=Array.from(n,e=>ft(e,r)).join("")).includes(" background-clip: text;")&&!t.includes(" -webkit-background-clip: text;")&&(t=t.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),t}catch(n){return null}var t}function ft(e,t){if(function(e){return"styleSheet"in e}(e)){let t;try{t=ht(e.styleSheet)||function(e){const{cssText:t}=e;if(t.split('"').length<3)return t;const n=["@import",`url(${JSON.stringify(e.href)})`];return""===e.layerName?n.push("layer"):e.layerName&&n.push(`layer(${e.layerName})`),e.supportsText&&n.push(`supports(${e.supportsText})`),e.media.length&&n.push(e.media.mediaText),n.join(" ")+";"}(e)}catch(n){t=e.cssText}return e.styleSheet.href?Et(t,e.styleSheet.href):t}{let n=e.cssText;return function(e){return"selectorText"in e}(e)&&e.selectorText.includes(":")&&(n=n.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm,"$1\\$2")),t?Et(n,t):n}}var mt=class{constructor(){Ne(this,"idNodeMap",/* @__PURE__ */new Map),Ne(this,"nodeMetaMap",/* @__PURE__ */new WeakMap)}getId(e){var t;return e?(null==(t=this.getMeta(e))?void 0:t.id)??-1:-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(e=>this.removeNodeFromMap(e))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const n=t.id;this.idNodeMap.set(n,e),this.nodeMetaMap.set(e,t)}replace(e,t){const n=this.getNode(e);if(n){const e=this.nodeMetaMap.get(n);e&&this.nodeMetaMap.set(t,e)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=/* @__PURE__ */new Map,this.nodeMetaMap=/* @__PURE__ */new WeakMap}};function gt({element:e,maskInputOptions:t,tagName:n,type:r,value:o,maskInputFn:i}){let s=o||"";const a=r&&yt(r);return(t[n.toLowerCase()]||a&&t[a])&&(s=i?i(s,e):"*".repeat(s.length)),s}function yt(e){return e.toLowerCase()}var bt="__rrweb_original__";function vt(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?yt(t):null}function wt(e,t){let n;try{n=new URL(e,t??window.location.href)}catch(o){return null}const r=n.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==r?void 0:r[1])??null}var xt=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,St=/^(?:[a-z+]+:)?\/\//i,kt=/^www\..*/i,Ct=/^(data:)([^,]*),(.*)/i;function Et(e,t){return(e||"").replace(xt,(e,n,r,o,i,s)=>{const a=r||i||s,c=n||o||"";if(!a)return e;if(St.test(a)||kt.test(a))return`url(${c}${a}${c})`;if(Ct.test(a))return`url(${c}${a}${c})`;if("/"===a[0])return`url(${c}${function(e){let t="";return t=e.indexOf("//")>-1?e.split("/").slice(0,3).join("/"):e.split("/")[0],t=t.split("?")[0],t}(t)+a}${c})`;const l=a.split("#")[0],d=a.substring(l.length),u=t.split("#")[0].split("/"),p=l.split("/");u.pop();for(const t of p)"."!==t&&(".."===t?u.pop():u.push(t));return`url(${c}${u.join("/")}${d}${c})`})}function It(e,t=!1){return t?e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,""):e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"").replace(/0px/g,"0")}var Mt,Tt,Rt=1,Ot=/* @__PURE__ */new RegExp("[^a-z0-9-_:]");function At(){return Rt++}var _t=/^[^ \t\n\r\u000c]+/,Dt=/^[, \t\n\r\u000c]+/,Pt=/* @__PURE__ */new WeakMap;function Lt(e,t){return t&&""!==t.trim()?Nt(e,t):t}function Nt(e,t){let n=Pt.get(e);if(n||(n=e.createElement("a"),Pt.set(e,n)),t){if(t.startsWith("blob:")||t.startsWith("data:"))return t}else t="";return n.setAttribute("href",t),n.href}function Ft(e,t,n,r){return r?"src"===n||"href"===n&&("use"!==t||"#"!==r[0])||"xlink:href"===n&&"#"!==r[0]||"background"===n&&["table","td","th"].includes(t)?Lt(e,r):"srcset"===n?function(e,t){if(""===t.trim())return t;let n=0;function r(e){let r;const o=e.exec(t.substring(n));return o?(r=o[0],n+=r.length,r):""}const o=[];for(;r(Dt),!(n>=t.length);){let i=r(_t);if(","===i.slice(-1))i=Lt(e,i.substring(0,i.length-1)),o.push(i);else{let r="";i=Lt(e,i);let s=!1;for(;;){const e=t.charAt(n);if(""===e){o.push((i+r).trim());break}if(s)")"===e&&(s=!1);else{if(","===e){n+=1,o.push((i+r).trim());break}"("===e&&(s=!0)}r+=e,n+=1}}}return o.join(", ")}(e,r):"style"===n?Et(r,Nt(e)):"object"===t&&"data"===n?Lt(e,r):r:r}function zt(e,t,n){return["video","audio"].includes(e)&&"autoplay"===t}function $t(e,t,n){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!n&&$t(rt(e),t,n);for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}return!!n&&$t(rt(e),t,n)}function Bt(e,t,n,r){let o;if(dt(e)){if(o=e,!nt(o).length)return!1}else{if(null===ot(e))return!1;o=ot(e)}try{if("string"==typeof t){if(r){if(o.closest(`.${t}`))return!0}else if(o.classList.contains(t))return!0}else if($t(o,t,r))return!0;if(n)if(r){if(o.closest(n))return!0}else if(o.matches(n))return!0}catch(i){}return!1}function Wt(e){return null==e?"":e.toLowerCase()}function Ut(e){return!0===e||"all"===e?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===e,headMetaDescKeywords:"all"===e,headTitleMutations:"all"===e}:e||{}}function Ht(e,t){const{doc:n,mirror:r,blockClass:o,blockSelector:i,maskTextClass:s,maskTextSelector:a,skipChild:c=!1,inlineStylesheet:l=!0,maskInputOptions:d={},maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f={},inlineImages:m=!1,recordCanvas:g=!1,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v=5e3,onStylesheetLoad:w,stylesheetLoadTimeout:x=5e3,keepIframeSrcFn:S=()=>!1,newlyAddedElement:k=!1,cssCaptured:C=!1}=t;let{needsMask:E}=t,{preserveWhiteSpace:I=!0}=t;E||(E=Bt(e,s,a,void 0===E));const M=function(e,t){const{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:s,inlineStylesheet:a,maskInputOptions:c={},maskTextFn:l,maskInputFn:d,dataURLOptions:u={},inlineImages:p,recordCanvas:h,keepIframeSrcFn:f,newlyAddedElement:m=!1,cssCaptured:g=!1}=t,y=function(e,t){if(!t.hasNode(e))return;const n=t.getId(e);return 1===n?void 0:n}(n,r);switch(e.nodeType){case e.DOCUMENT_NODE:return"CSS1Compat"!==e.compatMode?{type:He.Document,childNodes:[],compatMode:e.compatMode}:{type:He.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:He.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:y};case e.ELEMENT_NODE:return function(e,t){const{doc:n,blockClass:r,blockSelector:o,inlineStylesheet:i,maskInputOptions:s={},maskInputFn:a,dataURLOptions:c={},inlineImages:l,recordCanvas:d,keepIframeSrcFn:u,newlyAddedElement:p=!1,rootId:h}=t,f=function(e,t,n){try{if("string"==typeof t){if(e.classList.contains(t))return!0}else for(let n=e.classList.length;n--;){const r=e.classList[n];if(t.test(r))return!0}if(n)return e.matches(n)}catch(r){}return!1}(e,r,o),m=function(e){if(e instanceof HTMLFormElement)return"form";const t=yt(e.tagName);return Ot.test(t)?"div":t}(e);let g={};const y=e.attributes.length;for(let x=0;x<y;x++){const t=e.attributes[x];zt(m,t.name,t.value)||(g[t.name]=Ft(n,m,yt(t.name),t.value))}if("link"===m&&i){const t=Array.from(n.styleSheets).find(t=>t.href===e.href);let r=null;t&&(r=ht(t)),r&&(delete g.rel,delete g.href,g._cssText=r)}if("style"===m&&e.sheet){let t=ht(e.sheet);t&&(e.childNodes.length>1&&(t=function(e,t){return function(e,t,n=!1){const r=Array.from(t.childNodes),o=[];let i=0;if(r.length>1&&e&&"string"==typeof e){let t=It(e,n);const s=t.length/e.length;for(let a=1;a<r.length;a++)if(r[a].textContent&&"string"==typeof r[a].textContent){const c=It(r[a].textContent,n),l=100;let d=3;for(;d<c.length&&(c[d].match(/[a-zA-Z0-9]/)||-1!==c.indexOf(c.substring(0,d),1));d++);for(;d<c.length;d++){let u=c.substring(0,d),p=t.split(u),h=-1;if(2===p.length)h=p[0].length;else if(p.length>2&&""===p[0]&&""!==r[a-1].textContent)h=t.indexOf(u,1);else if(1===p.length){if(u=u.substring(0,u.length-1),p=t.split(u),p.length<=1)return o.push(e),o;d=101}else d===c.length-1&&(h=t.indexOf(u));if(p.length>=2&&d>l){const e=r[a-1].textContent;if(e&&"string"==typeof e){const n=It(e).length;h=t.indexOf(u,n)}-1===h&&(h=p[0].length)}if(-1!==h){let a=Math.floor(h/s);for(;a>0&&a<e.length;){if(i+=1,i>50*r.length)return o.push(e),o;const c=It(e.substring(0,a),n);if(c.length===h){o.push(e.substring(0,a)),e=e.substring(a),t=t.substring(h);break}c.length<h?a+=Math.max(1,Math.floor((h-c.length)/s)):a-=Math.max(1,Math.floor((c.length-h)*s))}break}}}}return o.push(e),o}(e,t).join("/* rr_split */")}(t,e)),g._cssText=t)}if(["input","textarea","select"].includes(m)){const t=e.value,n=e.checked;"radio"!==g.type&&"checkbox"!==g.type&&"submit"!==g.type&&"button"!==g.type&&t?g.value=gt({element:e,type:vt(e),tagName:m,value:t,maskInputOptions:s,maskInputFn:a}):n&&(g.checked=n)}if("option"===m&&(e.selected&&!s.select?g.selected=!0:delete g.selected),"dialog"===m&&e.open&&(g.rr_open_mode=e.matches("dialog:modal")?"modal":"non-modal"),"canvas"===m&&d)if("2d"===e.__context)(function(e){const t=e.getContext("2d");if(!t)return!0;for(let n=0;n<e.width;n+=50)for(let r=0;r<e.height;r+=50){const o=t.getImageData,i=bt in o?o[bt]:o;if(new Uint32Array(i.call(t,n,r,Math.min(50,e.width-n),Math.min(50,e.height-r)).data.buffer).some(e=>0!==e))return!1}return!0})(e)||(g.rr_dataURL=e.toDataURL(c.type,c.quality));else if(!("__context"in e)){const t=e.toDataURL(c.type,c.quality),r=n.createElement("canvas");r.width=e.width,r.height=e.height,t!==r.toDataURL(c.type,c.quality)&&(g.rr_dataURL=t)}if("img"===m&&l){Mt||(Mt=n.createElement("canvas"),Tt=Mt.getContext("2d"));const t=e,r=t.currentSrc||t.getAttribute("src")||"<unknown-src>",o=t.crossOrigin,i=()=>{t.removeEventListener("load",i);try{Mt.width=t.naturalWidth,Mt.height=t.naturalHeight,Tt.drawImage(t,0,0),g.rr_dataURL=Mt.toDataURL(c.type,c.quality)}catch(e){if("anonymous"!==t.crossOrigin)return t.crossOrigin="anonymous",void(t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i));console.warn(`Cannot inline img src=${r}! Error: ${e}`)}"anonymous"===t.crossOrigin&&(o?g.crossOrigin=o:t.removeAttribute("crossorigin"))};t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i)}if(["audio","video"].includes(m)){const t=g;t.rr_mediaState=e.paused?"paused":"played",t.rr_mediaCurrentTime=e.currentTime,t.rr_mediaPlaybackRate=e.playbackRate,t.rr_mediaMuted=e.muted,t.rr_mediaLoop=e.loop,t.rr_mediaVolume=e.volume}if(p||(e.scrollLeft&&(g.rr_scrollLeft=e.scrollLeft),e.scrollTop&&(g.rr_scrollTop=e.scrollTop)),f){const{width:t,height:n}=e.getBoundingClientRect();g={class:g.class,rr_width:`${t}px`,rr_height:`${n}px`}}let b;"iframe"!==m||u(g.src)||(e.contentDocument||(g.rr_src=g.src),delete g.src);try{customElements.get(m)&&(b=!0)}catch(w){}return{type:He.Element,tagName:m,attributes:g,childNodes:[],isSVG:(v=e,Boolean("svg"===v.tagName||v.ownerSVGElement)||void 0),needBlock:f,rootId:h,isCustom:b};var v}(e,{doc:n,blockClass:o,blockSelector:i,inlineStylesheet:a,maskInputOptions:c,maskInputFn:d,dataURLOptions:u,inlineImages:p,recordCanvas:h,keepIframeSrcFn:f,newlyAddedElement:m,rootId:y});case e.TEXT_NODE:return function(e,t){const{needsMask:n,maskTextFn:r,rootId:o,cssCaptured:i}=t,s=rt(e),a=s&&s.tagName;let c="";const l="STYLE"===a||void 0,d="SCRIPT"===a||void 0;return d?c="SCRIPT_PLACEHOLDER":i||(c=it(e),l&&c&&(c=Et(c,Nt(t.doc)))),!l&&!d&&c&&n&&(c=r?r(c,ot(e)):c.replace(/[\S]/g,"*")),{type:He.Text,textContent:c||"",rootId:o}}(e,{doc:n,needsMask:s,maskTextFn:l,rootId:y,cssCaptured:g});case e.CDATA_SECTION_NODE:return{type:He.CDATA,textContent:"",rootId:y};case e.COMMENT_NODE:return{type:He.Comment,textContent:it(e)||"",rootId:y};default:return!1}}(e,{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,dataURLOptions:f,inlineImages:m,recordCanvas:g,keepIframeSrcFn:S,newlyAddedElement:k,cssCaptured:C});if(!M)return console.warn(e,"not serialized"),null;let T;T=r.hasNode(e)?r.getId(e):function(e,t){if(t.comment&&e.type===He.Comment)return!0;if(e.type===He.Element){if(t.script&&("script"===e.tagName||"link"===e.tagName&&("preload"===e.attributes.rel&&"script"===e.attributes.as||"modulepreload"===e.attributes.rel)||"link"===e.tagName&&"prefetch"===e.attributes.rel&&"string"==typeof e.attributes.href&&"js"===wt(e.attributes.href)))return!0;if(t.headFavicon&&("link"===e.tagName&&"shortcut icon"===e.attributes.rel||"meta"===e.tagName&&(Wt(e.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===Wt(e.attributes.name)||"icon"===Wt(e.attributes.rel)||"apple-touch-icon"===Wt(e.attributes.rel)||"shortcut icon"===Wt(e.attributes.rel))))return!0;if("meta"===e.tagName){if(t.headMetaDescKeywords&&Wt(e.attributes.name).match(/^description|keywords$/))return!0;if(t.headMetaSocial&&(Wt(e.attributes.property).match(/^(og|twitter|fb):/)||Wt(e.attributes.name).match(/^(og|twitter):/)||"pinterest"===Wt(e.attributes.name)))return!0;if(t.headMetaRobots&&("robots"===Wt(e.attributes.name)||"googlebot"===Wt(e.attributes.name)||"bingbot"===Wt(e.attributes.name)))return!0;if(t.headMetaHttpEquiv&&void 0!==e.attributes["http-equiv"])return!0;if(t.headMetaAuthorship&&("author"===Wt(e.attributes.name)||"generator"===Wt(e.attributes.name)||"framework"===Wt(e.attributes.name)||"publisher"===Wt(e.attributes.name)||"progid"===Wt(e.attributes.name)||Wt(e.attributes.property).match(/^article:/)||Wt(e.attributes.property).match(/^product:/)))return!0;if(t.headMetaVerification&&("google-site-verification"===Wt(e.attributes.name)||"yandex-verification"===Wt(e.attributes.name)||"csrf-token"===Wt(e.attributes.name)||"p:domain_verify"===Wt(e.attributes.name)||"verify-v1"===Wt(e.attributes.name)||"verification"===Wt(e.attributes.name)||"shopify-checkout-api-token"===Wt(e.attributes.name)))return!0}}return!1}(M,h)||!I&&M.type===He.Text&&!M.textContent.replace(/^\s+|\s+$/gm,"").length?-2:At();const R=Object.assign(M,{id:T});if(r.add(e,R),-2===T)return null;y&&y(e);let O=!c;if(R.type===He.Element){O=O&&!R.needBlock,delete R.needBlock;const t=lt(e);t&&pt(t)&&(R.isShadowHost=!0)}if((R.type===He.Document||R.type===He.Element)&&O){h.headWhitespace&&R.type===He.Element&&"head"===R.tagName&&(I=!1);const t={doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:c,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S,cssCaptured:!1};if(R.type===He.Element&&"textarea"===R.tagName&&void 0!==R.attributes.value);else{R.type===He.Element&&void 0!==R.attributes._cssText&&"string"==typeof R.attributes._cssText&&(t.cssCaptured=!0);for(const n of Array.from(nt(e))){const e=Ht(n,t);e&&R.childNodes.push(e)}}let k=null;if(dt(e)&&(k=lt(e)))for(const e of Array.from(nt(k))){const n=Ht(e,t);n&&(pt(k)&&(n.isShadow=!0),R.childNodes.push(n))}}const A=rt(e);return A&&ut(A)&&pt(A)&&(R.isShadow=!0),R.type===He.Element&&"iframe"===R.tagName&&function(e,t,n){const r=e.contentWindow;if(!r)return;let o,i=!1;try{o=r.document.readyState}catch(a){return}if("complete"!==o){const r=setTimeout(()=>{i||(t(),i=!0)},n);return void e.addEventListener("load",()=>{clearTimeout(r),i=!0,t()})}const s="about:blank";if(r.location.href!==s||e.src===s||""===e.src)return setTimeout(t,0),e.addEventListener("load",t);e.addEventListener("load",t)}(e,()=>{const t=e.contentDocument;if(t&&b){const n=Ht(t,{doc:t,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S});n&&b(e,n)}},v),R.type===He.Element&&"link"===R.tagName&&"string"==typeof R.attributes.rel&&("stylesheet"===R.attributes.rel||"preload"===R.attributes.rel&&"string"==typeof R.attributes.href&&"css"===wt(R.attributes.href))&&function(e,t,n){let r,o=!1;try{r=e.sheet}catch(s){return}if(r)return;const i=setTimeout(()=>{o||(t(),o=!0)},n);e.addEventListener("load",()=>{clearTimeout(i),o=!0,t()})}(e,()=>{if(w){const t=Ht(e,{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S});t&&w(e,t)}},x),R}var jt=class e{constructor(...e){Ne(this,"parentElement",null),Ne(this,"parentNode",null),Ne(this,"ownerDocument"),Ne(this,"firstChild",null),Ne(this,"lastChild",null),Ne(this,"previousSibling",null),Ne(this,"nextSibling",null),Ne(this,"ELEMENT_NODE",1),Ne(this,"TEXT_NODE",3),Ne(this,"nodeType"),Ne(this,"nodeName"),Ne(this,"RRNodeType")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(t){if(!(t instanceof e))return!1;if(t.ownerDocument!==this.ownerDocument)return!1;if(t===this)return!0;for(;t.parentNode;){if(t.parentNode===this)return!0;t=t.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}};function qt(e,t,n=document){const r={capture:!0,passive:!0};return n.addEventListener(e,t,r),()=>n.removeEventListener(e,t,r)}var Vt="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.",Yt={map:{},getId:()=>(console.error(Vt),-1),getNode:()=>(console.error(Vt),null),removeNodeFromMap(){console.error(Vt)},has:()=>(console.error(Vt),!1),reset(){console.error(Vt)}};function Kt(e,t,n={}){let r=null,o=0;return function(...i){const s=Date.now();o||!1!==n.leading||(o=s);const a=t-(s-o),c=this;a<=0||a>t?(r&&(clearTimeout(r),r=null),o=s,e.apply(c,i)):r||!1===n.trailing||(r=setTimeout(()=>{o=!1===n.leading?0:Date.now(),r=null,e.apply(c,i)},a))}}function Xt(e,t,n,r,o=window){const i=o.Object.getOwnPropertyDescriptor(e,t);return o.Object.defineProperty(e,t,r?n:{set(e){setTimeout(()=>{n.set.call(this,e)},0),i&&i.set&&i.set.call(this,e)}}),()=>Xt(e,t,i||{},!0)}function Gt(e){var t,n,r,o;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null==(t=ot(i.body))?void 0:t.scrollLeft)||(null==(n=null==i?void 0:i.body)?void 0:n.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null==(r=ot(i.body))?void 0:r.scrollTop)||(null==(o=null==i?void 0:i.body)?void 0:o.scrollTop)||0}}function Jt(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Zt(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Qt(e){return e?e.nodeType===e.ELEMENT_NODE?e:ot(e):null}function en(e,t,n,r){if(!e)return!1;const o=Qt(e);if(!o)return!1;try{if("string"==typeof t){if(o.classList.contains(t))return!0;if(r&&null!==o.closest("."+t))return!0}else if($t(o,t,r))return!0}catch(i){}if(n){if(o.matches(n))return!0;if(r&&null!==o.closest(n))return!0}return!1}function tn(e,t,n){return!("TITLE"!==e.tagName||!n.headTitleMutations)||-2===t.getId(e)}function nn(e,t){if(ut(e))return!1;const n=t.getId(e);if(!t.has(n))return!0;const r=rt(e);return(!r||r.nodeType!==e.DOCUMENT_NODE)&&(!r||nn(r,t))}function rn(e){return Boolean(e.changedTouches)}function on(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))}function sn(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))}function an(e){return!!e&&(e instanceof jt&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(lt(e)))}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Yt=new Proxy(Yt,{get:(e,t,n)=>("map"===t&&console.error(Vt),Reflect.get(e,t,n))}));var cn=class{constructor(){Ne(this,"id",1),Ne(this,"styleIDMap",/* @__PURE__ */new WeakMap),Ne(this,"idStyleMap",/* @__PURE__ */new Map)}getId(e){return this.styleIDMap.get(e)??-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let n;return n=void 0===t?this.id++:t,this.styleIDMap.set(e,n),this.idStyleMap.set(n,e),n}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=/* @__PURE__ */new WeakMap,this.idStyleMap=/* @__PURE__ */new Map,this.id=1}generateId(){return this.id++}};function ln(e){var t;let n=null;return"getRootNode"in e&&(null==(t=at(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&ct(at(e))&&(n=ct(at(e))),n}function dn(e){const t=tt(e);return!!t&&(st(t,e)||function(e){const t=tt(e);if(!t)return!1;const n=function(e){let t,n=e;for(;t=ln(n);)n=t;return n}(e);return st(t,n)}(e))}function un(e){return"__ln"in e}var pn,hn=class{constructor(){Ne(this,"length",0),Ne(this,"head",null),Ne(this,"tail",null)}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let n=0;n<e;n++)t=(null==t?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&un(e.previousSibling)){const n=e.previousSibling.__ln.next;t.next=n,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,n&&(n.previous=t)}else if(e.nextSibling&&un(e.nextSibling)&&e.nextSibling.__ln.previous){const n=e.nextSibling.__ln.previous;t.previous=n,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,n&&(n.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;null===t.next&&(this.tail=t),this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next?t.next.previous=t.previous:this.tail=t.previous):(this.head=t.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)}},fn=(e,t)=>`${e}@${t}`,mn=class{constructor(){Ne(this,"frozen",!1),Ne(this,"locked",!1),Ne(this,"texts",[]),Ne(this,"attributes",[]),Ne(this,"attributeMap",/* @__PURE__ */new WeakMap),Ne(this,"removes",[]),Ne(this,"mapRemoves",[]),Ne(this,"movedMap",{}),Ne(this,"addedSet",/* @__PURE__ */new Set),Ne(this,"movedSet",/* @__PURE__ */new Set),Ne(this,"droppedSet",/* @__PURE__ */new Set),Ne(this,"removesSubTreeCache",/* @__PURE__ */new Set),Ne(this,"mutationCb"),Ne(this,"blockClass"),Ne(this,"blockSelector"),Ne(this,"maskTextClass"),Ne(this,"maskTextSelector"),Ne(this,"inlineStylesheet"),Ne(this,"maskInputOptions"),Ne(this,"maskTextFn"),Ne(this,"maskInputFn"),Ne(this,"keepIframeSrcFn"),Ne(this,"recordCanvas"),Ne(this,"inlineImages"),Ne(this,"slimDOMOptions"),Ne(this,"dataURLOptions"),Ne(this,"doc"),Ne(this,"mirror"),Ne(this,"iframeManager"),Ne(this,"stylesheetManager"),Ne(this,"shadowDomManager"),Ne(this,"canvasManager"),Ne(this,"processedNodeManager"),Ne(this,"unattachedDoc"),Ne(this,"processMutations",e=>{e.forEach(this.processMutation),this.emit()}),Ne(this,"emit",()=>{if(this.frozen||this.locked)return;const e=[],t=/* @__PURE__ */new Set,n=new hn,r=e=>{let t=e,n=-2;for(;-2===n;)t=t&&t.nextSibling,n=t&&this.mirror.getId(t);return n},o=o=>{const i=rt(o);if(!i||!dn(o))return;let s=!1;if(o.nodeType===Node.TEXT_NODE){const e=i.tagName;if("TEXTAREA"===e)return;"STYLE"===e&&this.addedSet.has(i)&&(s=!0)}const a=ut(i)?this.mirror.getId(ln(o)):this.mirror.getId(i),c=r(o);if(-1===a||-1===c)return n.addNode(o);const l=Ht(o,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:e=>{on(e,this.mirror)&&this.iframeManager.addIframe(e),sn(e,this.mirror)&&this.stylesheetManager.trackLinkElement(e),an(o)&&this.shadowDomManager.addShadowRoot(lt(o),this.doc)},onIframeLoad:(e,t)=>{this.iframeManager.attachIframe(e,t),this.shadowDomManager.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{this.stylesheetManager.attachLinkElement(e,t)},cssCaptured:s});l&&(e.push({parentId:a,nextId:c,node:l}),t.add(l.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of this.movedSet)yn(this.removesSubTreeCache,a,this.mirror)&&!this.movedSet.has(rt(a))||o(a);for(const a of this.addedSet)bn(this.droppedSet,a)||yn(this.removesSubTreeCache,a,this.mirror)?bn(this.movedSet,a)?o(a):this.droppedSet.add(a):o(a);let i=null;for(;n.length;){let e=null;if(i){const t=this.mirror.getId(rt(i.value)),n=r(i.value);-1!==t&&-1!==n&&(e=i)}if(!e){let t=n.tail;for(;t;){const n=t;if(t=t.previous,n){const t=this.mirror.getId(rt(n.value));if(-1===r(n.value))continue;if(-1!==t){e=n;break}{const t=n.value,r=rt(t);if(r&&r.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const t=ct(r);if(-1!==this.mirror.getId(t)){e=n;break}}}}}}if(!e){for(;n.head;)n.removeNode(n.head.value);break}i=e.previous,n.removeNode(e.value),o(e.value)}const s={texts:this.texts.map(e=>{const t=e.node,n=rt(t);return n&&"TEXTAREA"===n.tagName&&this.genTextAreaValueMutation(n),{id:this.mirror.getId(t),value:e.value}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),attributes:this.attributes.map(e=>{const{attributes:t}=e;if("string"==typeof t.style){const n=JSON.stringify(e.styleDiff),r=JSON.stringify(e._unchangedStyles);n.length<t.style.length&&(n+r).split("var(").length===t.style.split("var(").length&&(t.style=e.styleDiff)}return{id:this.mirror.getId(e.node),attributes:t}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),removes:this.removes,adds:e};(s.texts.length||s.attributes.length||s.removes.length||s.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=/* @__PURE__ */new WeakMap,this.removes=[],this.addedSet=/* @__PURE__ */new Set,this.movedSet=/* @__PURE__ */new Set,this.droppedSet=/* @__PURE__ */new Set,this.removesSubTreeCache=/* @__PURE__ */new Set,this.movedMap={},this.mutationCb(s))}),Ne(this,"genTextAreaValueMutation",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t));const n=Array.from(nt(e),e=>it(e)||"").join("");t.attributes.value=gt({element:e,maskInputOptions:this.maskInputOptions,tagName:e.tagName,type:vt(e),value:n,maskInputFn:this.maskInputFn})}),Ne(this,"processMutation",e=>{if(!tn(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case"characterData":{const t=it(e.target);en(e.target,this.blockClass,this.blockSelector,!1)||t===e.oldValue||this.texts.push({value:Bt(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,Qt(e.target)):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const n=e.target;let r=e.attributeName,o=e.target.getAttribute(r);if("value"===r){const e=vt(n);o=gt({element:n,maskInputOptions:this.maskInputOptions,tagName:n.tagName,type:e,value:o,maskInputFn:this.maskInputFn})}if(en(e.target,this.blockClass,this.blockSelector,!1)||o===e.oldValue)return;let i=this.attributeMap.get(e.target);if("IFRAME"===n.tagName&&"src"===r&&!this.keepIframeSrcFn(o)){if(n.contentDocument)return;r="rr_src"}if(i||(i={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(i),this.attributeMap.set(e.target,i)),"type"===r&&"INPUT"===n.tagName&&"password"===(e.oldValue||"").toLowerCase()&&n.setAttribute("data-rr-is-password","true"),!zt(n.tagName,r))if(i.attributes[r]=Ft(this.doc,yt(n.tagName),yt(r),o),"style"===r){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(t){this.unattachedDoc=this.doc}const r=this.unattachedDoc.createElement("span");e.oldValue&&r.setAttribute("style",e.oldValue);for(const e of Array.from(n.style)){const t=n.style.getPropertyValue(e),o=n.style.getPropertyPriority(e);t!==r.style.getPropertyValue(e)||o!==r.style.getPropertyPriority(e)?i.styleDiff[e]=""===o?t:[t,o]:i._unchangedStyles[e]=[t,o]}for(const e of Array.from(r.style))""===n.style.getPropertyValue(e)&&(i.styleDiff[e]=!1)}else"open"===r&&"DIALOG"===n.tagName&&(n.matches("dialog:modal")?i.attributes.rr_open_mode="modal":i.attributes.rr_open_mode="non-modal");break}case"childList":if(en(e.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===e.target.tagName)return void this.genTextAreaValueMutation(e.target);e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const n=this.mirror.getId(t),r=ut(e.target)?this.mirror.getId(ct(e.target)):this.mirror.getId(e.target);en(e.target,this.blockClass,this.blockSelector,!1)||tn(t,this.mirror,this.slimDOMOptions)||!function(e,t){return-1!==t.getId(e)}(t,this.mirror)||(this.addedSet.has(t)?(gn(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&-1===n||nn(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[fn(n,r)]?gn(this.movedSet,t):(this.removes.push({parentId:r,id:n,isShadow:!(!ut(e.target)||!pt(e.target))||void 0}),function(e,t){const n=[e];for(;n.length;){const e=n.pop();t.has(e)||(t.add(e),nt(e).forEach(e=>n.push(e)))}}(t,this.removesSubTreeCache))),this.mapRemoves.push(t))})}}),Ne(this,"genAdds",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!this.addedSet.has(e)&&!this.movedSet.has(e)){if(this.mirror.hasNode(e)){if(tn(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let n=null;t&&this.mirror.hasNode(t)&&(n=this.mirror.getId(t)),n&&-1!==n&&(this.movedMap[fn(this.mirror.getId(e),n)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);en(e,this.blockClass,this.blockSelector,!1)||(nt(e).forEach(e=>this.genAdds(e)),an(e)&&nt(lt(e)).forEach(t=>{this.processedNodeManager.add(t,this),this.genAdds(t,e)}))}})}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}};function gn(e,t){e.delete(t),nt(t).forEach(t=>gn(e,t))}function yn(e,t,n){return 0!==e.size&&function(e,t){const n=rt(t);return!!n&&e.has(n)}(e,t)}function bn(e,t){return 0!==e.size&&vn(e,t)}function vn(e,t){const n=rt(t);return!!n&&(!!e.has(n)||vn(e,n))}var wn=e=>pn?(...t)=>{try{return e(...t)}catch(n){if(pn&&!0===pn(n))return;throw n}}:e,xn=[];function Sn(e){try{if("composedPath"in e){const t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch{}return e&&e.target}function kn(e,t){const n=new mn;xn.push(n),n.init(e);const[r,o]=[Ke("MutationObserver").constructor,Ye.MutationObserver??(()=>{})],i=new r(wn(n.processMutations.bind(n)));return i.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),[i,o]}function Cn({scrollCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,sampling:i}){return qt("scroll",wn(Kt(wn(i=>{const s=Sn(i);if(!s||en(s,r,o,!0))return;const a=n.getId(s);if(s===t&&t.defaultView){const n=Gt(t.defaultView);e({id:a,x:n.left,y:n.top})}else e({id:a,x:s.scrollLeft,y:s.scrollTop})}),i.scroll||100)),t)}var En=["INPUT","TEXTAREA","SELECT"],In=/* @__PURE__ */new WeakMap;function Mn(e){return function e(t,n){if(An("CSSGroupingRule")&&t.parentRule instanceof CSSGroupingRule||An("CSSMediaRule")&&t.parentRule instanceof CSSMediaRule||An("CSSSupportsRule")&&t.parentRule instanceof CSSSupportsRule||An("CSSConditionRule")&&t.parentRule instanceof CSSConditionRule){const r=Array.from(t.parentRule.cssRules).indexOf(t);return n.unshift(r),e(t.parentRule,n)}if(t.parentStyleSheet){const e=Array.from(t.parentStyleSheet.cssRules).indexOf(t);n.unshift(e)}return n}(e,[])}function Tn(e,t,n){let r,o;return e?(e.ownerNode?r=t.getId(e.ownerNode):o=n.getId(e),{styleId:o,id:r}):{}}function Rn({mirror:e,stylesheetManager:t},n){var r,o,i;let s=null;s="#document"===n.nodeName?e.getId(n):e.getId(ct(n));const a="#document"===n.nodeName?null==(r=n.defaultView)?void 0:r.Document:null==(i=null==(o=n.ownerDocument)?void 0:o.defaultView)?void 0:i.ShadowRoot,c=(null==a?void 0:a.prototype)?Object.getOwnPropertyDescriptor(null==a?void 0:a.prototype,"adoptedStyleSheets"):void 0;return null!==s&&-1!==s&&a&&c?(Object.defineProperty(n,"adoptedStyleSheets",{configurable:c.configurable,enumerable:c.enumerable,get(){var e;return null==(e=c.get)?void 0:e.call(this)},set(e){var n;const r=null==(n=c.set)?void 0:n.call(this,e);if(null!==s&&-1!==s)try{t.adoptStyleSheets(e,s)}catch(o){}return r}}),wn(()=>{Object.defineProperty(n,"adoptedStyleSheets",{configurable:c.configurable,enumerable:c.enumerable,get:c.get,set:c.set})})):()=>{}}function On(e,t={}){const n=e.doc.defaultView;if(!n)return()=>{};let r;!function(e,t){const{mutationCb:n,mousemoveCb:r,mouseInteractionCb:o,scrollCb:i,viewportResizeCb:s,inputCb:a,mediaInteractionCb:c,styleSheetRuleCb:l,styleDeclarationCb:d,canvasMutationCb:u,fontCb:p,selectionCb:h,customElementCb:f}=e;e.mutationCb=(...e)=>{t.mutation&&t.mutation(...e),n(...e)},e.mousemoveCb=(...e)=>{t.mousemove&&t.mousemove(...e),r(...e)},e.mouseInteractionCb=(...e)=>{t.mouseInteraction&&t.mouseInteraction(...e),o(...e)},e.scrollCb=(...e)=>{t.scroll&&t.scroll(...e),i(...e)},e.viewportResizeCb=(...e)=>{t.viewportResize&&t.viewportResize(...e),s(...e)},e.inputCb=(...e)=>{t.input&&t.input(...e),a(...e)},e.mediaInteractionCb=(...e)=>{t.mediaInteaction&&t.mediaInteaction(...e),c(...e)},e.styleSheetRuleCb=(...e)=>{t.styleSheetRule&&t.styleSheetRule(...e),l(...e)},e.styleDeclarationCb=(...e)=>{t.styleDeclaration&&t.styleDeclaration(...e),d(...e)},e.canvasMutationCb=(...e)=>{t.canvasMutation&&t.canvasMutation(...e),u(...e)},e.fontCb=(...e)=>{t.font&&t.font(...e),p(...e)},e.selectionCb=(...e)=>{t.selection&&t.selection(...e),h(...e)},e.customElementCb=(...e)=>{t.customElement&&t.customElement(...e),f(...e)}}(e,t);let o=()=>{};e.recordDOM&&([r,o]=kn(e,e.doc));const i=function({mousemoveCb:e,sampling:t,doc:n,mirror:r}){if(!1===t.mousemove)return()=>{};const o="number"==typeof t.mousemove?t.mousemove:50,i="number"==typeof t.mousemoveCallback?t.mousemoveCallback:500;let s,a=[];const c=Kt(wn(t=>{const n=Date.now()-s;e(a.map(e=>(e.timeOffset-=n,e)),t),a=[],s=null}),i),l=wn(Kt(wn(e=>{const t=Sn(e),{clientX:n,clientY:o}=rn(e)?e.changedTouches[0]:e;s||(s=Qe()),a.push({x:n,y:o,id:r.getId(t),timeOffset:Qe()-s}),c("undefined"!=typeof DragEvent&&e instanceof DragEvent?ze.Drag:e instanceof MouseEvent?ze.MouseMove:ze.TouchMove)}),o,{trailing:!1})),d=[qt("mousemove",l,n),qt("touchmove",l,n),qt("drag",l,n)];return wn(()=>{d.forEach(e=>e())})}(e),s=function({mouseInteractionCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,sampling:i}){if(!1===i.mouseInteraction)return()=>{};const s=!0===i.mouseInteraction||void 0===i.mouseInteraction?{}:i.mouseInteraction,a=[];let c=null;return Object.keys($e).filter(e=>Number.isNaN(Number(e))&&!e.endsWith("_Departed")&&!1!==s[e]).forEach(i=>{let s=yt(i);const l=(t=>i=>{const s=Sn(i);if(en(s,r,o,!0))return;let a=null,l=t;if("pointerType"in i){switch(i.pointerType){case"mouse":a=Be.Mouse;break;case"touch":a=Be.Touch;break;case"pen":a=Be.Pen}a===Be.Touch?$e[t]===$e.MouseDown?l="TouchStart":$e[t]===$e.MouseUp&&(l="TouchEnd"):Be.Pen}else rn(i)&&(a=Be.Touch);null!==a?(c=a,(l.startsWith("Touch")&&a===Be.Touch||l.startsWith("Mouse")&&a===Be.Mouse)&&(a=null)):$e[t]===$e.Click&&(a=c,c=null);const d=rn(i)?i.changedTouches[0]:i;if(!d)return;const u=n.getId(s),{clientX:p,clientY:h}=d;wn(e)({type:$e[l],id:u,x:p,y:h,...null!==a&&{pointerType:a}})})(i);if(window.PointerEvent)switch($e[i]){case $e.MouseDown:case $e.MouseUp:s=s.replace("mouse","pointer");break;case $e.TouchStart:case $e.TouchEnd:return}a.push(qt(s,l,t))}),wn(()=>{a.forEach(e=>e())})}(e),a=Cn(e),c=function({viewportResizeCb:e},{win:t}){let n=-1,r=-1;return qt("resize",wn(Kt(wn(()=>{const t=Jt(),o=Zt();n===t&&r===o||(e({width:Number(o),height:Number(t)}),n=t,r=o)}),200)),t)}(e,{win:n}),l=function({inputCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,ignoreClass:i,ignoreSelector:s,maskInputOptions:a,maskInputFn:c,sampling:l,userTriggeredOnInput:d}){function u(e){let n=Sn(e);const l=e.isTrusted,u=n&&n.tagName;if(n&&"OPTION"===u&&(n=ot(n)),!n||!u||En.indexOf(u)<0||en(n,r,o,!0))return;if(n.classList.contains(i)||s&&n.matches(s))return;let h=n.value,f=!1;const m=vt(n)||"";"radio"===m||"checkbox"===m?f=n.checked:(a[u.toLowerCase()]||a[m])&&(h=gt({element:n,maskInputOptions:a,tagName:u,type:m,value:h,maskInputFn:c})),p(n,d?{text:h,isChecked:f,userTriggered:l}:{text:h,isChecked:f});const g=n.name;"radio"===m&&g&&f&&t.querySelectorAll(`input[type="radio"][name="${g}"]`).forEach(e=>{if(e!==n){const t=e.value;p(e,d?{text:t,isChecked:!f,userTriggered:!1}:{text:t,isChecked:!f})}})}function p(t,r){const o=In.get(t);if(!o||o.text!==r.text||o.isChecked!==r.isChecked){In.set(t,r);const o=n.getId(t);wn(e)({...r,id:o})}}const h=("last"===l.input?["change"]:["input","change"]).map(e=>qt(e,wn(u),t)),f=t.defaultView;if(!f)return()=>{h.forEach(e=>e())};const m=f.Object.getOwnPropertyDescriptor(f.HTMLInputElement.prototype,"value"),g=[[f.HTMLInputElement.prototype,"value"],[f.HTMLInputElement.prototype,"checked"],[f.HTMLSelectElement.prototype,"value"],[f.HTMLTextAreaElement.prototype,"value"],[f.HTMLSelectElement.prototype,"selectedIndex"],[f.HTMLOptionElement.prototype,"selected"]];return m&&m.set&&h.push(...g.map(e=>Xt(e[0],e[1],{set(){wn(u)({target:this,isTrusted:!1})}},!1,f))),wn(()=>{h.forEach(e=>e())})}(e),d=function({mediaInteractionCb:e,blockClass:t,blockSelector:n,mirror:r,sampling:o,doc:i}){const s=wn(i=>Kt(wn(o=>{const s=Sn(o);if(!s||en(s,t,n,!0))return;const{currentTime:a,volume:c,muted:l,playbackRate:d,loop:u}=s;e({type:i,id:r.getId(s),currentTime:a,volume:c,muted:l,playbackRate:d,loop:u})}),o.media||500)),a=[qt("play",s(Ue.Play),i),qt("pause",s(Ue.Pause),i),qt("seeked",s(Ue.Seeked),i),qt("volumechange",s(Ue.VolumeChange),i),qt("ratechange",s(Ue.RateChange),i)];return wn(()=>{a.forEach(e=>e())})}(e);let u=()=>{},p=()=>{},h=()=>{},f=()=>{};e.recordDOM&&(u=function({styleSheetRuleCb:e,mirror:t,stylesheetManager:n},{win:r}){if(!r.CSSStyleSheet||!r.CSSStyleSheet.prototype)return()=>{};const o=r.CSSStyleSheet.prototype.insertRule;r.CSSStyleSheet.prototype.insertRule=new Proxy(o,{apply:wn((r,o,i)=>{const[s,a]=i,{id:c,styleId:l}=Tn(o,t,n.styleMirror);return(c&&-1!==c||l&&-1!==l)&&e({id:c,styleId:l,adds:[{rule:s,index:a}]}),r.apply(o,i)})}),r.CSSStyleSheet.prototype.addRule=function(e,t,n=this.cssRules.length){const o=`${e} { ${t} }`;return r.CSSStyleSheet.prototype.insertRule.apply(this,[o,n])};const i=r.CSSStyleSheet.prototype.deleteRule;let s,a;r.CSSStyleSheet.prototype.deleteRule=new Proxy(i,{apply:wn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=Tn(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,removes:[{index:s}]}),r.apply(o,i)})}),r.CSSStyleSheet.prototype.removeRule=function(e){return r.CSSStyleSheet.prototype.deleteRule.apply(this,[e])},r.CSSStyleSheet.prototype.replace&&(s=r.CSSStyleSheet.prototype.replace,r.CSSStyleSheet.prototype.replace=new Proxy(s,{apply:wn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=Tn(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,replace:s}),r.apply(o,i)})})),r.CSSStyleSheet.prototype.replaceSync&&(a=r.CSSStyleSheet.prototype.replaceSync,r.CSSStyleSheet.prototype.replaceSync=new Proxy(a,{apply:wn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=Tn(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,replaceSync:s}),r.apply(o,i)})}));const c={};_n("CSSGroupingRule")?c.CSSGroupingRule=r.CSSGroupingRule:(_n("CSSMediaRule")&&(c.CSSMediaRule=r.CSSMediaRule),_n("CSSConditionRule")&&(c.CSSConditionRule=r.CSSConditionRule),_n("CSSSupportsRule")&&(c.CSSSupportsRule=r.CSSSupportsRule));const l={};return Object.entries(c).forEach(([r,o])=>{l[r]={insertRule:o.prototype.insertRule,deleteRule:o.prototype.deleteRule},o.prototype.insertRule=new Proxy(l[r].insertRule,{apply:wn((r,o,i)=>{const[s,a]=i,{id:c,styleId:l}=Tn(o.parentStyleSheet,t,n.styleMirror);return(c&&-1!==c||l&&-1!==l)&&e({id:c,styleId:l,adds:[{rule:s,index:[...Mn(o),a||0]}]}),r.apply(o,i)})}),o.prototype.deleteRule=new Proxy(l[r].deleteRule,{apply:wn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=Tn(o.parentStyleSheet,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,removes:[{index:[...Mn(o),s]}]}),r.apply(o,i)})})}),wn(()=>{r.CSSStyleSheet.prototype.insertRule=o,r.CSSStyleSheet.prototype.deleteRule=i,s&&(r.CSSStyleSheet.prototype.replace=s),a&&(r.CSSStyleSheet.prototype.replaceSync=a),Object.entries(c).forEach(([e,t])=>{t.prototype.insertRule=l[e].insertRule,t.prototype.deleteRule=l[e].deleteRule})})}(e,{win:n}),p=Rn(e,e.doc),h=function({styleDeclarationCb:e,mirror:t,ignoreCSSAttributes:n,stylesheetManager:r},{win:o}){const i=o.CSSStyleDeclaration.prototype.setProperty;o.CSSStyleDeclaration.prototype.setProperty=new Proxy(i,{apply:wn((o,s,a)=>{var c;const[l,d,u]=a;if(n.has(l))return i.apply(s,[l,d,u]);const{id:p,styleId:h}=Tn(null==(c=s.parentRule)?void 0:c.parentStyleSheet,t,r.styleMirror);return(p&&-1!==p||h&&-1!==h)&&e({id:p,styleId:h,set:{property:l,value:d,priority:u},index:Mn(s.parentRule)}),o.apply(s,a)})});const s=o.CSSStyleDeclaration.prototype.removeProperty;return o.CSSStyleDeclaration.prototype.removeProperty=new Proxy(s,{apply:wn((o,i,a)=>{var c;const[l]=a;if(n.has(l))return s.apply(i,[l]);const{id:d,styleId:u}=Tn(null==(c=i.parentRule)?void 0:c.parentStyleSheet,t,r.styleMirror);return(d&&-1!==d||u&&-1!==u)&&e({id:d,styleId:u,remove:{property:l},index:Mn(i.parentRule)}),o.apply(i,a)})}),wn(()=>{o.CSSStyleDeclaration.prototype.setProperty=i,o.CSSStyleDeclaration.prototype.removeProperty=s})}(e,{win:n}),e.collectFonts&&(f=function({fontCb:e,doc:t}){const n=t.defaultView;if(!n)return()=>{};const r=[],o=/* @__PURE__ */new WeakMap,i=n.FontFace;n.FontFace=function(e,t,n){const r=new i(e,t,n);return o.set(r,{family:e,buffer:"string"!=typeof t,descriptors:n,fontSource:"string"==typeof t?t:JSON.stringify(Array.from(new Uint8Array(t)))}),r};const s=et(t.fonts,"add",function(t){return function(n){return setTimeout(wn(()=>{const t=o.get(n);t&&(e(t),o.delete(n))}),0),t.apply(this,[n])}});return r.push(()=>{n.FontFace=i}),r.push(s),wn(()=>{r.forEach(e=>e())})}(e)));const m=function(e){const{doc:t,mirror:n,blockClass:r,blockSelector:o,selectionCb:i}=e;let s=!0;const a=wn(()=>{const e=t.getSelection();if(!e||s&&(null==e?void 0:e.isCollapsed))return;s=e.isCollapsed||!1;const a=[],c=e.rangeCount||0;for(let t=0;t<c;t++){const{startContainer:i,startOffset:s,endContainer:c,endOffset:l}=e.getRangeAt(t);en(i,r,o,!0)||en(c,r,o,!0)||a.push({start:n.getId(i),startOffset:s,end:n.getId(c),endOffset:l})}i({ranges:a})});return a(),qt("selectionchange",a)}(e),g=function({doc:e,customElementCb:t}){const n=e.defaultView;return n&&n.customElements?et(n.customElements,"define",function(e){return function(n,r,o){try{t({define:{name:n}})}catch(i){console.warn(`Custom element callback failed for ${n}`)}return e.apply(this,[n,r,o])}}):()=>{}}(e),y=[];for(const b of e.plugins)y.push(b.observer(b.callback,n,b.options));return wn(()=>{xn.forEach(e=>e.reset()),r?.disconnect(),o(),i(),s(),a(),c(),l(),d(),u(),p(),h(),f(),m(),g(),y.forEach(e=>e())})}function An(e){return void 0!==window[e]}function _n(e){return Boolean(void 0!==window[e]&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}for(var Dn=class{constructor(e){Ne(this,"iframeIdToRemoteIdMap",/* @__PURE__ */new WeakMap),Ne(this,"iframeRemoteIdToIdMap",/* @__PURE__ */new WeakMap),this.generateIdFn=e}getId(e,t,n,r){const o=n||this.getIdToRemoteIdMap(e),i=r||this.getRemoteIdToIdMap(e);let s=o.get(t);return s||(s=this.generateIdFn(),o.set(t,s),i.set(s,t)),s}getIds(e,t){const n=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(t=>this.getId(e,t,n,r))}getRemoteId(e,t,n){const r=n||this.getRemoteIdToIdMap(e);return"number"!=typeof t?t:r.get(t)||-1}getRemoteIds(e,t){const n=this.getRemoteIdToIdMap(e);return t.map(t=>this.getRemoteId(e,t,n))}reset(e){if(!e)return this.iframeIdToRemoteIdMap=/* @__PURE__ */new WeakMap,void(this.iframeRemoteIdToIdMap=/* @__PURE__ */new WeakMap);this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=/* @__PURE__ */new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=/* @__PURE__ */new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}},Pn=class{constructor(e){Ne(this,"iframes",/* @__PURE__ */new WeakMap),Ne(this,"crossOriginIframeMap",/* @__PURE__ */new WeakMap),Ne(this,"crossOriginIframeMirror",new Dn(At)),Ne(this,"crossOriginIframeStyleMirror"),Ne(this,"crossOriginIframeRootIdMap",/* @__PURE__ */new WeakMap),Ne(this,"mirror"),Ne(this,"mutationCb"),Ne(this,"wrappedEmit"),Ne(this,"loadListener"),Ne(this,"stylesheetManager"),Ne(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Dn(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var n,r;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(n=e.contentWindow)||n.addEventListener("message",this.handleMessage.bind(this))),null==(r=this.loadListener)||r.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){const t=e;if("rrweb"!==t.data.type||t.origin!==t.data.origin)return;if(!e.source)return;const n=this.crossOriginIframeMap.get(e.source);if(!n)return;const r=this.transformCrossOriginEvent(n,t.data.event);r&&this.wrappedEmit(r,t.data.isCheckout)}transformCrossOriginEvent(e,t){var n;switch(t.type){case Fe.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);const n=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,n),this.patchRootIdOnNode(t.data.node,n),{timestamp:t.timestamp,type:Fe.IncrementalSnapshot,data:{source:ze.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Fe.Meta:case Fe.Load:case Fe.DomContentLoaded:return!1;case Fe.Plugin:return t;case Fe.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case Fe.IncrementalSnapshot:switch(t.data.source){case ze.Mutation:return t.data.adds.forEach(t=>{this.replaceIds(t,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(t.node,e);const n=this.crossOriginIframeRootIdMap.get(e);n&&this.patchRootIdOnNode(t.node,n)}),t.data.removes.forEach(t=>{this.replaceIds(t,e,["parentId","id"])}),t.data.attributes.forEach(t=>{this.replaceIds(t,e,["id"])}),t.data.texts.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case ze.Drag:case ze.TouchMove:case ze.MouseMove:return t.data.positions.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case ze.ViewportResize:return!1;case ze.MediaInteraction:case ze.MouseInteraction:case ze.Scroll:case ze.CanvasMutation:case ze.Input:return this.replaceIds(t.data,e,["id"]),t;case ze.StyleSheetRule:case ze.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case ze.Font:return t;case ze.Selection:return t.data.ranges.forEach(t=>{this.replaceIds(t,e,["start","end"])}),t;case ze.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),null==(n=t.data.styles)||n.forEach(t=>{this.replaceStyleIds(t,e,["styleId"])}),t}}return!1}replace(e,t,n,r){for(const o of r)(Array.isArray(t[o])||"number"==typeof t[o])&&(Array.isArray(t[o])?t[o]=e.getIds(n,t[o]):t[o]=e.getId(n,t[o]));return t}replaceIds(e,t,n){return this.replace(this.crossOriginIframeMirror,e,t,n)}replaceStyleIds(e,t,n){return this.replace(this.crossOriginIframeStyleMirror,e,t,n)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(e=>{this.replaceIdOnNode(e,t)})}patchRootIdOnNode(e,t){e.type===He.Document||e.rootId||(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(e=>{this.patchRootIdOnNode(e,t)})}},Ln=class{constructor(e){Ne(this,"shadowDoms",/* @__PURE__ */new WeakSet),Ne(this,"mutationCb"),Ne(this,"scrollCb"),Ne(this,"bypassOptions"),Ne(this,"mirror"),Ne(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!pt(e))return;if(this.shadowDoms.has(e))return;this.shadowDoms.add(e);const[n]=kn({...this.bypassOptions,doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>n.disconnect()),this.restoreHandlers.push(Cn({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(ct(e))),this.restoreHandlers.push(Rn({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){e.contentWindow&&e.contentDocument&&this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){const n=this;this.restoreHandlers.push(et(e.prototype,"attachShadow",function(e){return function(r){const o=e.call(this,r),i=lt(this);return i&&dn(this)&&n.addShadowRoot(i,t),o}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(t){}}),this.restoreHandlers=[],this.shadowDoms=/* @__PURE__ */new WeakSet}},Nn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Fn="undefined"==typeof Uint8Array?[]:/* @__PURE__ */new Uint8Array(256),zn=0;zn<64;zn++)Fn[Nn.charCodeAt(zn)]=zn;var $n=function(e){var t,n=new Uint8Array(e),r=n.length,o="";for(t=0;t<r;t+=3)o+=Nn[n[t]>>2],o+=Nn[(3&n[t])<<4|n[t+1]>>4],o+=Nn[(15&n[t+1])<<2|n[t+2]>>6],o+=Nn[63&n[t+2]];return r%3==2?o=o.substring(0,o.length-1)+"=":r%3==1&&(o=o.substring(0,o.length-2)+"=="),o},Bn=/* @__PURE__ */new Map,Wn=(e,t,n)=>{if(!e||!jn(e,t)&&"object"!=typeof e)return;const r=function(e,t){let n=Bn.get(e);return n||(n=/* @__PURE__ */new Map,Bn.set(e,n)),n.has(t)||n.set(t,[]),n.get(t)}(n,e.constructor.name);let o=r.indexOf(e);return-1===o&&(o=r.length,r.push(e)),o};function Un(e,t,n){if(e instanceof Array)return e.map(e=>Un(e,t,n));if(null===e)return e;if(e instanceof Float32Array||e instanceof Float64Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Int8Array||e instanceof Uint8ClampedArray)return{rr_type:e.constructor.name,args:[Object.values(e)]};if(e instanceof ArrayBuffer)return{rr_type:e.constructor.name,base64:$n(e)};if(e instanceof DataView)return{rr_type:e.constructor.name,args:[Un(e.buffer,t,n),e.byteOffset,e.byteLength]};if(e instanceof HTMLImageElement){const t=e.constructor.name,{src:n}=e;return{rr_type:t,src:n}}return e instanceof HTMLCanvasElement?{rr_type:"HTMLImageElement",src:e.toDataURL()}:e instanceof ImageData?{rr_type:e.constructor.name,args:[Un(e.data,t,n),e.width,e.height]}:jn(e,t)||"object"==typeof e?{rr_type:e.constructor.name,index:Wn(e,t,n)}:e}var Hn=(e,t,n)=>e.map(e=>Un(e,t,n)),jn=(e,t)=>{const n=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(e=>"function"==typeof t[e]);return Boolean(n.find(n=>e instanceof t[n]))};function qn(e,t,n,r){const o=[];try{const i=et(e.HTMLCanvasElement.prototype,"getContext",function(e){return function(o,...i){if(!en(this,t,n,!0)){const e=function(e){return"experimental-webgl"===e?"webgl":e}(o);if("__context"in this||(this.__context=e),r&&["webgl","webgl2"].includes(e))if(i[0]&&"object"==typeof i[0]){const e=i[0];e.preserveDrawingBuffer||(e.preserveDrawingBuffer=!0)}else i.splice(0,1,{preserveDrawingBuffer:!0})}return e.apply(this,[o,...i])}});o.push(i)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{o.forEach(e=>e())}}function Vn(e,t,n,r,o,i){const s=[],a=Object.getOwnPropertyNames(e);for(const c of a)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(c))try{if("function"!=typeof e[c])continue;const a=et(e,c,function(e){return function(...s){const a=e.apply(this,s);if(Wn(a,i,this),"tagName"in this.canvas&&!en(this.canvas,r,o,!0)){const e=Hn(s,i,this),r={type:t,property:c,args:e};n(this.canvas,r)}return a}});s.push(a)}catch{const r=Xt(e,c,{set(e){n(this.canvas,{type:t,property:c,args:[e],setter:!0})}});s.push(r)}return s}var Yn='(function() {\n "use strict";\n var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);\n for (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n }\n var encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";\n for (i2 = 0; i2 < len; i2 += 3) {\n base64 += chars[bytes[i2] >> 2];\n base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\n base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\n base64 += chars[bytes[i2 + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + "=";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + "==";\n }\n return base64;\n };\n const lastBlobMap = /* @__PURE__ */ new Map();\n const transparentBlobMap = /* @__PURE__ */ new Map();\n async function getTransparentBlobFor(width, height, dataURLOptions) {\n const id = `${width}-${height}`;\n if ("OffscreenCanvas" in globalThis) {\n if (transparentBlobMap.has(id)) return transparentBlobMap.get(id);\n const offscreen = new OffscreenCanvas(width, height);\n offscreen.getContext("2d");\n const blob = await offscreen.convertToBlob(dataURLOptions);\n const arrayBuffer = await blob.arrayBuffer();\n const base64 = encode(arrayBuffer);\n transparentBlobMap.set(id, base64);\n return base64;\n } else {\n return "";\n }\n }\n const worker = self;\n worker.onmessage = async function(e) {\n if ("OffscreenCanvas" in globalThis) {\n const { id, bitmap, width, height, dataURLOptions } = e.data;\n const transparentBase64 = getTransparentBlobFor(\n width,\n height,\n dataURLOptions\n );\n const offscreen = new OffscreenCanvas(width, height);\n const ctx = offscreen.getContext("2d");\n ctx.drawImage(bitmap, 0, 0);\n bitmap.close();\n const blob = await offscreen.convertToBlob(dataURLOptions);\n const type = blob.type;\n const arrayBuffer = await blob.arrayBuffer();\n const base64 = encode(arrayBuffer);\n if (!lastBlobMap.has(id) && await transparentBase64 === base64) {\n lastBlobMap.set(id, base64);\n return worker.postMessage({ id });\n }\n if (lastBlobMap.get(id) === base64) return worker.postMessage({ id });\n worker.postMessage({\n id,\n type,\n base64,\n width,\n height\n });\n lastBlobMap.set(id, base64);\n } else {\n return worker.postMessage({ id: e.data.id });\n }\n };\n})();\n//# sourceMappingURL=image-bitmap-data-url-worker-IJpC7g_b.js.map\n',Kn="undefined"!=typeof self&&self.Blob&&new Blob([Yn],{type:"text/javascript;charset=utf-8"});function Xn(e){let t;try{if(t=Kn&&(self.URL||self.webkitURL).createObjectURL(Kn),!t)throw"";const n=new Worker(t,{name:null==e?void 0:e.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch(n){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Yn),{name:null==e?void 0:e.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}var Gn,Jn,Zn,Qn=class{constructor(e){Ne(this,"pendingCanvasMutations",/* @__PURE__ */new Map),Ne(this,"rafStamps",{latestId:0,invokeId:null}),Ne(this,"mirror"),Ne(this,"mutationCb"),Ne(this,"resetObservers"),Ne(this,"frozen",!1),Ne(this,"locked",!1),Ne(this,"processMutation",(e,t)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(e)||this.pendingCanvasMutations.set(e,[]),this.pendingCanvasMutations.get(e).push(t)});const{sampling:t="all",win:n,blockClass:r,blockSelector:o,recordCanvas:i,dataURLOptions:s}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,i&&"all"===t&&this.initCanvasMutationObserver(n,r,o),i&&"number"==typeof t&&this.initCanvasFPSObserver(t,n,r,o,{dataURLOptions:s})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,n,r,o){const i=qn(t,n,r,!0),s=/* @__PURE__ */new Map,a=new Xn;a.onmessage=e=>{const{id:t}=e.data;if(s.set(t,!1),!("base64"in e.data))return;const{base64:n,type:r,width:o,height:i}=e.data;this.mutationCb({id:t,type:We["2D"],commands:[{property:"clearRect",args:[0,0,o,i]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:n}],type:r}]},0,0]}]})};const c=1e3/e;let l,d=0;const u=e=>{d&&e-d<c||(d=e,(()=>{const e=[];return t.document.querySelectorAll("canvas").forEach(t=>{en(t,n,r,!0)||e.push(t)}),e})().forEach(async e=>{var t;const n=this.mirror.getId(e);if(s.get(n))return;if(0===e.width||0===e.height)return;if(s.set(n,!0),["webgl","webgl2"].includes(e.__context)){const n=e.getContext(e.__context);!1===(null==(t=null==n?void 0:n.getContextAttributes())?void 0:t.preserveDrawingBuffer)&&n.clear(n.COLOR_BUFFER_BIT)}const r=await createImageBitmap(e);a.postMessage({id:n,bitmap:r,width:e.width,height:e.height,dataURLOptions:o.dataURLOptions},[r])})),l=requestAnimationFrame(u)};l=requestAnimationFrame(u),this.resetObservers=()=>{i(),cancelAnimationFrame(l)}}initCanvasMutationObserver(e,t,n){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=qn(e,t,n,!1),o=function(e,t,n,r){const o=[],i=Object.getOwnPropertyNames(t.CanvasRenderingContext2D.prototype);for(const s of i)try{if("function"!=typeof t.CanvasRenderingContext2D.prototype[s])continue;const i=et(t.CanvasRenderingContext2D.prototype,s,function(o){return function(...i){return en(this.canvas,n,r,!0)||setTimeout(()=>{const n=Hn(i,t,this);e(this.canvas,{type:We["2D"],property:s,args:n})},0),o.apply(this,i)}});o.push(i)}catch{const n=Xt(t.CanvasRenderingContext2D.prototype,s,{set(t){e(this.canvas,{type:We["2D"],property:s,args:[t],setter:!0})}});o.push(n)}return()=>{o.forEach(e=>e())}}(this.processMutation.bind(this),e,t,n),i=function(e,t,n,r){const o=[];return void 0!==t.WebGLRenderingContext&&o.push(...Vn(t.WebGLRenderingContext.prototype,We.WebGL,e,n,r,t)),void 0!==t.WebGL2RenderingContext&&o.push(...Vn(t.WebGL2RenderingContext.prototype,We.WebGL2,e,n,r,t)),()=>{o.forEach(e=>e())}}(this.processMutation.bind(this),e,t,n);this.resetObservers=()=>{r(),o(),i()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const n=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,n)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const n=this.pendingCanvasMutations.get(e);if(!n||-1===t)return;const r=n.map(e=>{const{type:t,...n}=e;return n}),{type:o}=n[0];this.mutationCb({id:t,type:o,commands:r}),this.pendingCanvasMutations.delete(e)}},er=class{constructor(e){Ne(this,"trackedLinkElements",/* @__PURE__ */new WeakSet),Ne(this,"mutationCb"),Ne(this,"adoptedStyleSheetCb"),Ne(this,"styleMirror",new cn),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(0===e.length)return;const n={id:t,styleIds:[]},r=[];for(const o of e){let e;this.styleMirror.has(o)?e=this.styleMirror.getId(o):(e=this.styleMirror.add(o),r.push({styleId:e,rules:Array.from(o.rules||CSSRule,(e,t)=>({rule:ft(e,o.href),index:t}))})),n.styleIds.push(e)}r.length>0&&(n.styles=r),this.adoptedStyleSheetCb(n)}reset(){this.styleMirror.reset(),this.trackedLinkElements=/* @__PURE__ */new WeakSet}trackStylesheetInLinkElement(e){}},tr=class{constructor(){Ne(this,"nodeMap",/* @__PURE__ */new WeakMap),Ne(this,"active",!1)}inOtherBuffer(e,t){const n=this.nodeMap.get(e);return n&&Array.from(n).some(e=>e!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=/* @__PURE__ */new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||/* @__PURE__ */new Set).add(t))}destroy(){}},nr=!1;try{if(2!==Array.from([1],e=>2*e)[0]){const e=document.createElement("iframe");document.body.appendChild(e),Array.from=(null==(_e=e.contentWindow)?void 0:_e.Array.from)||Array.from,document.body.removeChild(e)}}catch(Qd){}var rr=new mt;function or(e={}){const{emit:t,checkoutEveryNms:n,checkoutEveryNth:r,blockClass:o="rr-block",blockSelector:i=null,ignoreClass:s="rr-ignore",ignoreSelector:a=null,maskTextClass:c="rr-mask",maskTextSelector:l=null,inlineStylesheet:d=!0,maskAllInputs:u,maskInputOptions:p,slimDOMOptions:h,maskInputFn:f,maskTextFn:m,hooks:g,packFn:y,sampling:b={},dataURLOptions:v={},mousemoveWait:w,recordDOM:x=!0,recordCanvas:S=!1,recordCrossOriginIframes:k=!1,recordAfter:C=("DOMContentLoaded"===e.recordAfter?e.recordAfter:"load"),userTriggeredOnInput:E=!1,collectFonts:I=!1,inlineImages:M=!1,plugins:T,keepIframeSrcFn:R=()=>!1,ignoreCSSAttributes:O=/* @__PURE__ */new Set([]),errorHandler:A}=e;pn=A;const _=!k||window.parent===window;let D=!1;if(!_)try{window.parent.document&&(D=!1)}catch(V){D=!0}if(_&&!t)throw new Error("emit function is required");if(!_&&!D)return()=>{};void 0!==w&&void 0===b.mousemove&&(b.mousemove=w),rr.reset();const P=!0===u?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==p?p:{password:!0},L=Ut(h);let N;!function(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let F=0;const z=e=>{for(const t of T||[])t.eventProcessor&&(e=t.eventProcessor(e));return y&&!D&&(e=y(e)),e};Gn=(e,o)=>{var i;const s=e;if(s.timestamp=Qe(),!(null==(i=xn[0])?void 0:i.isFrozen())||s.type===Fe.FullSnapshot||s.type===Fe.IncrementalSnapshot&&s.data.source===ze.Mutation||xn.forEach(e=>e.unfreeze()),_)t?.(z(s),o);else if(D){const e={type:"rrweb",event:z(s),origin:window.location.origin,isCheckout:o};window.parent.postMessage(e,"*")}if(s.type===Fe.FullSnapshot)N=s,F=0;else if(s.type===Fe.IncrementalSnapshot){if(s.data.source===ze.Mutation&&s.data.isAttachIframe)return;F++;const e=r&&F>=r,t=n&&s.timestamp-N.timestamp>n;(e||t)&&Jn(!0)}};const $=e=>{Gn({type:Fe.IncrementalSnapshot,data:{source:ze.Mutation,...e}})},B=e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.Scroll,...e}}),W=e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.CanvasMutation,...e}}),U=new er({mutationCb:$,adoptedStyleSheetCb:e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.AdoptedStyleSheet,...e}})}),H=new Pn({mirror:rr,mutationCb:$,stylesheetManager:U,recordCrossOriginIframes:k,wrappedEmit:Gn});for(const K of T||[])K.getMirror&&K.getMirror({nodeMirror:rr,crossOriginIframeMirror:H.crossOriginIframeMirror,crossOriginIframeStyleMirror:H.crossOriginIframeStyleMirror});const j=new tr;Zn=new Qn({recordCanvas:S,mutationCb:W,win:window,blockClass:o,blockSelector:i,mirror:rr,sampling:b.canvas,dataURLOptions:v});const q=new Ln({mutationCb:$,scrollCb:B,bypassOptions:{blockClass:o,blockSelector:i,maskTextClass:c,maskTextSelector:l,inlineStylesheet:d,maskInputOptions:P,dataURLOptions:v,maskTextFn:m,maskInputFn:f,recordCanvas:S,inlineImages:M,sampling:b,slimDOMOptions:L,iframeManager:H,stylesheetManager:U,canvasManager:Zn,keepIframeSrcFn:R,processedNodeManager:j},mirror:rr});Jn=(e=!1)=>{if(!x)return;Gn({type:Fe.Meta,data:{href:window.location.href,width:Zt(),height:Jt()}},e),U.reset(),q.init(),xn.forEach(e=>e.lock());const t=function(e,t){const{mirror:n=new mt,blockClass:r="rr-block",blockSelector:o=null,maskTextClass:i="rr-mask",maskTextSelector:s=null,inlineStylesheet:a=!0,inlineImages:c=!1,recordCanvas:l=!1,maskAllInputs:d=!1,maskTextFn:u,maskInputFn:p,slimDOM:h=!1,dataURLOptions:f,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:b,onStylesheetLoad:v,stylesheetLoadTimeout:w,keepIframeSrcFn:x=()=>!1}=t;return Ht(e,{doc:e,mirror:n,blockClass:r,blockSelector:o,maskTextClass:i,maskTextSelector:s,skipChild:!1,inlineStylesheet:a,maskInputOptions:!0===d?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===d?{password:!0}:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:Ut(h),dataURLOptions:f,inlineImages:c,recordCanvas:l,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:b,onStylesheetLoad:v,stylesheetLoadTimeout:w,keepIframeSrcFn:x,newlyAddedElement:!1})}(document,{mirror:rr,blockClass:o,blockSelector:i,maskTextClass:c,maskTextSelector:l,inlineStylesheet:d,maskAllInputs:P,maskTextFn:m,maskInputFn:f,slimDOM:L,dataURLOptions:v,recordCanvas:S,inlineImages:M,onSerialize:e=>{on(e,rr)&&H.addIframe(e),sn(e,rr)&&U.trackLinkElement(e),an(e)&&q.addShadowRoot(lt(e),document)},onIframeLoad:(e,t)=>{H.attachIframe(e,t),q.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{U.attachLinkElement(e,t)},keepIframeSrcFn:R});if(!t)return console.warn("Failed to snapshot the document");Gn({type:Fe.FullSnapshot,data:{node:t,initialOffset:Gt(window)}},e),xn.forEach(e=>e.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&U.adoptStyleSheets(document.adoptedStyleSheets,rr.getId(document))};try{const e=[],t=e=>{var t;return wn(On)({mutationCb:$,mousemoveCb:(e,t)=>Gn({type:Fe.IncrementalSnapshot,data:{source:t,positions:e}}),mouseInteractionCb:e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.MouseInteraction,...e}}),scrollCb:B,viewportResizeCb:e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.ViewportResize,...e}}),inputCb:e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.Input,...e}}),mediaInteractionCb:e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.MediaInteraction,...e}}),styleSheetRuleCb:e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.StyleSheetRule,...e}}),styleDeclarationCb:e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.StyleDeclaration,...e}}),canvasMutationCb:W,fontCb:e=>Gn({type:Fe.IncrementalSnapshot,data:{source:ze.Font,...e}}),selectionCb:e=>{Gn({type:Fe.IncrementalSnapshot,data:{source:ze.Selection,...e}})},customElementCb:e=>{Gn({type:Fe.IncrementalSnapshot,data:{source:ze.CustomElement,...e}})},blockClass:o,ignoreClass:s,ignoreSelector:a,maskTextClass:c,maskTextSelector:l,maskInputOptions:P,inlineStylesheet:d,sampling:b,recordDOM:x,recordCanvas:S,inlineImages:M,userTriggeredOnInput:E,collectFonts:I,doc:e,maskInputFn:f,maskTextFn:m,keepIframeSrcFn:R,blockSelector:i,slimDOMOptions:L,dataURLOptions:v,mirror:rr,iframeManager:H,stylesheetManager:U,shadowDomManager:q,processedNodeManager:j,canvasManager:Zn,ignoreCSSAttributes:O,plugins:(null==(t=null==T?void 0:T.filter(e=>e.observer))?void 0:t.map(e=>({observer:e.observer,options:e.options,callback:t=>Gn({type:Fe.Plugin,data:{plugin:e.name,payload:t}})})))||[]},g)};H.addLoadListener(n=>{try{e.push(t(n.contentDocument))}catch(r){console.warn(r)}});const n=()=>{Jn(),e.push(t(document)),nr=!0};return["interactive","complete"].includes(document.readyState)?n():(e.push(qt("DOMContentLoaded",()=>{Gn({type:Fe.DomContentLoaded,data:{}}),"DOMContentLoaded"===C&&n()})),e.push(qt("load",()=>{Gn({type:Fe.Load,data:{}}),"load"===C&&n()},window))),()=>{e.forEach(e=>{try{e()}catch(t){String(t).toLowerCase().includes("cross-origin")||console.warn(t)}}),j.destroy(),nr=!1,pn=void 0}}catch(Y){console.warn(Y)}}or.addCustomEvent=(e,t)=>{if(!nr)throw new Error("please add custom event after start recording");Gn({type:Fe.Custom,data:{tag:e,payload:t}})},or.freezePage=()=>{xn.forEach(e=>e.freeze())},or.takeFullSnapshot=e=>{if(!nr)throw new Error("please take full snapshot after start recording");Jn(e)},or.mirror=rr;var ir=class extends Error{},sr=class e{static instance=null;abortController=null;chatId=null;status="disconnected";callbacks=/* @__PURE__ */new Set;tornDown=!1;credentialRejected=!1;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;maxReconnectDelay=3e4;reconnectTimer=null;connectionId=0;tabId=globalThis.crypto.randomUUID();registrationWaiters=/* @__PURE__ */new Set;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}addCallbacks(e){this.callbacks.add(e)}removeCallbacks(e){this.callbacks.delete(e)}isConnected(){return"registered"===this.status}reconnectSuppressed(){return this.tornDown||this.credentialRejected}canReconnect(){return null!==this.chatId&&!this.reconnectSuppressed()&&!this.isConnected()}reconnectNow(){this.canReconnect()&&null!==this.chatId&&(this.clearReconnectTimer(),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.connect(this.chatId).catch(console.error))}async ready(e){await this.connect(e),await this.waitUntilRegistered()}async waitUntilRegistered(){if(!this.isConnected()){if(this.credentialRejected)throw new ir("Chat is unavailable — the widget credentials were rejected.");await new Promise((e,t)=>this.registrationWaiters.add({resolve:e,reject:t}))}}async connect(e){if(this.credentialRejected)return;if(this.tornDown=!1,this.chatId===e&&("connecting"===this.status||"open"===this.status||"registered"===this.status))return;this.abortController&&(this.abortController.abort(),this.abortController=null),this.chatId=e,this.status="connecting";const t=++this.connectionId;this.abortController=new AbortController;const n=this.abortController.signal;try{const r=De.getCredentialedConfig(),o=await Me.widgetStream({chat_id:e,tab_id:this.tabId,...r&&{marketrix_id:r.mtxId,marketrix_key:r.mtxKey}},{signal:n});this.status="open",this.consumeEvents(o,t)}catch(r){n.aborted||(console.error("[StreamClient] Connection failed:",r),this.status="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.reconnectSuppressed()||(console.warn("[StreamClient] Stream error:",r),this.status="error")}finally{n||this.connectionId!==t||this.reconnectSuppressed()||(this.status="disconnected",this.scheduleReconnect())}}disconnect(){this.tornDown=!0,this.credentialRejected=!1,this.clearReconnectTimer(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.status="disconnected",this.chatId=null,this.settleWaiters(/* @__PURE__ */new Error("Stream disconnected before registration"))}send(e){return this.chatId?Me.widgetMessagePost({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"))}notifyError(e){this.callbacks.forEach(t=>t.onError?.(e))}settleWaiters(e){for(const t of this.registrationWaiters)t.reject(e);this.registrationWaiters.clear()}giveUp(e){const t=new ir(e);this.notifyError(t),this.settleWaiters(t)}handleMessage(e){if(!this.reconnectSuppressed()&&"heartbeat"!==e.type){if("registered"===e.type&&e.chat_id===this.chatId){this.status="registered",this.reconnectAttempts=0,this.reconnectDelay=1e3;for(const e of this.registrationWaiters)e.resolve();this.registrationWaiters.clear()}"chat/error"===e.type&&"auth"===e.request_id&&(console.error("[StreamClient] Authentication failed — will not reconnect"),this.credentialRejected=!0,this.giveUp("Chat is unavailable — the widget credentials were rejected.")),this.callbacks.forEach(t=>t.onMessage?.(e))}}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.giveUp("Could not reconnect to the assistant. Try again.");this.clearReconnectTimer(),this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);this.reconnectTimer=setTimeout(()=>{!this.reconnectSuppressed()&&this.chatId&&this.connect(this.chatId).catch(console.error)},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},ar=class{chatId;applicationId;events=[];sessionId=globalThis.crypto.randomUUID();stopRecording=null;flushTimer=null;flushPromise=Promise.resolve();stopped=!1;constructor(e,t){this.chatId=e,this.applicationId=t}async start(){this.stopRecording||this.stopped||(await sr.getInstance().ready(this.chatId),this.stopped||(await Me.widgetMessagePost({chat_id:this.chatId,command:{type:"rrweb/metadata",rrweb_session_id:this.sessionId,chat_id:this.chatId,application_id:this.applicationId,url:window.location.href,user_agent:navigator.userAgent,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}}}),this.stopped||(this.stopRecording=or({emit:e=>this.buffer(e),maskAllInputs:!0,maskTextClass:/^(rr-mask|mtx-mask)$/,blockClass:/^(rr-block|mtx-block)$/}))))}stop(){this.stopped=!0,this.stopRecording?.(),this.stopRecording=null,this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.flush()}buffer(e){this.events.push(e),this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flush()},500))}flush(){return this.flushPromise=this.flushPromise.then(async()=>{this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null;const e=this.events.splice(0);if(e.length)try{await Me.widgetMessagePost({chat_id:this.chatId,command:{type:"rrweb/events",rrweb_session_id:this.sessionId,events:e}})}catch(t){this.events=e.concat(this.events).slice(0,2e4),console.error("Failed to record session events:",t)}}),this.flushPromise}},cr=e=>"string"==typeof e,lr=e=>"boolean"==typeof e,dr=(...e)=>t=>"string"==typeof t&&e.includes(t),ur={widget_enabled:lr,widget_appearance:dr("default","hidden"),widget_position:dr("bottom_left","bottom_right","top_left","top_right"),widget_header:cr,widget_body:cr,widget_greeting:cr,widget_greeting_toast:lr,widget_recording:lr,widget_feature_tell:lr,widget_feature_show:lr,widget_feature_do:lr,widget_background_color:cr,widget_text_color:cr,widget_border_color:cr,widget_accent_color:cr,widget_secondary_color:cr,widget_border_radius:cr,widget_font_size:cr,widget_width:cr,widget_height:cr,widget_animation_duration:cr,widget_fade_duration:cr,widget_chips:e=>Array.isArray(e)&&e.every(e=>"object"==typeof e&&null!==e&&dr("tell","show","do")(e.chip_mode)&&cr(e.chip_text))},pr=Object.keys(ur);function hr(e){if("object"!=typeof e||null===e)return{invalidFields:["settings"]};const t=e,n=pr.filter(e=>!ur[e](t[e]));if(n.length>0)return{invalidFields:n};const r={};for(const o of pr)r[o]=t[o];return{settings:r}}var fr=e=>`Widget settings are invalid: ${e.join(", ")}`;function mr(e,t={}){return{...t,...e}}function gr(e){return e.mtxId??(null!=e.mtxApp?String(e.mtxApp):"default")}function yr(e){return e instanceof Error?e.message:"string"==typeof e?e:"Unknown error"}function br(e,t){const n=new Error(e);return n.cause=t,n}function vr(){}var wr=Object.freeze([]),xr=Object.freeze({});function Sr(t){e.useEffect(t,wr)}var kr={};function Cr(t,n){const r=e.useRef(kr);return r.current===kr&&(r.current=t(n)),r}var Er="undefined"!=typeof document?e.useLayoutEffect:()=>{},Ir=function(e,...t){const n=new URL("https://base-ui.com/production-error");return n.searchParams.set("code",e.toString()),t.forEach(e=>n.searchParams.append("args[]",e)),`Base UI error #${e}; visit ${n} for the full message.`},Mr=/*#__PURE__*/e.createContext(void 0);function Tr(){const t=e.useContext(Mr);if(!t)throw new Error(Ir(73));return t}var Rr=parseInt(e.version,10);function Or(e){return Rr>=e}var Ar,_r=Or(19)?function(t,n,r,o,i){return function(t,n,r,o,i){const s=e.useCallback(()=>n(t.getSnapshot(),r,o,i),[t,n,r,o,i]);return h(t.subscribe,s,s)}(t,n,r,o,i)}:function(e,t,n,r,o){return function(){throw new Error("React 19 uses its native useSyncExternalStore")}(e.subscribe,e.getSnapshot,e.getSnapshot)};function Dr(e,t,n,r,o){return _r(e,t,n,r,o)}Ar={before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let n=0;n<e.syncHooks.length;n+=1){const r=e.syncHooks[n],o=r.selector(r.store.state,r.a1,r.a2,r.a3);Object.is(r.value,o)||(t=!0,r.value=o)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const n=/* @__PURE__ */new Set;for(const o of e.syncHooks)n.add(o.store);const r=[];for(const e of n)r.push(e.subscribe(t));return()=>{for(const e of r)e()}}),h(e.subscribe,e.getSnapshot,e.getSnapshot))}},[].push(Ar);var Pr=class{constructor(e){this.state=e,this.listeners=/* @__PURE__ */new Set,this.updateTick=0}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.state;setState(e){if(this.state===e)return;this.state=e,this.updateTick+=1;const t=this.updateTick;for(const n of this.listeners){if(t!==this.updateTick)return;n(e)}}update(e){for(const t in e)if(!Object.is(this.state[t],e[t]))return void this.setState({...this.state,...e})}set(e,t){Object.is(this.state[e],t)||this.setState({...this.state,[e]:t})}notifyAll(){const e={...this.state};this.setState(e)}use(e,t,n,r){return Dr(this,e,t,n,r)}},Lr={...e},Nr=Lr.useInsertionEffect,Fr=Nr&&Nr!==Lr.useLayoutEffect?Nr:e=>e();function zr(e){const t=Cr($r).current;return t.next=e,Fr(t.effect),t.trampoline}function $r(){const e={next:void 0,callback:Br,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function Br(){}var Wr=class extends Pr{constructor(e,t={},n){super(e),this.context=t,this.selectors=n}useSyncedValue(t,n){e.useDebugValue(t);const r=this;Er(()=>{r.state[t]!==n&&r.set(t,n)},[r,t,n])}useSyncedValueWithCleanup(e,t){const n=this;Er(()=>(n.state[e]!==t&&n.set(e,t),()=>{n.set(e,void 0)}),[n,e,t])}useSyncedValues(e){const t=this,n=Object.values(e);Er(()=>{t.update(e)},[t,...n])}useControlledProp(t,n){e.useDebugValue(t);const r=this,o=void 0!==n;Er(()=>{o&&!Object.is(r.state[t],n)&&r.setState({...r.state,[t]:n})},[r,t,n,o])}select(e,t,n,r){return(0,this.selectors[e])(this.state,t,n,r)}useState(t,n,r,o){return e.useDebugValue(t),Dr(this,this.selectors[t],n,r,o)}useContextCallback(t,n){e.useDebugValue(t);const r=zr(n??vr);this.context[t]=r}useStateSetter(t){const n=e.useRef(void 0);return void 0===n.current&&(n.current=e=>{this.set(t,e)}),n.current}observe(e,t){let n;n="function"==typeof e?e:this.selectors[e];let r=n(this.state);return t(r,r,this),this.subscribe(e=>{const o=n(e);if(!Object.is(r,o)){const e=r;r=o,t(o,e,this)}})}};function Ur(){return"undefined"!=typeof window}function Hr(e){return qr(e)?(e.nodeName||"").toLowerCase():"#document"}function jr(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function qr(e){return!!Ur()&&(e instanceof Node||e instanceof jr(e).Node)}function Vr(e){return!!Ur()&&(e instanceof Element||e instanceof jr(e).Element)}function Yr(e){return!!Ur()&&(e instanceof HTMLElement||e instanceof jr(e).HTMLElement)}function Kr(e){return!(!Ur()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof jr(e).ShadowRoot)}function Xr(e){return/^(html|body|#document)$/.test(Hr(e))}function Gr(e){return jr(e).getComputedStyle(e)}function Jr(e){if("html"===Hr(e))return e;const t=e.assignedSlot||e.parentNode||Kr(e)&&e.host||function(e){var t;return null==(t=(qr(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}(e);return Kr(t)?t.host:t}function Zr(...e){return()=>{for(let t=0;t<e.length;t+=1){const n=e[t];n&&n()}}}function Qr(e){return e?.ownerDocument||document}function eo(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}var to=null;globalThis.requestAnimationFrame;var no=new class{callbacks=[];callbacksCount=0;nextId=1;startId=1;isScheduled=!1;tick=e=>{this.isScheduled=!1;const t=this.callbacks,n=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,n>0)for(let r=0;r<t.length;r+=1)t[r]?.(e)};request(e){const t=this.nextId;return this.nextId+=1,this.callbacks.push(e),this.callbacksCount+=1,this.isScheduled||(requestAnimationFrame(this.tick),this.isScheduled=!0),t}cancel(e){const t=e-this.startId;t<0||t>=this.callbacks.length||(this.callbacks[t]=null,this.callbacksCount-=1)}},ro=class e{static create(){return new e}static request(e){return no.request(e)}static cancel(e){return no.cancel(e)}currentId=to;request(e){this.cancel(),this.currentId=no.request(()=>{this.currentId=to,e()})}cancel=()=>{this.currentId!==to&&(no.cancel(this.currentId),this.currentId=to)};disposeEffect=()=>this.cancel};function oo(){const e=Cr(ro.create).current;return Sr(e.disposeEffect),e}var io=class e{static create(){return new e}currentId=0;start(e,t){this.clear(),this.currentId=setTimeout(()=>{this.currentId=0,t()},e)}isStarted(){return 0!==this.currentId}clear=()=>{0!==this.currentId&&(clearTimeout(this.currentId),this.currentId=0)};disposeEffect=()=>this.clear};function so(){const e=Cr(io.create).current;return Sr(e.disposeEffect),e}var ao=0;function co(e,t){if("string"==typeof e)return{description:e};if("function"==typeof e){const n=e(t);return"string"==typeof n?{description:n}:n}return e}var{userAgent:lo,platform:uo,maxTouchPoints:po}="undefined"==typeof navigator?{userAgent:"",platform:"",maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??0},ho=lo.toLowerCase(),fo=uo.toLowerCase(),mo=/^i(os$|p)/.test(fo)||"macintel"===fo&&po>1,go="android",yo=fo===go||ho.includes(go),bo=!mo&&fo.startsWith("mac"),vo=(fo.startsWith("win"),!yo&&/^(linux|chrome os)/.test(fo),bo||mo),wo="undefined"!=typeof CSS&&!!CSS.supports?.("-webkit-backdrop-filter:none"),xo=(!wo&&ho.includes("firefox"),!wo&&ho.includes("chrom"),vo),So=/jsdom|happydom/.test(ho),ko="data-base-ui-focusable";function Co(e){let t=e.activeElement;for(;null!=t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function Eo(e,t){if(!e||!t)return!1;const n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&Kr(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function Io(e){return"composedPath"in e?e.composedPath()[0]:e.target}function Mo(e,t){if(null==t)return!1;if("composedPath"in e)return e.composedPath().includes(t);const n=e;return null!=n.target&&t.contains(n.target)}function To(e){return Yr(e)&&e.matches("input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])")}function Ro(e){return!!e&&"combobox"===e.getAttribute("role")&&To(e)}function Oo(e){if(!e||So)return!0;try{return e.matches(":focus-visible")}catch(t){return!0}}function Ao(e){return e?e.hasAttribute("data-base-ui-focusable")?e:e.querySelector("[data-base-ui-focusable]")||e:null}function _o(e,t,n=!0){return e.filter(e=>e.parentId===t).flatMap(t=>[...!n||t.context?.open?[t]:[],..._o(e,t.id,n)])}function Do(e,t){let n=[],r=e.find(e=>e.id===t)?.parentId;for(;r;){const t=e.find(e=>e.id===r);r=t?.parentId,t&&(n=n.concat(t))}return n}function Po(e,t){return t<0||t>=e.length}function Lo(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:o=1}={}){let i=t;do{i+=n?-o:o}while(i>=0&&i<=e.length-1&&No(e,i,r));return i}function No(e,t,n){if("function"==typeof n?n(t):n?.includes(t))return!0;const r=e[t];return!!r&&(!Fo(r)||!!r.matches(":disabled")||!n&&(r.hasAttribute("disabled")||"true"===r.getAttribute("aria-disabled")))}function Fo(e,t=(e?Gr(e):null)){return!(!(e&&e.isConnected&&t)||function(e){return"hidden"===e.visibility||"collapse"===e.visibility}(t))&&("function"==typeof e.checkVisibility?e.checkVisibility():"none"!==t.display&&"contents"!==t.display)}function zo(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const n=e.getRootNode();return Kr(n)?n.host:null}function $o(e){for(const t of Array.from(e.children))if("summary"===Hr(t))return t;return null}function Bo(e,t){const n=$o(t);return!!n&&(e===n||Eo(n,e))}function Wo(e){const t=e?Hr(e):"";return null!=e&&e.matches('a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]')&&("summary"!==t||null!=e.parentElement&&"details"===Hr(e.parentElement)&&$o(e.parentElement)===e)&&("details"!==t||null==$o(e))&&("input"!==t||"hidden"!==e.type)}function Uo(e){if(!Wo(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=zo(t)){const n=t!==e,r="slot"===Hr(t);if(t.hasAttribute("inert"))return!1;if(n&&"details"===Hr(t)&&!t.open&&!Bo(e,t)||t.hasAttribute("hidden")||!r&&!Ho(t,n))return!1}return!0}function Ho(e,t){const n=Gr(e);return t?"none"!==n.display:Fo(e,n)}function jo(e){const t=e.tabIndex;if(t<0){const t=Hr(e);if("details"===t||"audio"===t||"video"===t||Yr(e)&&e.isContentEditable)return 0}return t}function qo(e){if("input"!==Hr(e))return null;const t=e;return"radio"===t.type&&""!==t.name?t:null}function Vo(e){if(Yr(e)&&"slot"===Hr(e)){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return Yr(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function Yo(e,t){Vo(e).forEach(e=>{Wo(e)&&t.push(e),Yo(e,t)})}function Ko(e,t,n){Vo(e).forEach(e=>{Yr(e)&&e.matches(t)&&n.push(e),Ko(e,t,n)})}function Xo(e){return Uo(e)&&jo(e)>=0}function Go(e){const t=[];return Yo(e,t),t.filter(Uo)}function Jo(e){const t=Go(e);return t.filter(e=>jo(e)>=0&&function(e,t){const n=qo(e);if(!n)return!0;const r=t.find(e=>{const t=qo(e);return t?.name===n.name&&t.form===n.form&&t.checked});return r?r===n:t.find(e=>{const t=qo(e);return t?.name===n.name&&t.form===n.form})===n}(e,t))}function Zo(e,t){const n=Jo(e),r=n.length;if(0===r)return;const o=Co(Qr(e)),i=n.indexOf(o);return n[-1===i?1===t?0:r-1:i+t]}function Qo(e){return Zo(Qr(e).body,1)||e}function ei(e){return Zo(Qr(e).body,-1)||e}function ti(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!Eo(n,r)}function ni(e){const t=[];Ko(e,"[data-tabindex]",t),t.forEach(e=>{const t=e.dataset.tabindex;delete e.dataset.tabindex,t?e.setAttribute("tabindex",t):e.removeAttribute("tabindex")})}function ri(e){const t=/* @__PURE__ */new Map;let n=0,r=0;return e.forEach((e,o)=>{const i="ending"===e.transitionStatus;t.set(e.id,{value:e,domIndex:o,visibleIndex:i?-1:n,offsetY:r}),r+=e.height||0,i||(n+=1)}),t}function oi(e,t){let n=0;return e.map(e=>{if("ending"===e.transitionStatus)return e;const r=n>=t;return n+=1,e.limited===r?e:{...e,limited:r}})}var ii={toasts:e=>e.toasts,isEmpty:e=>0===e.toasts.length,toast:(e,t)=>e.toastMetadata.get(t)?.value,toastIndex:(e,t)=>e.toastMetadata.get(t)?.domIndex??-1,toastOffsetY:(e,t)=>e.toastMetadata.get(t)?.offsetY??0,toastVisibleIndex:(e,t)=>e.toastMetadata.get(t)?.visibleIndex??-1,focused:e=>e.focused,expanded:e=>e.hovering||e.focused,expandedOrOutOfFocus:e=>e.hovering||e.focused||!e.isWindowFocused,prevFocusElement:e=>e.prevFocusElement},si=class extends Wr{timers=/* @__PURE__ */new Map;areTimersPaused=!1;constructor(e){super({...e,toastMetadata:ri(e.toasts)},{},ii)}setViewport=e=>{this.set("viewport",e)};syncProviderProps(e,t){const n=this.state.limit!==t;if(this.state.timeout===e&&!n)return;const r={timeout:e,limit:t};if(n){const e=oi(this.state.toasts,t);r.toasts=e,r.toastMetadata=ri(e)}this.update(r)}disposeEffect=()=>()=>{this.timers.forEach(e=>{e.timeout?.clear()}),this.timers.clear()};removeToast(e,t=!1){const n=ii.toastIndex(this.state,e);if(-1===n)return;const r=this.state.toasts[n];t||r?.onRemove?.();const o=[...this.state.toasts];o.splice(n,1),this.setToasts(o)}addToast=e=>{const{timeout:t,limit:n}=this.state,r=e.id||(ao+=1,`toast-${Math.random().toString(36).slice(2,6)}-${ao}`);if(e.id){const t=ii.toast(this.state,e.id);if(t){if("ending"!==t.transitionStatus){const{id:t,transitionStatus:n,...r}=e;return this.updateToastInternal(e.id,r,!0,!0),e.id}this.removeToast(e.id,!0)}}const o={...e,id:r,updateKey:0,transitionStatus:"starting"},i=[o,...this.state.toasts];this.setToasts(oi(i,n));const s=o.timeout??t;return"loading"!==o.type&&s>0&&this.scheduleTimer(r,s,()=>this.closeToast(r)),ii.expandedOrOutOfFocus(this.state)&&this.pauseTimers(),r};updateToast=(e,t)=>{this.updateToastInternal(e,t,!1,!0)};updateToastInternal=(e,t,n=!1,r=!1)=>{const{timeout:o,toasts:i}=this.state,s=ii.toast(this.state,e);if(!s)return;if("ending"===s.transitionStatus)return;const a={...s,...t,...r&&{updateKey:s.updateKey+1}};this.setToasts(i.map(t=>t.id===e?a:t));const c=a.timeout??o,l=s.timeout??o,d=Object.hasOwn(t,"timeout"),u="ending"!==a.transitionStatus&&"loading"!==a.type&&c>0,p=this.timers.has(e),h=l!==c,f="loading"===s.type;u||!p?u&&(!p||h||d||f||n)&&(this.clearTimer(e),this.scheduleTimer(e,c,()=>this.closeToast(e)),ii.expandedOrOutOfFocus(this.state)&&this.pauseTimers()):this.clearTimer(e)};closeToast=e=>{const t=void 0===e,{limit:n,toasts:r}=this.state;let o;if(t)o=r,this.clearTimers();else{const t=ii.toast(this.state,e);if(!t)return;o=[t],this.clearTimer(e)}const i=oi(r.map(n=>t||n.id===e?{...n,transitionStatus:"ending",height:0}:n),n);this.setToasts(i,!i.some(e=>"ending"!==e.transitionStatus)),o.forEach(e=>{"ending"!==e.transitionStatus&&e.onClose?.()}),this.handleFocusManagement(e)};promiseToast=(e,t)=>{const n=co(t.loading),r=this.addToast({...n,type:"loading"}),o=e.then(e=>{const n=co(t.success,e);return this.updateToast(r,{...n,type:"success",timeout:n.timeout}),e}).catch(e=>{const n=co(t.error,e);return this.updateToast(r,{...n,type:"error",timeout:n.timeout}),Promise.reject(e)});return{}.hasOwnProperty.call(t,"setPromise")&&t.setPromise(o),o};pauseTimers(){this.areTimersPaused||(this.areTimersPaused=!0,this.timers.forEach(e=>{e.timeout&&(e.timeout.clear(),e.remaining=Math.max(e.remaining-(Date.now()-e.start),0))}))}resumeTimers(){this.areTimersPaused&&(this.areTimersPaused=!1,this.timers.forEach((e,t)=>{e.remaining=e.remaining>0?e.remaining:e.delay,e.timeout??=io.create(),e.timeout.start(e.remaining,()=>{this.handleTimerFired(t),e.callback()}),e.start=Date.now()}))}restoreFocusToPrevElement(){this.state.prevFocusElement?.focus({preventScroll:!0})}handleDocumentPointerDown=e=>{if("touch"!==e.pointerType)return;const t=Io(e);Eo(this.state.viewport,t)||(this.resumeTimers(),this.update({hovering:!1,focused:!1}))};scheduleTimer(e,t,n){const r=Date.now(),o=ii.expandedOrOutOfFocus(this.state)?void 0:io.create();o?.start(t,()=>{this.handleTimerFired(e),n()}),this.timers.set(e,{timeout:o,start:r,delay:t,remaining:t,callback:n})}clearTimers(){this.timers.forEach(e=>{e.timeout?.clear()}),this.timers.clear(),this.areTimersPaused=!1}clearTimer(e){this.timers.get(e)?.timeout?.clear(),this.timers.delete(e),this.resetPausedStateIfNoTimersRemain()}handleTimerFired(e){this.timers.delete(e),this.resetPausedStateIfNoTimersRemain()}resetPausedStateIfNoTimersRemain(){0===this.timers.size&&(this.areTimersPaused=!1)}setToasts(e,t=0===e.length){const n={toasts:e,toastMetadata:ri(e)};t&&(n.hovering=!1,n.focused=!1),this.update(n)}handleFocusManagement(e){const t=Co(Qr(this.state.viewport));if(!this.state.viewport||!Eo(this.state.viewport,t)||!Oo(t))return;if(void 0===e)return void this.restoreFocusToPrevElement();const n=ii.toasts(this.state),r=ii.toastIndex(this.state,e),o=(e,t)=>{for(let r=e;r>=0&&r<n.length;r+=t)if("ending"!==n[r].transitionStatus)return n[r];return null},i=o(r+1,1)??o(r-1,-1);i?i.ref?.current?.focus():this.restoreFocusToPrevElement()}},ai=function(t){const{children:n,timeout:r=5e3,limit:o=3,toastManager:i}=t,s=Cr(()=>new si({timeout:r,limit:o,viewport:null,toasts:[],hovering:!1,focused:!1,isWindowFocused:!0,prevFocusElement:null})).current;return Sr(s.disposeEffect),e.useEffect(function(){if(i)return i[" subscribe"](({action:e,options:t})=>{const n=t.id;"promise"===e&&t.promise?s.promiseToast(t.promise,t):"update"===e&&n?s.updateToast(n,t):"close"===e?s.closeToast(n):s.addToast(t)})},[s,i]),/*#__PURE__*/b(Mr.Provider,{value:s,children:[/*#__PURE__*/y(ci,{store:s,timeout:r,limit:o}),n]})};function ci(e){const{store:t,timeout:n,limit:r}=e;return Er(()=>{t.syncProviderProps(n,r)},[t,n,r]),null}var li={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1,position:"fixed",top:0,left:0},di=/*#__PURE__*/e.forwardRef(function(t,n){const[r,o]=e.useState();return Er(()=>{xo&&wo&&o("button")},[]),/*#__PURE__*/y("span",{...t,ref:n,style:li,"aria-hidden":!r||void 0,tabIndex:0,role:r,"data-base-ui-focus-guard":""})});function ui(e,t,n,r){const o=Cr(pi).current;return function(e,t,n,r,o){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==o}(o,e,t,n,r)&&hi(o,[e,t,n,r]),o.callback}function pi(){return{callback:null,cleanup:null,refs:[]}}function hi(e,t){e.refs=t,t.every(e=>null==e)?e.callback=null:e.callback=n=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),null!=n){const r=Array(t.length).fill(null);for(let e=0;e<t.length;e+=1){const o=t[e];if(null!=o)switch(typeof o){case"function":{const t=o(n);"function"==typeof t&&(r[e]=t);break}case"object":o.current=n}}e.cleanup=()=>{for(let e=0;e<t.length;e+=1){const n=t[e];if(null!=n)switch(typeof n){case"function":{const t=r[e];"function"==typeof t?t():n(null);break}case"object":n.current=null}}}}}}function fi(t){if(!/*#__PURE__*/e.isValidElement(t))return null;const n=t,r=n.props;return(Or(19)?r?.ref:n.ref)??null}function mi(e,t){return e&&!t?e:!e&&t?t:e||t?{...e,...t}:void 0}var gi={};function yi(e,t,n,r,o){if(!(n||r||o||e))return bi(t);let i=bi(e);return t&&(i=vi(i,t)),n&&(i=vi(i,n)),r&&(i=vi(i,r)),o&&(i=vi(i,o)),i}function bi(e){return xi(e)?{...Si(e,gi)}:function(e){const t={...e};for(const n in t){const e=t[n];wi(n,e)&&(t[n]=Ci(e))}return t}(e)}function vi(e,t){return xi(t)?Si(t,e):function(e,t){if(!t)return e;for(const n in t){const r=t[n];switch(n){case"style":e[n]=mi(e.style,r);break;case"className":e[n]=Ii(e.className,r);break;default:wi(n,r)?e[n]=ki(e[n],r):e[n]=r}}return e}(e,t)}function wi(e,t){const n=e.charCodeAt(0),r=e.charCodeAt(1),o=e.charCodeAt(2);return 111===n&&110===r&&o>=65&&o<=90&&("function"==typeof t||void 0===t)}function xi(e){return"function"==typeof e}function Si(e,t){return xi(e)?e(t):e??gi}function ki(e,t){return t?e?(...n)=>{const r=n[0];if(Mi(r)){const o=r;Ei(o);const i=t(...n);return o.baseUIHandlerPrevented||e?.(...n),i}const o=t(...n);return e?.(...n),o}:Ci(t):e}function Ci(e){return e?(...t)=>{const n=t[0];return Mi(n)&&Ei(n),e(...t)}:e}function Ei(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function Ii(e,t){return t?e?t+" "+e:t:e}function Mi(e){return null!=e&&"object"==typeof e&&"nativeEvent"in e}function Ti(t,n,o={}){const i=n.render,s=function(e,t={}){const{className:n,style:r,render:o}=e,{state:i=xr,ref:s,props:a,stateAttributesMapping:c,enabled:l=!0}=t,d=l?function(e,t){return"function"==typeof e?e(t):e}(n,i):void 0,u=l?function(e,t){return"function"==typeof e?e(t):e}(r,i):void 0,p=l?function(e,t){const n={};for(const r in e){const o=e[r];if(t?.hasOwnProperty(r)){const e=t[r](o);null!=e&&Object.assign(n,e);continue}!0===o?n[`data-${r.toLowerCase()}`]="":o&&(n[`data-${r.toLowerCase()}`]=o.toString())}return n}(i,c):xr,h=l&&a?function(e){return Array.isArray(e)?function(e){if(0===e.length)return gi;if(1===e.length)return bi(e[0]);let t=bi(e[0]);for(let n=1;n<e.length;n+=1)t=vi(t,e[n]);return t}(e):yi(void 0,e)}(a):void 0,f=l?mi(p,h)??{}:xr;return"undefined"!=typeof document&&(l?Array.isArray(s)?f.ref=function(e){const t=Cr(pi).current;return function(e,t){return e.refs.length!==t.length||e.refs.some((e,n)=>e!==t[n])}(t,e)&&hi(t,e),t.callback}([f.ref,fi(o),...s]):f.ref=ui(f.ref,fi(o),s):ui(null,null)),l?(void 0!==d&&(f.className=Ii(f.className,d)),void 0!==u&&(f.style=mi(f.style,u)),f):xr}(n,o);return!1===o.enabled?null:function(t,n,o,i){if(n){if("function"==typeof n)return n(o,i);const t=yi(o,n.props);t.ref=o.ref;let r=n;return r?.$$typeof===Ri&&(r=e.Children.toArray(n)[0]),/*#__PURE__*/e.cloneElement(r,t)}if(t&&"string"==typeof t)return function(t,n){return"button"===t?/*#__PURE__*/r("button",{type:"button",...n,key:n.key}):"img"===t?/*#__PURE__*/r("img",{alt:"",...n,key:n.key}):/*#__PURE__*/e.createElement(t,n)}(t,o);throw new Error(Ir(8))}(t,i,s,o.state??xr)}var Ri=Symbol.for("react.lazy"),Oi=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,children:s,...a}=t,c=Tr(),l=so(),d=e.useRef(!1),u=e.useRef(!1),p=e.useRef(!1),h=c.useState("isEmpty"),f=c.useState("toasts"),m=c.useState("focused"),g=c.useState("expanded"),v=c.useState("prevFocusElement"),w=f[0]?.height,x=f.some(e=>"ending"===e.transitionStatus),S=f.filter(e=>"high"===e.priority);function k(){c.state.toasts.some(e=>"ending"===e.transitionStatus)||p.current||!u.current||(c.state.isWindowFocused&&c.resumeTimers(),c.set("hovering",!1),u.current=!1)}function C(){c.pauseTimers(),c.set("hovering",!0),u.current=!1}function E(e){"touch"===e.pointerType&&(p.current=!1,k())}function I(){d.current?d.current=!1:m||Oo(Co(Qr(c.state.viewport)))&&(c.set("focused",!0),c.pauseTimers())}e.useEffect(()=>{const e=c.state.viewport;if(!e||h)return;const t=jr(e),n=Qr(e);return Zr(eo(t,"keydown",function(t){"F6"===t.key&&Io(t)!==e&&(t.preventDefault(),c.set("prevFocusElement",Co(n)),e?.focus({preventScroll:!0}),c.pauseTimers(),c.set("focused",!0))}),eo(t,"blur",function(e){Io(e)===t&&(c.set("isWindowFocused",!1),c.pauseTimers())},!0),eo(t,"focus",function(n){if(n.relatedTarget)return;const r=Io(n),o=Co(Qr(e));r!==t&&Eo(e,r)&&Oo(o)||c.resumeTimers(),l.start(0,()=>c.set("isWindowFocused",!0))},!0),eo(n,"pointerdown",c.handleDocumentPointerDown,!0))},[c,l,h]),e.useEffect(k,[x,c]);const M={tabIndex:-1,role:"region","aria-live":"polite","aria-atomic":!1,"aria-relevant":"additions text","aria-label":"Notifications",onMouseEnter:C,onMouseMove:C,onMouseLeave:function(){u.current=!0,k()},onFocus:I,onBlur:function(e){m&&!Eo(c.state.viewport,e.relatedTarget)&&(c.set("focused",!1),c.state.isWindowFocused&&c.resumeTimers())},onKeyDown:function(e){"Tab"===e.key&&e.shiftKey&&Io(e.nativeEvent)===c.state.viewport&&(e.preventDefault(),c.restoreFocusToPrevElement())},onClick:I,onPointerDown:function(e){"touch"===e.pointerType&&(p.current=!0)},onPointerUp:E,onPointerCancel:E,style:{"--toast-frontmost-height":w?`${w}px`:void 0}},T={expanded:g},R=!h&&v&&/*#__PURE__*/y(di,{onFocus:function(e){d.current=!0;const t=e.relatedTarget===c.state.viewport?f.find(e=>"ending"!==e.transitionStatus&&!e.limited):void 0;t?t.ref?.current?.focus():c.restoreFocusToPrevElement()}}),O=Ti("div",t,{ref:[n,c.setViewport],state:T,props:[M,a,{children:/*#__PURE__*/b(e.Fragment,{children:[R,s,R]})}]});/*#__PURE__*/
2
+ return b(e.Fragment,{children:[R,O,!m&&S.length>0&&/*#__PURE__*/y("div",{style:li,children:S.map(e=>/*#__PURE__*/b("div",{role:"alert","aria-atomic":!0,children:[/*#__PURE__*/y("div",{children:e.title}),/*#__PURE__*/y("div",{children:e.description})]},e.id))})]})});function Ai(e){return Or(19)?e:e?"true":void 0}var _i=/*#__PURE__*/e.createContext(void 0);function Di(){const t=e.useContext(_i);if(!t)throw new Error(Ir(66));return t}var Pi=/*#__PURE__*/function(e){return e.startingStyle="data-starting-style",e.endingStyle="data-ending-style",e}({}),Li={"data-starting-style":""},Ni={"data-ending-style":""},Fi={transitionStatus:e=>"starting"===e?Li:"ending"===e?Ni:null};function zi(e){return null==e?e:"current"in e?e.current:e}function $i(t){const{enabled:n=!0,open:r,ref:o,onComplete:i}=t,s=zr(i),a=function(e,t=!1){const n=oo();return zr((r,o=null)=>{n.cancel();const i=zi(e);if(null==i)return;const s=i,a=()=>{m.flushSync(r)};if("function"!=typeof s.getAnimations||globalThis.BASE_UI_ANIMATIONS_DISABLED)r();else{if(t){const e="data-starting-style";if(!s.hasAttribute(e))return void n.request(c);const t=new MutationObserver(()=>{s.hasAttribute(e)||(t.disconnect(),c())});return t.observe(s,{attributes:!0,attributeFilter:[e]}),void o?.addEventListener("abort",()=>t.disconnect(),{once:!0})}n.request(c)}function c(){Promise.all(s.getAnimations().map(e=>e.finished)).then(()=>{o?.aborted||a()},()=>{o?.aborted||(s.getAnimations().some(e=>e.pending||"finished"!==e.playState)?c():a())})}})}(o,r);e.useEffect(()=>{if(!n)return;const e=new AbortController;return a(s,e.signal),()=>{e.abort()}},[n,r,s,a])}var Bi={clipPath:"inset(50%)",position:"fixed",top:0,left:0};function Wi(e,t,n){switch(e){case"up":return-n;case"down":return n;case"left":return-t;case"right":return t;default:return 0}}var Ui={...Fi,swipeDirection:e=>e?{"data-swipe-direction":e}:null},Hi=/*#__PURE__*/e.forwardRef(function(t,n){const{toast:r,render:o,className:i,swipeDirection:s=["down","right"],style:a,...c}=t,l=void 0!==r.positionerProps?.anchor;let d=[];l||(d=Array.isArray(s)?s:[s]);const u=d.length>0,p=Tr(),[h,f]=e.useState(void 0),[g,b]=e.useState(!1),[v,w]=e.useState(!1),[x,S]=e.useState({x:0,y:0}),[k,C]=e.useState({x:0,y:0,scale:1}),[E,I]=e.useState(),[M,T]=e.useState(),[R,O]=e.useState(null),A=e.useRef(null),_=e.useRef(void 0),D=e.useRef({x:0,y:0}),P=e.useRef({x:0,y:0,scale:1}),L=e.useRef(void 0),N=e.useRef(0),F=e.useRef(!1),z=e.useRef({x:0,y:0}),$=e.useRef(!1),B=e.useRef({x:0,y:0}),W=e.useRef(null),U=e.useRef(null),H=p.useState("toastIndex",r.id),j=p.useState("toastVisibleIndex",r.id),q=p.useState("toastOffsetY",r.id),V=p.useState("focused"),Y=p.useState("expanded");$i({open:"ending"!==r.transitionStatus,ref:A,onComplete(){"ending"===r.transitionStatus&&p.removeToast(r.id)}});const K=zr((e=!1)=>{const t=A.current;if(!t)return;const n=t.style.height;t.style.height="auto";const o=t.offsetHeight;function i(){p.updateToastInternal(r.id,{ref:A,height:o,transitionStatus:void 0})}t.style.height=n,e?m.flushSync(i):i()});function X(e){B.current=e,S(e)}Er(()=>{const e=_.current;"starting"!==r.transitionStatus&&e===r.id||(void 0!==e&&(f(void 0),C({x:0,y:0,scale:1}),X({x:0,y:0})),_.current=r.id,K())},[K,r.id,r.transitionStatus]),Er(()=>()=>{U.current?.abort()},[]);const G=zr(e=>{if(e.pointerId!==W.current)return;W.current=null,U.current?.abort(),U.current=null,b(!1),w(!1),O(null);const t=P.current;if("pointercancel"===e.type||F.current)return X({x:t.x,y:t.y}),void f(void 0);const n=B.current,o=n.x-t.x,i=n.y-t.y;let s;for(const r of d)if(Wi(r,o,i)>40){s=r;break}s?(f(s),p.closeToast(r.id)):(X({x:t.x,y:t.y}),f(void 0))});e.useEffect(()=>{const e=A.current;if(u&&e)return eo(e,"touchmove",function(t){null!==W.current&&Eo(e,Io(t))&&t.preventDefault()},{passive:!1})},[u]);const J="high"===r.priority,Z={role:J?"alertdialog":"dialog",tabIndex:0,"aria-modal":!1,"aria-labelledby":E,"aria-describedby":M,"aria-hidden":!(!J||V)||void 0,onPointerDown:u?function(e){if(0!==e.button)return;if("touch"===e.pointerType&&p.pauseTimers(),Io(e.nativeEvent)?.closest('button,a,input,textarea,[role="button"],[data-base-ui-swipe-ignore],[data-swipe-ignore]'))return;F.current=!1,L.current=void 0,N.current=0,W.current=e.pointerId,D.current={x:e.clientX,y:e.clientY},z.current=D.current;const t=e.currentTarget,n=function(e){const t=jr(e).getComputedStyle(e).transform;let n=0,r=0,o=1;if(t&&"none"!==t){const e=t.match(/matrix(?:3d)?\(([^)]+)\)/);if(e){const t=e[1].split(", ").map(parseFloat);6===t.length?(n=t[4],r=t[5],o=Math.sqrt(t[0]*t[0]+t[1]*t[1])):16===t.length&&(n=t[12],r=t[13],o=t[0])}}return{x:n,y:r,scale:o}}(t);P.current=n,C(n),X({x:n.x,y:n.y}),p.set("hovering",!0),b(!0),w(!1),O(null),$.current=!0,U.current?.abort();const r=new AbortController;U.current=r;const o=Qr(t);o.addEventListener("pointerup",G,{signal:r.signal}),o.addEventListener("pointercancel",G,{signal:r.signal}),t.setPointerCapture?.(e.pointerId)}:void 0,onPointerMove:u?function(e){if(e.pointerId!==W.current)return;e.preventDefault(),$.current&&(D.current={x:e.clientX,y:e.clientY},$.current=!1);const{clientY:t,clientX:n,movementX:r,movementY:o}=e;(o<0&&t>z.current.y||o>0&&t<z.current.y)&&(z.current={x:z.current.x,y:t}),(r<0&&n>z.current.x||r>0&&n<z.current.x)&&(z.current={x:n,y:z.current.y});const i=n-D.current.x,s=t-D.current.y,a=t-z.current.y,c=n-z.current.x;let l,u=R;if(!v&&Math.sqrt(i*i+s*s)>=1){w(!0);const e=d.includes("left")||d.includes("right"),t=d.includes("up")||d.includes("down");e&&t&&(u=Math.abs(i)>Math.abs(s)?"horizontal":"vertical",O(u))}if(L.current){const e=L.current,t=Wi(e,c,a);t>40?(F.current=!1,f(e)):d.includes("left")&&d.includes("right")||d.includes("up")&&d.includes("down")||!(N.current-t>=10)||(F.current=!0)}else"vertical"===u?s>0?l="down":s<0&&(l="up"):"horizontal"===u?i>0?l="right":i<0&&(l="left"):l=Math.abs(i)>=Math.abs(s)?i>0?"right":"left":s>0?"down":"up",l&&d.includes(l)&&(L.current=l,N.current=Wi(l,i,s),f(l));const p=function(e,t){const n=e=>e>0?e**.5:-(Math.abs(e)**.5),r=e>0&&!d.includes("right")||e<0&&!d.includes("left"),o=t>0&&!d.includes("down")||t<0&&!d.includes("up");return{x:r?n(e):e,y:o?n(t):t}}(i,s);let h=P.current.x,m=P.current.y;const g=d.includes("left")||d.includes("right"),y=d.includes("up")||d.includes("down");"vertical"!==u&&g&&(h+=p.x),"horizontal"!==u&&y&&(m+=p.y),X({x:h,y:m})}:void 0,onPointerUp:u?G:void 0,onPointerCancel:u?G:void 0,onKeyDown:function(e){if("Escape"===e.key){if(!A.current||!Eo(A.current,Co(Qr(A.current))))return;p.closeToast(r.id)}},inert:Ai(r.limited),style:{...function(){const e=x.x-k.x,t=x.y-k.y;return{transition:g?"none":void 0,transform:g?`translateX(${x.x}px) translateY(${x.y}px) scale(${k.scale})`:void 0,"--toast-swipe-movement-x":`${e}px`,"--toast-swipe-movement-y":`${t}px`}}(),"--toast-index":"ending"===r.transitionStatus?H:j,"--toast-offset-y":`${q}px`,"--toast-height":r.height?`${r.height}px`:void 0}},Q=e.useMemo(()=>({toast:r,setTitleId:I,setDescriptionId:T,recalculateHeight:K,visibleIndex:j,expanded:Y}),[r,I,T,K,j,Y]),ee={transitionStatus:r.transitionStatus,expanded:Y,limited:r.limited||!1,type:r.type,swiping:g,swipeDirection:h},te=Ti("div",t,{ref:[n,A],state:ee,stateAttributesMapping:Ui,props:[Z,c]});/*#__PURE__*/
3
+ return y(_i.Provider,{value:Q,children:te})}),ji=0,qi=Lr.useId;function Vi(t,n){if(void 0!==qi){const e=qi();return t??(n?`${n}-${e}`:e)}return function(t,n="mui"){const[r,o]=e.useState(t),i=t||r;return e.useEffect(()=>{null==r&&o(`${n}-${ji+=1}`)},[r,n]),i}(t,n)}function Yi(e){return null!=e&&"boolean"!=typeof e&&""!==e&&(!Array.isArray(e)||e.some(Yi))}function Ki(t){/*#__PURE__*/
4
+ return e.isValidElement(t)&&Yi(t.props.children)}function Xi(e,t,n){const{toast:r,setTitleId:o,setDescriptionId:i}=Di(),s="title"===n?o:i,a=t??("title"===n?r.title:r.description);return{id:Vi(e),children:a,type:r.type,setId:s}}function Gi(e,t,n){const r=Ki(e);return Er(()=>{if(r)return n(t),()=>{n(e=>e===t?void 0:e)}},[r,t,n]),r?e:null}var Ji=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,children:s,...a}=e,{id:c,children:l,type:d,setId:u}=Xi(i,s,"description");return Gi(Ti("p",e,{ref:t,state:{type:d},props:{...a,id:c,children:l}}),c,u)}),Zi=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,children:s,...a}=e,{id:c,children:l,type:d,setId:u}=Xi(i,s,"title");return Gi(Ti("h2",e,{ref:t,state:{type:d},props:{...a,id:c,children:l}}),c,u)}),Qi=/*#__PURE__*/e.createContext(void 0);function es(t=!1){const n=e.useContext(Qi);if(void 0===n&&!t)throw new Error(Ir(16));return n}function ts(e,t,{detail:n=0}={}){e.dispatchEvent(new(jr(e).PointerEvent)("click",{bubbles:!0,cancelable:!0,composed:!0,detail:n,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function ns(t={}){const{disabled:n=!1,focusableWhenDisabled:r,tabIndex:o=0,native:i=!0,composite:s}=t,a=e.useRef(null),c=es(!0),l=s??void 0!==c,{props:d}=function(t){const{focusableWhenDisabled:n,disabled:r,composite:o=!1,tabIndex:i=0,isNativeButton:s}=t,a=o&&!1!==n,c=o&&!1===n;return{props:e.useMemo(()=>{const e={onKeyDown(e){r&&n&&"Tab"!==e.key&&e.preventDefault()}};return o||(e.tabIndex=i,!s&&r&&(e.tabIndex=n?i:-1)),(s&&(n||a)||!s&&r)&&(e["aria-disabled"]=r),!s||n&&!c||(e.disabled=r),e},[o,r,n,a,c,s,i])}}({focusableWhenDisabled:r,disabled:n,composite:l,tabIndex:o,isNativeButton:i}),u=e.useCallback(()=>{const e=a.current;rs(e)&&l&&n&&void 0===d.disabled&&e.disabled&&(e.disabled=!1)},[n,d.disabled,l]);return Er(u,[u]),{getButtonProps:e.useCallback((e={})=>{const{onClick:t,onMouseDown:r,onKeyUp:o,onKeyDown:s,onPointerDown:a,...c}=e;return yi({onClick(e){n?e.preventDefault():t?.(e)},onMouseDown(e){n||r?.(e)},onKeyDown(e){if(n)return;if(Ei(e),s?.(e),e.baseUIHandlerPrevented)return;const t=e.target===e.currentTarget,r=e.currentTarget,o=rs(r),a=!i&&Yr(c=r)&&"A"===c.tagName&&Boolean(c.href);var c;const d=t&&(i?o:!a),u="Enter"===e.key,p=" "===e.key,h=r.getAttribute("role"),f=h?.startsWith("menuitem")||"option"===h||"gridcell"===h;if(t&&l&&p){if(e.defaultPrevented&&f)return;return e.preventDefault(),void(i&&!o||(e.preventBaseUIHandler(),ts(r,e)))}d&&!i&&(p||u)?e.defaultPrevented||(e.preventDefault(),u&&(e.preventBaseUIHandler(),ts(r,e))):t&&a&&p&&e.preventDefault()},onKeyUp(e){n||(Ei(e),o?.(e),e.target===e.currentTarget&&i&&l&&rs(e.currentTarget)&&" "===e.key?e.preventDefault():e.baseUIHandlerPrevented||e.target!==e.currentTarget||i||l||e.defaultPrevented||" "!==e.key||(e.preventBaseUIHandler(),ts(e.currentTarget,e)))},onPointerDown(e){n?e.preventDefault():a?.(e)}},i?{type:"button"}:{role:"button"},d,c)},[n,d,l,i]),buttonRef:zr(e=>{a.current=e,u()})}}function rs(e){return Yr(e)&&"BUTTON"===e.tagName}var os=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,disabled:s,nativeButton:a=!0,...c}=t,l=Tr(),{toast:d,expanded:u}=Di(),[p,h]=e.useState(!1),{getButtonProps:f,buttonRef:m}=ns({disabled:s,native:a});return Ti("button",t,{ref:[n,m],state:{type:d.type},props:[{"aria-hidden":!u&&!p,onClick(){l.closeToast(d.id)},onFocus(){h(!0)},onBlur(){h(!1)}},c,f]})}),is=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,disabled:i,nativeButton:s=!0,...a}=e,{toast:c}=Di(),l=c.actionProps?.children??a.children,{getButtonProps:d,buttonRef:u}=ns({disabled:i,native:s}),p=Ti("button",e,{ref:[t,u],state:{type:c.type},props:[a,c.actionProps,d,{children:l}]});return Ki(p)?p:null}),ss="none",as="missing",cs="initial";function ls(e,t,n,r){let o=!1,i=!1;const s=r??xr;return{reason:e,event:t??new Event("base-ui"),cancel(){o=!0},allowPropagation(){i=!0},get isCanceled(){return o},get isPropagationAllowed(){return i},trigger:n,...s}}function ds(e){return`data-base-ui-${e}`}var us=/*#__PURE__*/e.createContext(null),ps=()=>e.useContext(us),hs=ds("portal");function fs(t={}){const{ref:n,container:r,componentProps:o=xr,elementProps:i}=t,s=Vi(),a=ps()?.portalNode,[c,l]=e.useState(null),[d,u]=e.useState(null),p=zr(e=>{null!==e&&u(e)}),h=e.useRef(null);Er(()=>{if(null===r)return void(h.current&&(h.current=null,u(null),l(null)));const e=(r&&(qr(r)?r:r.current))??a??document.body;null!=e?h.current!==e&&(h.current=e,u(null),l(e)):h.current&&(h.current=null,u(null),l(null))},[r,a]);const f=Ti("div",o,{ref:[n,p],props:[{id:s,[hs]:""},i]}),g=c&&f?/*#__PURE__*/m.createPortal(f,c):null;return{node:d,nodeId:/*#__PURE__*/e.isValidElement(f)?f.props.id:void 0,subtree:g}}var ms=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,children:s,container:a,...c}=t,{node:l,nodeId:d,subtree:u}=fs({container:a,ref:n,componentProps:t,elementProps:c}),p=e.useRef(null),h=e.useRef(null),f=e.useRef(null),g=e.useRef(null),[v,w]=e.useState(null),x=e.useRef(!1),S=v?.modal,k=v?.open,C=!!v&&!v.modal&&v.open&&!!l;e.useEffect(()=>{if(l&&!S)return Zr(eo(l,"focusin",e,!0),eo(l,"focusout",e,!0));function e(e){l&&e.relatedTarget&&ti(e)&&("focusin"===e.type?x.current&&(ni(l),x.current=!1):(function(e){Jo(e).forEach(e=>{e.dataset.tabindex=e.getAttribute("tabindex")||"",e.setAttribute("tabindex","-1")})}(l),x.current=!0))}},[l,S]),Er(()=>{l&&!0===k&&x.current&&(ni(l),x.current=!1)},[k,l]);const E=e.useMemo(()=>({beforeOutsideRef:p,afterOutsideRef:h,beforeInsideRef:f,afterInsideRef:g,portalNode:l,setFocusManagerState:w}),[l]);/*#__PURE__*/
5
+ return b(e.Fragment,{children:[u,/*#__PURE__*/b(us.Provider,{value:E,children:[C&&l&&/*#__PURE__*/y(di,{"data-type":"outside",ref:p,onFocus:e=>{if(ti(e,l))f.current?.focus();else{const e=v?v.domReference:null;ei(e)?.focus()}}}),C&&l&&/*#__PURE__*/y("span",{"aria-owns":d,style:Bi}),l&&/*#__PURE__*/m.createPortal(s,l),C&&l&&/*#__PURE__*/y(di,{"data-type":"outside",ref:h,onFocus:e=>{if(ti(e,l))g.current?.focus();else{const t=v?v.domReference:null;Qo(t)?.focus(),v?.closeOnFocusOut&&v?.onOpenChange(!1,ls("focus-out",e.nativeEvent))}}})]})]})}),gs=/*#__PURE__*/e.forwardRef(function(t,n){const{children:r,container:o,className:i,render:s,style:a,...c}=t,{node:l,subtree:d}=fs({container:o,ref:n,componentProps:t,elementProps:c});return d||l?/*#__PURE__*/b(e.Fragment,{children:[d,l&&/*#__PURE__*/m.createPortal(r,l)]}):null}),ys=/*#__PURE__*/e.forwardRef(function(e,t){/*#__PURE__*/
6
+ return y(gs,{ref:t,...e})});function bs(e){const t=Cr(vs,e).current;return t.next=e,Er(t.effect),t}function vs(e){const t={current:e,next:e,effect:()=>{t.current=t.next}};return t}var ws=0;function xs(e,t={}){const{preventScroll:n=!1,sync:r=!1,shouldFocus:o}=t;function i(){o&&!o()||e?.focus({preventScroll:n})}if(cancelAnimationFrame(ws),r)return i(),vr;const s=requestAnimationFrame(i);return ws=s,()=>{ws===s&&(cancelAnimationFrame(s),ws=0)}}var Ss={inert:/* @__PURE__ */new WeakMap,"aria-hidden":/* @__PURE__ */new WeakMap},ks="data-base-ui-inert",Cs={inert:/* @__PURE__ */new WeakSet,"aria-hidden":/* @__PURE__ */new WeakSet},Es=/* @__PURE__ */new WeakMap,Is=0;function Ms(e){return e?Kr(e)?e.host:Ms(e.parentNode):null}var Ts=(e,t)=>t.map(t=>{if(e.contains(t))return t;const n=Ms(t);return e.contains(n)?n:null}).filter(e=>null!=e),Rs=e=>{const t=/* @__PURE__ */new Set;return e.forEach(e=>{let n=e;for(;n&&!t.has(n);)t.add(n),n=n.parentNode}),t},Os=(e,t,n)=>{const r=[],o=e=>{e&&!n.has(e)&&Array.from(e.children).forEach(e=>{"script"!==Hr(e)&&(t.has(e)?o(e):r.push(e))})};return o(e),r};function As(e,t={}){const{ariaHidden:n=!1,inert:r=!1,mark:o=!0}=t;return function(e,t,n,r,{mark:o=!0}){let i=null;r?i="inert":n&&(i="aria-hidden");let s=null,a=null;const c=Ts(t,e),l=o?Os(t,Rs(c),new Set(c)):[],d=[],u=[];if(i){const e=Ss[i],n=function(e){return Cs[e]}(i);a=n,s=e;const r=Ts(t,Array.from(t.querySelectorAll("[aria-live]"))),o=c.concat(r);Os(t,Rs(o),new Set(o)).forEach(t=>{const r=t.getAttribute(i),o=null!==r&&"false"!==r,s=(e.get(t)||0)+1;e.set(t,s),d.push(t),1===s&&o&&n.add(t),o||t.setAttribute(i,"inert"===i?"":"true")})}return o&&l.forEach(e=>{const t=(Es.get(e)||0)+1;Es.set(e,t),u.push(e),1===t&&e.setAttribute(ks,"")}),Is+=1,()=>{s&&d.forEach(e=>{const t=(s.get(e)||0)-1;s.set(e,t),t||(!a?.has(e)&&i&&e.removeAttribute(i),a?.delete(e))}),o&&u.forEach(e=>{const t=(Es.get(e)||0)-1;Es.set(e,t),t||e.removeAttribute(ks)}),(Is-=1)||(Ss.inert=/* @__PURE__ */new WeakMap,Ss["aria-hidden"]=/* @__PURE__ */new WeakMap,Cs.inert=/* @__PURE__ */new WeakSet,Cs["aria-hidden"]=/* @__PURE__ */new WeakSet,Es=/* @__PURE__ */new WeakMap)}}(e,Qr(e[0]).body,n,r,{mark:o})}function _s(){const e=/* @__PURE__ */new Map;return{emit(t,n){e.get(t)?.forEach(e=>e(n))},on(t,n){e.has(t)||e.set(t,/* @__PURE__ */new Set),e.get(t).add(n)},off(t,n){e.get(t)?.delete(n)}}}var Ds=/*#__PURE__*/e.createContext(null),Ps=/*#__PURE__*/e.createContext(null),Ls=t=>{const n=e.useContext(Ps);return t??n},Ns=[];function Fs(){Ns=Ns.filter(e=>e.deref()?.isConnected)}function zs(e){Fs(),e&&"body"!==Hr(e)&&(Ns.push(new WeakRef(e)),Ns.length>20&&(Ns=Ns.slice(-20)))}function $s(){return Fs(),Ns[Ns.length-1]?.deref()}function Bs(e){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex"))return;if(!e.getAttribute("role")?.includes("dialog"))return;const t=Go(e).filter(e=>{const t=e.getAttribute("data-tabindex")||"";return Xo(e)||e.hasAttribute("data-tabindex")&&!t.startsWith("-")}),n=e.getAttribute("tabindex");0===t.length?"0"!==n&&(e.setAttribute("tabindex","0"),e.setAttribute("data-tabindex","0")):("-1"!==n||e.hasAttribute("data-tabindex")&&"-1"!==e.getAttribute("data-tabindex"))&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function Ws(t){const{context:n,children:r,disabled:o=!1,initialFocus:i=!0,returnFocus:s=!0,restoreFocus:a=!1,modal:c=!0,closeOnFocusOut:l=!0,openInteractionType:d="",nextFocusableElement:u,previousFocusableElement:p,beforeContentFocusGuardRef:h,externalTree:f,getInsideElements:m}=t,g="rootStore"in n?n.rootStore:n,v=g.useState("open"),w=g.useState("domReferenceElement"),x=g.useState("floatingElement"),{events:S,dataRef:k}=g.context,C=zr(()=>k.current.floatingContext?.nodeId),E=!1===i,I=Ro(w)&&E,M=bs(i),T=bs(s),R=bs(d),O=bs(v),A=Ls(f),_=ps(),D=e.useRef(!1),P=e.useRef(!1),L=e.useRef(!1),N=e.useRef(null),F=e.useRef(""),z=e.useRef(""),$=e.useRef(null),B=e.useRef(null),W=ui($,h,_?.beforeInsideRef),U=ui(B,_?.afterInsideRef),H=so(),j=so(),q=oo(),V=null!=_,Y=Ao(x),K=zr((e=Y)=>e?Jo(e):[]),X=zr(()=>m?.().filter(e=>null!=e)??[]);e.useEffect(()=>{if(!o&&c)return eo(Qr(Y),"keydown",function(e){"Tab"===e.key&&Eo(Y,Co(Qr(Y)))&&0===K().length&&!I&&function(e){e.preventDefault(),e.stopPropagation()}(e)})},[o,Y,c,I,K]),e.useEffect(()=>{if(o||!v)return;const e=Qr(Y);function t(){L.current=!1}return Zr(eo(e,"pointerdown",function(e){const t=Io(e),n=X(),r=Eo(x,t)||Eo(w,t)||Eo(_?.portalNode,t)||n.some(e=>e===t||Eo(e,t));L.current=!r,z.current=e.pointerType||"keyboard",t?.closest("[data-base-ui-click-trigger]")&&(P.current=!0,j.start(0,()=>{P.current=!1}))},!0),eo(e,"pointerup",t,!0),eo(e,"pointercancel",t,!0),eo(e,"keydown",function(){z.current="keyboard"},!0),t)},[o,x,w,Y,v,_,j,X]),e.useEffect(()=>{if(o||!l)return;const e=Qr(Y);function t(t){const n=t.relatedTarget,r=t.currentTarget,o=Io(t);c&&null==n&&null!=o&&Eo(x,o)&&zs(o),queueMicrotask(()=>{const i=C(),s=g.context.triggerElements,l=X(),d=n?.hasAttribute(ds("focus-guard"))&&[$.current,B.current,_?.beforeInsideRef.current,_?.afterInsideRef.current,_?.beforeOutsideRef.current,_?.afterOutsideRef.current,zi(p),zi(u)].includes(n),h=!(Eo(w,n)||Eo(x,n)||Eo(n,x)||Eo(_?.portalNode,n)||l.some(e=>e===n||Eo(e,n))||s.hasMatchingElement(e=>Eo(e,n))||d||A&&(_o(A.nodesRef.current,i).find(e=>Eo(e.context?.elements.floating,n)||Eo(e.context?.elements.domReference,n))||Do(A.nodesRef.current,i).find(e=>[e.context?.elements.floating,Ao(e.context?.elements.floating)].includes(n)||e.context?.elements.domReference===n)));if(r===w&&Y&&Bs(Y),a&&r!==w&&!Fo(o)&&Co(e)===e.body){if(Yr(Y)&&(Y.focus(),"popup"===a))return void q.request(()=>{Y.focus()});const e=K(),t=N.current,n=(t&&e.includes(t)?t:null)||e[e.length-1]||Y;Yr(n)&&n.focus()}k.current.insideReactTree?k.current.insideReactTree=!1:!I&&c||!n||!h||P.current||!I&&n===$s()||(D.current=!0,g.setOpen(!1,ls("focus-out",t)))})}const n=Yr(w)?w:null;return x||n?Zr(n&&eo(n,"focusout",t),n&&eo(n,"pointerdown",function(){P.current=!0,j.start(0,()=>{P.current=!1})}),x&&eo(x,"focusin",function(e){const t=Io(e);Xo(t)&&(N.current=t)}),x&&eo(x,"focusout",t),x&&_&&eo(x,"focusout",function(){L.current||(k.current.insideReactTree=!0,H.start(0,()=>{k.current.insideReactTree=!1}))},!0)):void 0},[o,w,x,Y,c,A,_,g,l,a,K,I,C,k,H,j,q,u,p,X]),e.useEffect(()=>{if(o||!x||!v)return;const e=Array.from(_?.portalNode?.querySelectorAll(`[${ds("portal")}]`)||[]),t=(A?Do(A.nodesRef.current,C()):[]).find(e=>Ro(e.context?.elements.domReference||null))?.context?.elements.domReference,n=As([x,...e,$.current,B.current,_?.beforeOutsideRef.current,_?.afterOutsideRef.current,...X(),t,zi(p),zi(u),I?w:null].filter(e=>null!=e),{ariaHidden:c||I,mark:!1}),r=As([x,...e].filter(e=>null!=e));return()=>{r(),n()}},[v,o,w,x,c,_,I,A,C,u,p,X]),Er(()=>{if(!v||o||!Yr(Y))return;F.current="",z.current="";const e=Qr(Y),t=Co(e);queueMicrotask(()=>{const n=M.current,r="function"==typeof n?n(R.current||""):n;if(void 0===r||!1===r)return;if(Eo(Y,t))return;let o=null;const i=()=>(null==o&&(o=K(Y)),o[0]||Y);let s;s=!0===r||null===r?i():zi(r),s=s||i();const a=Eo(Y,Co(e));xs(s,{preventScroll:s===Y,shouldFocus(){if(!O.current)return!1;if(a)return!0;const t=Co(e);return!(t!==s&&Eo(Y,t))}})})},[o,v,Y,K,M,R,O]),Er(()=>{if(o||!Y)return;const e=Qr(Y),t=Co(e),n=null==R.current;function r(e){var t;if(e.open||(F.current=function(e,t){const n=jr(Io(e));return e instanceof n.KeyboardEvent?"keyboard":e instanceof n.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof n.MouseEvent?t||(0===e.detail?"keyboard":"mouse"):""}(e.nativeEvent,z.current)),"trigger-hover"===e.reason&&"mouseleave"===e.nativeEvent.type&&(D.current=!0),"outside-press"===e.reason)if(e.nested)D.current=!1;else if(""===(t=e.nativeEvent).pointerType&&t.isTrusted||(yo&&t.pointerType?"click"===t.type&&1===t.buttons:0===t.detail&&!t.pointerType)||function(e){return!So&&(!yo&&0===e.width&&0===e.height||yo&&1===e.width&&1===e.height&&0===e.pressure&&0===e.detail&&"mouse"===e.pointerType||e.width<1&&e.height<1&&0===e.pressure&&0===e.detail&&"touch"===e.pointerType)}(e.nativeEvent))D.current=!1;else{let e=!1;Qr(Y).createElement("div").focus({get preventScroll(){return e=!0,!1}}),D.current=!e}}return zs(t),S.on("openchange",r),()=>{S.off("openchange",r);const o=Co(e),i=X(),s=Eo(x,o)||i.some(e=>e===o||Eo(e,o))||A&&_o(A.nodesRef.current,C(),!1).some(e=>Eo(e.context?.elements.floating,o)),a=T.current,c=F.current,l=function(e){const r=T.current;let o="function"==typeof r?r(e):r;if(void 0===o||!1===o)return null;null===o&&(o=!0);const i=w?.isConnected?w:null,s=t?.isConnected&&"body"!==Hr(t)?t:null;let a=n?s||i:i||s;return a||(a=$s()||null),"boolean"==typeof o?a:zi(o)||a||null}(c);queueMicrotask(()=>{const t=(n=l)?Xo(n)?n:Jo(n)[0]||n:null;var n;const r="boolean"!=typeof a;if(a&&!D.current&&Yr(t)&&(r||t===o||o===e.body||s)){const e={preventScroll:!0};"keyboard"===c&&(e.focusVisible=!0),t.focus(e)}D.current=!1})}},[o,x,Y,T,R,S,A,w,C,X]),Er(()=>{if(!wo||v||!x)return;const e=Co(Qr(x));Yr(e)&&To(e)&&Eo(x,e)&&e.blur()},[v,x]),Er(()=>{if(!o&&_)return _.setFocusManagerState({modal:c,closeOnFocusOut:l,open:v,onOpenChange:g.setOpen,domReference:w}),()=>{_.setFocusManagerState(null)}},[o,_,c,v,g,l,w]),Er(()=>{if(!o&&Y)return Bs(Y),()=>{queueMicrotask(Fs)}},[o,Y]);const G=!o&&(!c||!I)&&(V||c);/*#__PURE__*/
7
+ return b(e.Fragment,{children:[G&&/*#__PURE__*/y(di,{"data-type":"inside",ref:W,onFocus:e=>{if(c){const e=K();xs(e[e.length-1])}else _?.portalNode&&(D.current=!1,ti(e,_.portalNode)?Qo(w)?.focus():zi(p??_.beforeOutsideRef)?.focus())}}),r,G&&/*#__PURE__*/y(di,{"data-type":"inside",ref:U,onFocus:e=>{c?xs(K()[0]):_?.portalNode&&(l&&(D.current=!0),ti(e,_.portalNode)?ei(w)?.focus():zi(u??_.afterOutsideRef)?.focus())}})]})}function Us(){return!1}var Hs={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId},js=class extends Wr{constructor(e){const{syncOnly:t,nested:n,onOpenChange:r,triggerElements:o,...i}=e;super({...i,positionReference:i.referenceElement,domReferenceElement:i.referenceElement},{onOpenChange:r,dataRef:{current:{}},events:_s(),nested:n,triggerElements:o},Hs),this.syncOnly=t}syncOpenEvent=(e,t)=>{(!e||!this.state.open||null!=t&&function(e){const t=e.type;return"click"===t||"mousedown"===t||"keydown"===t||"keyup"===t}(t))&&(this.context.dataRef.current.openEvent=e?t:void 0)};dispatchOpenChange=(e,t)=>{this.syncOpenEvent(e,t.event);const n={open:e,reason:t.reason,nativeEvent:t.event,nested:this.context.nested,triggerElement:t.trigger};this.context.events.emit("openchange",n)};setOpen=(e,t)=>{this.syncOnly||this.dispatchOpenChange(e,t),this.context.onOpenChange?.(e,t)}};function qs(t,n=!1,r=!1){const[o,i]=e.useState(t&&n?"idle":void 0),[s,a]=e.useState(t);return t&&!s&&(a(!0),i("starting")),t||!s||"ending"===o||r||i("ending"),t||s||"ending"!==o||i(void 0),Er(()=>{if(!t&&s&&"ending"!==o&&r){const e=ro.request(()=>{i("ending")});return()=>{ro.cancel(e)}}},[t,s,o,r]),Er(()=>{if(!t||n)return;const e=ro.request(()=>{i(void 0)});return()=>{ro.cancel(e)}},[n,t]),Er(()=>{if(!t||!n)return;t&&s&&"idle"!==o&&i("starting");const e=ro.request(()=>{i("idle")});return()=>{ro.cancel(e)}},[n,t,s,o]),{mounted:s,setMounted:a,transitionStatus:o}}var Vs={tabIndex:-1,[ko]:""};function Ys({handle:e,store:t}){return Er(()=>e.attachStore(t),[e,t]),null}var Ks=class{constructor(){this.idMap=/* @__PURE__ */new Map}add(e,t){this.idMap.set(e,t)}delete(e){this.idMap.delete(e)}hasElement(e){for(const t of this.idMap.values())if(t===e)return!0;return!1}hasMatchingElement(e){for(const t of this.idMap.values())if(e(t))return!0;return!1}getById(e){return this.idMap.get(e)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}},Xs=e=>e.triggerIdProp??e.activeTriggerId,Gs=e=>e.openProp??e.open,Js=e=>(e.popupElement?.id??e.floatingId)||void 0;function Zs(e,t){return void 0!==t&&Gs(e)&&Xs(e)===t}var Qs,ea={open:Gs,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:Xs,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:Js,isTriggerActive:(e,t)=>void 0!==t&&Xs(e)===t,isOpenedByTrigger:(e,t)=>Zs(e,t),isMountedByTrigger:(e,t)=>void 0!==t&&Xs(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>function(e,t){return!!Zs(e,t)||void 0!==t&&Gs(e)&&null==Xs(e)&&1===e.triggerCount}(e,t)?Js(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement},ta=/*#__PURE__*/e.createContext(void 0);(Qs={}).open="data-open",Qs.closed="data-closed",Qs[Qs.startingStyle=Pi.startingStyle]="startingStyle",Qs[Qs.endingStyle=Pi.endingStyle]="endingStyle",Qs.anchorHidden="data-anchor-hidden",Qs.side="data-side",Qs.align="data-align";var na={"data-open":""},ra={"data-closed":""},oa={"data-anchor-hidden":""},ia={open:e=>e?na:ra,anchorHidden:e=>e?oa:null},sa={...ia,...Fi};function aa(){const t=Tr(),n=t.useState("toasts");return e.useMemo(()=>({toasts:n,add:t.addToast,close:t.closeToast,update:t.updateToast,promise:t.promiseToast}),[n,t])}var ca="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%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",la={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)"},da={none:"0",sm:"calc(var(--radius) - 4px)",md:"calc(var(--radius) - 2px)",lg:"var(--radius)",xl:"calc(var(--radius) + 4px)",theme:"var(--radius)",pill:"9999px",circle:"9999px"},ua={default:"var(--foreground)",muted:"var(--foreground-muted)",faint:"var(--foreground-faint)",primary:"var(--primary)",inherit:"inherit"},pa={tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625"},ha={info:{background:"#f0f9ff",border:"1px solid #bae6fd",titleColor:"#0c4a6e",bodyColor:"#0369a1",closeColor:"#7dd3fc",actionBackground:"#e0f2fe"},error:{background:"#fef2f2",border:"1px solid #fecaca",titleColor:"#b91c1c",bodyColor:"#b91c1c",closeColor:"#f87171",actionBackground:"#fee2e2"},neutral:{background:"rgba(255, 255, 255, 0.95)",border:"1px solid rgba(255, 255, 255, 0.2)",titleColor:"#1f2937",bodyColor:"#1f2937",closeColor:"#6b7280",actionBackground:"transparent"}};function fa(e){if(e&&"none"!==e)return{boxShadow:la[e]}}var ma=2147483003,ga={none:"0","2xs":"2px",xs:"4px",sm:"6px",md:"8px",lg:"12px",xl:"16px","2xl":"24px"},ya={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch",baseline:"baseline"},ba={start:"flex-start",center:"center",end:"flex-end",between:"space-between",around:"space-around"},va={spin:"mtx-spin 1s linear infinite",ping:"mtx-ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"mtx-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",fadeIn:"mtx-fade-in 0.5s ease-out"},wa={top:"borderTopWidth",bottom:"borderBottomWidth",left:"borderLeftWidth",right:"borderRightWidth"},xa=/* @__PURE__ */new Set(["padding","paddingX","paddingY","paddingTop","paddingBottom","gap","align","justify","grow","shrink","position","inset","overflow","overflowY","width","height","minWidth","border","rounded","animate","hidden","as","style"]);function Sa(e){const t={};return void 0!==e.padding&&(t.padding=ga[e.padding]),void 0!==e.paddingX&&(t.paddingLeft=ga[e.paddingX],t.paddingRight=ga[e.paddingX]),void 0!==e.paddingY&&(t.paddingTop=ga[e.paddingY],t.paddingBottom=ga[e.paddingY]),void 0!==e.paddingTop&&(t.paddingTop=ga[e.paddingTop]),void 0!==e.paddingBottom&&(t.paddingBottom=ga[e.paddingBottom]),void 0!==e.gap&&(t.gap=ga[e.gap]),void 0!==e.align&&(t.alignItems=ya[e.align]),void 0!==e.justify&&(t.justifyContent=ba[e.justify]),!0===e.grow&&(t.flex="1 1 0%"),!1===e.shrink&&(t.flexShrink=0),void 0!==e.position&&(t.position=e.position),void 0!==e.inset&&(t.inset="0"===e.inset?"0":ga[e.inset]),void 0!==e.overflow&&(t.overflow=e.overflow),void 0!==e.overflowY&&(t.overflowY=e.overflowY),void 0!==e.width&&(t.width="full"===e.width?"100%":"auto"),void 0!==e.height&&(t.height="full"===e.height?"100%":"auto"),"0"===e.minWidth&&(t.minWidth=0),void 0!==e.border&&!1!==e.border&&(t.borderColor="var(--border)",t.borderStyle="solid",!0===e.border?t.borderWidth="1px":t[wa[e.border]]="1px"),void 0!==e.rounded&&!1!==e.rounded&&(!0===e.rounded?t.borderRadius=da.theme:"full"===e.rounded?t.borderRadius=da.pill:t.borderRadius=da[e.rounded]),void 0!==e.animate&&"none"!==e.animate&&(t.animation=va[e.animate]),!0===e.hidden&&(t.display="none"),t}var ka={sm:20,md:32,lg:48};function Ca(e){const{src:t,alt:n,elevation:r,fit:o="contain",size:i="md",rounded:s,className:a,style:c,ref:l,...d}=e,u="string"==typeof i?ka[i]:i;/* @__PURE__ */
8
+ return y("img",{...d,ref:l,alt:n,className:a?`mtx-avatar ${a}`:"mtx-avatar",src:t,style:{objectFit:o,width:u,height:u,...Sa({rounded:s}),...fa(r),...c}})}var Ea=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,disabled:o=!1,focusableWhenDisabled:i=!1,nativeButton:s=!0,style:a,...c}=e,{getButtonProps:l,buttonRef:d}=ns({disabled:o,focusableWhenDisabled:i,native:s});return Ti("button",e,{state:{disabled:o},ref:[t,d],props:[c,l]})}),Ia={default:da.lg,theme:da.theme,pill:da.pill};function Ma({active:e=!1,className:t,disabled:n,elevation:r,full:o,shape:i="default",size:s="md",stacked:a=!1,type:c="button",variant:l="primary",style:d,ref:u,...p}){/* @__PURE__ */
9
+ return y(Ea,{...p,ref:u,className:t?`mtx-button ${t}`:"mtx-button","data-active":e?"true":"false","data-disabled":n?"true":"false","data-full":o?"true":"false","data-size":s,"data-stacked":a?"true":"false","data-variant":l,disabled:n,style:{borderRadius:Ia[i],...fa(r),...d},type:c})}var Ta={default:{},card:{backgroundColor:"var(--card)",color:"var(--card-foreground)"}},Ra={none:{},card:{padding:"8px 12px"},toast:{padding:"8px 12px 8px 8px"}},Oa=o(function(e,t){const{as:n="div",background:r="default",className:o,elevation:i,paddingPreset:s="none",style:a,...c}=e,l=function(e){const t={};for(const n in e)xa.has(n)||(t[n]=e[n]);return t}(c);/* @__PURE__ */
10
+ return y(n,{...l,ref:t,className:o,style:{...Ta[r],...Ra[s],...fa(i),...Sa(e),...a}})}),Aa=o(function(e,t){const{direction:n,hidden:r,style:o,...i}=e;/* @__PURE__ */
11
+ return y(Oa,{...i,ref:t,hidden:r,style:{display:!0===r?"none":"flex",..."column"===n&&{flexDirection:"column"},...o}})}),_a=(e,t=2)=>({d:e,stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round"}),Da={checkCircle:{viewBox:"0 0 512 512",paths:[{d:"M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z"}]},circle:{viewBox:"0 0 512 512",paths:[{d:"M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"}]},exclamationCircle:{viewBox:"0 0 512 512",paths:[{d:"M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"}]},arrowUp:{viewBox:"0 0 448 512",paths:[{d:"M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"}]},arrowDown:{viewBox:"0 0 448 512",paths:[{d:"M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"}]},chatBubble:{viewBox:"0 0 512 512",paths:[{d:"M87.48 380c1.2-4.38-1.43-10.47-3.94-14.86a42.63 42.63 0 0 0-2.54-3.8 199.81 199.81 0 0 1-33-110C47.64 139.09 140.72 48 255.82 48 356.2 48 440 117.54 459.57 209.85a199 199 0 0 1 4.43 41.64c0 112.41-89.49 204.93-204.59 204.93-18.31 0-43-4.6-56.47-8.37s-26.92-8.77-30.39-10.11a31.14 31.14 0 0 0-11.13-2.07 30.7 30.7 0 0 0-12.08 2.43L81.5 462.78a15.92 15.92 0 0 1-4.66 1.22 9.61 9.61 0 0 1-9.58-9.74 15.85 15.85 0 0 1 .6-3.29z",fill:"none",stroke:"currentColor",strokeWidth:32,strokeLinecap:"round"},{d:"M160 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"},{d:"M256 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"},{d:"M352 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"}]},stop:{viewBox:"0 0 512 512",paths:[{d:"M392 432H120a40 40 0 0 1-40-40V120a40 40 0 0 1 40-40h272a40 40 0 0 1 40 40v272a40 40 0 0 1-40 40z"}]},mousePointerClick:{viewBox:"0 0 24 24",paths:[_a("M14 4.1 12 6"),_a("m5.1 8-2.9-.8"),_a("m6 12-1.9 2"),_a("M7.2 2.2 8 5.1"),_a("M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z")]},ticktick:{viewBox:"0 0 24 24",paths:[{d:"M12 0C5.383 0 0 5.383 0 12s5.383 12 12 12 12-5.383 12-12h-2.7c0 5.128-4.172 9.3-9.3 9.3-5.128 0-9.3-4.172-9.3-9.3 0-5.128 4.172-9.3 9.3-9.3V0Zm7.4 2.583-7.505 9.371L8.388 9.08l-2.002 2.436 4.741 3.888a1.573 1.573 0 0 0 2.231-.233l8.504-10.617L19.4 2.583Z"}]},home:{viewBox:"0 0 24 24",paths:[_a("M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6")]},chat:{viewBox:"0 0 24 24",paths:[_a("M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z")]},send:{viewBox:"0 0 24 24",paths:[_a("M5 12h14m-7-7l7 7-7 7")]},closeSmall:{viewBox:"0 0 12 12",paths:[_a("M9 3L3 9M3 3l6 6",1.5)]},close:{viewBox:"0 0 20 20",paths:[{d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",fillRule:"evenodd",clipRule:"evenodd"}]},chevronDown:{viewBox:"0 0 24 24",paths:[_a("M19 9l-7 7-7-7",2.5)]},screenShare:{viewBox:"0 0 24 24",paths:[_a("M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z")]},alertCircle:{viewBox:"0 0 24 24",paths:[_a("M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z")]}};function Pa({name:e,size:t=16,className:n,ref:r,...o}){const i=Da[e];return i?/* @__PURE__ */y("svg",{...o,ref:r,"aria-hidden":"true",className:n?`mtx-icon ${n}`:"mtx-icon",fill:"none",height:t,viewBox:i.viewBox,width:t,xmlns:"http://www.w3.org/2000/svg",children:i.paths.map((e,t)=>/* @__PURE__ */y("path",{clipRule:e.clipRule,d:e.d,fill:e.fill??(e.stroke?"none":"currentColor"),fillRule:e.fillRule,stroke:e.stroke,strokeLinecap:e.strokeLinecap,strokeLinejoin:e.strokeLinejoin,strokeMiterlimit:e.strokeMiterlimit,strokeWidth:e.strokeWidth},t))}):null}function La({variant:e="ghost",size:t="sm",tone:n,label:r,disabled:o,children:i,style:s,ref:a,...c}){/* @__PURE__ */
12
+ return y("button",{...c,ref:a,type:"button",disabled:o,"aria-label":r,className:"mtx-icon-button","data-disabled":o?"true":"false","data-size":t,"data-variant":e,style:n?{color:ua[n],...s}:s,children:i})}var Na=o(function(e,t){/* @__PURE__ */
13
+ return y(Aa,{...e,ref:t,direction:"column"})}),Fa={xxs:"10px",xs:"0.75rem",sm:"0.875rem",lg:"1.125rem"},za={normal:400,medium:500,semibold:600},$a={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function Ba({as:e="span",block:t=!1,inheritColor:n=!1,italic:r=!1,leading:o,variant:i="default",size:s,weight:a,truncate:c,align:l,className:d,ref:u,style:p,...h}){/* @__PURE__ */
14
+ return y(e,{...h,ref:u,className:d,style:{color:ua[n?"inherit":i],...s&&{fontSize:Fa[s]},...a&&{fontWeight:za[a]},...l&&{textAlign:l},...o&&{lineHeight:pa[o]},...t&&{display:"block"},...r&&{fontStyle:"italic"},...c&&$a,...p}})}var Wa=()=>{const{toasts:e}=aa();return e.map(e=>{const t=ha[n=e.type,"error"===n||"info"===n?n:"neutral"];var n;/* @__PURE__ */
15
+ return b(Hi,{toast:e,className:"mtx-toast",render:/* @__PURE__ */y(Aa,{align:"center",gap:"md",rounded:"pill",paddingPreset:"toast",elevation:"panel",style:{backgroundColor:t.background,border:t.border}}),children:[
16
+ /* @__PURE__ */y(Ca,{src:ca,alt:"",size:28,rounded:"full"}),
17
+ /* @__PURE__ */b(Na,{grow:!0,minWidth:"0",children:[/* @__PURE__ */y(Zi,{render:/* @__PURE__ */y(Ba,{as:"span",block:!0,inheritColor:!0,weight:"medium",style:{fontSize:"13px",color:t.titleColor,whiteSpace:e.actionProps?"normal":"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})}),null!=e.description&&/* @__PURE__ */y(Ji,{render:/* @__PURE__ */y(Ba,{as:"span",block:!0,inheritColor:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})})]}),e.actionProps&&/* @__PURE__ */y(is,{render:/* @__PURE__ */y(Ma,{type:"button",variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
18
+ /* @__PURE__ */y(os,{render:/* @__PURE__ */y(La,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */y(Pa,{name:"closeSmall",size:12})})]},e.id)})},Ua=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */b(ai,{children:[e,/* @__PURE__ */y(ys,{container:t??void 0,children:/* @__PURE__ */y(Oi,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */y(Wa,{})})})]}),Ha=aa,ja=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Ha();return a(()=>{if(null!=e)return s({id:"error",type:"error",title:e,timeout:0,priority:"high",onClose:t,...n&&{actionProps:{children:"Retry",onClick:n}}}),()=>c("error")},[e,n,s,c,t]),a(()=>{if(r)return s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}),()=>c("greeting")},[r,o,s,c,i]),null};function qa(e){const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}}function Va({videoStream:e,...t}){const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screenshare ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}}var Ya=new class{restore(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=De.getContext();return{...o,messages:r.map(qa)}}persist(e){De.updateContext({...e,messages:e.messages.map(Va)})}};function Ka(e,t,n,r={}){return{id:`${e}-${Date.now()}`,content:n,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Xa=(e,t,n="user-message")=>Ka(n,"user",e.trim(),{mode:t}),Ga=e=>Ka("agent-message","agent",e.trim()),Ja=(e,t,n,r)=>Ka(r,n,e,{mode:t,isSystemMessage:!0}),Za={show:"Show",tell:"Tell",do:"Do"},Qa=e=>Za[e];function ec(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function tc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest,o=e=>e.isPlaceholder&&void 0===e.mode||e.mode===n,i=[];!t||"show"!==n&&"do"!==n||i.push(e=>r(e)&&o(e)&&!!e.isPlaceholder,e=>r(e)&&o(e)),i.push(e=>r(e)&&!!e.isPlaceholder,r);for(const s of i){const t=ec(e,s);if(t>=0)return{index:t,message:e[t]}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var nc=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys"]),rc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function oc(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var ic=(e,t)=>e.parts.findIndex(e=>(e=>"progress"===e.type&&"in_progress"===e.status)(e)&&e.browserToolName===t),sc=/* @__PURE__ */new Map([["navigate","Navigating"],["search","Searching"],["click_element","Clicking element"],["type_text","Typing text"],["scroll","Scrolling"],["scroll_to_text","Scrolling to text"],["send_keys","Pressing key"],["extract","Extracting content"],["get_dropdown_options","Reading dropdown options"],["select_dropdown_option","Selecting option"],["go_back","Going back"],["wait","Waiting"],["close_tab","Closing tab"],["done","Done"],["get_html","Reading the page"],["get_screenshot","Taking screenshot"]]),ac=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*cc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function lc(e){if(!(e instanceof Element))return!1;try{if(!function(e){const t=e.tagName.toLowerCase();return"button"===t||"input"===t||"textarea"===t||"select"===t||"a"===t&&e.hasAttribute("href")||ac.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0}(e))return!1;if(!0===e.disabled)return!1;if("true"===e.getAttribute("aria-disabled"))return!1;for(const r of cc(e))if(r instanceof HTMLElement&&r.inert)return!1;const t=window.getComputedStyle(e);if("none"===t.display||"none"===t.pointerEvents)return!1;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;for(const r of cc(e))if(r!==e){const e=window.getComputedStyle(r).overflow;if("hidden"===e||"clip"===e){const e=r.getBoundingClientRect();if(n.right<e.left||n.left>e.right||n.bottom<e.top||n.top>e.bottom)return!1}if(r===document.body)break}for(let r=e.getRootNode();r instanceof ShadowRoot;r=r.host.getRootNode()){const e=r.host.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1}return!0}catch(t){return console.error("[isInteractable] Unexpected error:",t),!1}}var dc=["id","type","role","aria-label","name","href"],uc=new class{index=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;generateAnchoredSelector(e){const t=[];let n=e;for(;n!==document.body;){const e=n.id?`#${CSS.escape(n.id)}`:"";if(e&&1===document.querySelectorAll(e).length)return t.unshift(e),t.join(" > ");const r=n.parentElement;if(!r)break;const o=n.tagName,i=Array.from(r.children).filter(e=>e.tagName===o),s=i.length>1?`:nth-of-type(${i.indexOf(n)+1})`:"";t.unshift(o.toLowerCase()+s),n=r}return["body",...t].join(" > ")}staleReason(e){return document.contains(e.element)?dc.some((t,n)=>e.element.getAttribute(t)!==e.identity[n])?"has changed":null:"no longer exists"}indexInteractableElements(){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;for(;t;){const r=t instanceof HTMLElement?t:null;if(r){const e=r.matches('a[href], button, input, textarea, select, [role="button"]'),t=r.classList.contains("cursor-pointer")||r.classList.contains("clickable"),o="function"==typeof r.onclick;(e||t||o||lc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:dc.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,{selector:r}]of this.index.entries())try{e.querySelector(r)?.setAttribute("data-id",n.toString())}catch(t){console.warn(`[DomService] Failed to tag index ${n}:`,t)}return e.outerHTML}getSequenceForElement(e){return this.elementToSequence.get(e)}clearIndex(){this.index.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap}checkElementInteractable(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`;const o=r.left+r.width/2,i=r.top+r.height/2,s=document.elementFromPoint(o,i);if(s&&s!==e&&!e.contains(s)&&!s.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=s.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${s.className?`${e}.${s.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}getValidatedElement(e){const t=this.index.get(e);if(!t)return{element:null,error:`Element ${e} not found`};const n=this.staleReason(t);if(n)return{element:null,error:`DOM_CHANGED: Element at index ${e} ${n}. Call get_html to get updated indices.`};const r=this.checkElementInteractable(t.element,e);return r?{element:null,error:r}:{element:t.element}}},pc=null;function hc(){return pc?.active&&"live"===pc.getVideoTracks()[0]?.readyState?pc:(pc=null,null)}async function fc(){if(!1===De.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=hc();if(e)return e;const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!t||0===t.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return pc=t,t.getVideoTracks()[0].addEventListener("ended",()=>{pc=null}),t}var mc=["scroll","resize","touchmove","wheel"],gc=new class{currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;visibilityCheckInterval=null;async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:o}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===o&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),this.createHighlight(t),this.createPopup(n,r),this.setupPositionUpdates(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})),this.currentPromise}cleanup(){if(this.takeSettlers().reject?.(/* @__PURE__ */new Error("Cancelled by cleanup")),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler){for(const e of mc)window.removeEventListener(e,this.scrollHandler,{capture:!0});this.scrollHandler=null}this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.currentPopup?.remove(),this.currentHighlight?.remove(),document.getElementById("marketrix-show-popup")?.remove(),document.getElementById("marketrix-show-highlight")?.remove(),this.currentPopup=null,this.currentHighlight=null,this.currentElement=null,this.currentOptions=null,this.currentPromise=null}completeAction(){this.takeSettlers().resolve?.(),this.cleanup()}takeSettlers(){const e={resolve:this.resolvePromise,reject:this.rejectPromise};return this.resolvePromise=null,this.rejectPromise=null,e}createHighlight(e){const t=e.getBoundingClientRect(),n=document.createElement("div");n.id="marketrix-show-highlight",n.style.cssText=`position:fixed;top:${t.top}px;left:${t.left}px;width:${t.width}px;height:${t.height}px;border:3px solid #3b82f6;border-radius:4px;box-shadow:0 0 0 4px rgba(59,130,246,0.2),0 0 20px rgba(59,130,246,0.4);z-index:2147483645;pointer-events:none;transition:none;`,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><div style="display:flex;gap:8px;justify-content:flex-end;"><button id="marketrix-show-continue" style="background:#3b82f6;color:white;border:none;border-radius:6px;padding:8px 16px;font-size:12px;font-weight:500;cursor:pointer;">Continue</button></div>`,n.style.cssText="position: fixed; width: 320px; background: white; border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 2147483646; padding: 16px;",document.body.appendChild(n),this.currentPopup=n,t||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.scrollHandler=()=>{if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();Object.assign(this.currentHighlight.style,{top:`${e.top}px`,left:`${e.left}px`,width:`${e.width}px`,height:`${e.height}px`}),this.updatePopupPosition()};for(const e of mc)window.addEventListener(e,this.scrollHandler,{capture:!0,passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=10,n=e.left+e.width/2,r=e.top+e.height/2,o=[{left:e.right+20,top:r-60},{left:e.left-320-20,top:r-60},{left:n-160,top:e.top-120-20},{left:n-160,top:e.bottom+20}];let i=o[0];for(const s of o)if(s.left>=t&&s.left+320<=window.innerWidth-t&&s.top>=t&&s.top+120<=window.innerHeight-t){i=s;break}this.currentPopup.style.left=`${Math.max(t,Math.min(i.left,window.innerWidth-320-t))}px`,this.currentPopup.style.top=`${Math.max(t,Math.min(i.top,window.innerHeight-120-t))}px`}setupClickHandler(){this.clickHandler=e=>{this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)&&(e.preventDefault(),e.stopPropagation(),this.completeAction())},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{e.querySelector("#marketrix-show-continue")?.addEventListener("click",e=>{e.stopPropagation(),this.completeAction()})})}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{const e=this.currentElement;if(!e)return;const t=e.getBoundingClientRect();if(t.bottom<0||t.top>window.innerHeight||t.right<0||t.left>window.innerWidth)return void this.failShowAction("ELEMENT_OFF_SCREEN: The highlighted element scrolled out of view");const n=uc.getSequenceForElement(e)??-1,r=uc.checkElementInteractable(e,n);r&&this.failShowAction(r)},200)}failShowAction(e){this.takeSettlers().reject?.(new Error(e)),this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}},yc=e=>({success:!0,data:{text:e}}),bc=e=>({success:!0,data:e}),vc=e=>({success:!1,data:{text:""},error:e}),wc=e=>({success:!1,data:{options:[]},error:e}),xc=new class{async executeTool(e,t,n="do",r=""){const o=t;try{if("show"===n&&nc.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=uc.getValidatedElement(t);if(!n)return vc(o||`Element ${t} not found`);await gc.showToolAction({element:n,explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e})}}switch(e){case"navigate":return this.navigate(o);case"search":return this.search(o);case"click_element":return await this.clickElement(o);case"type_text":return this.typeText(o);case"scroll":return this.scroll(o);case"scroll_to_text":return this.scrollToText(o);case"extract":return this.extract(o);case"go_back":return this.goBack();case"wait":return await this.wait(o);case"select_dropdown_option":return this.selectDropdownOption(o);case"get_dropdown_options":return this.getDropdownOptions(o);case"send_keys":return this.sendKeys(o);case"close_tab":return this.closeTab();case"done":return this.done(o);case"get_html":return this.getHtml();case"get_screenshot":return await this.getScreenshot();default:return vc(`Unknown tool: ${e}`)}}catch(i){return vc(i instanceof Error?i.message:String(i))}}navigate(e){if(!e.url)return vc("URL is required");if(e.new_tab)return window.open(e.url,"_blank")?yc(`Opened ${e.url} in new tab`):vc("The browser blocked opening a new tab");const t=e.url;return{...yc(`Navigating to ${t}`),afterResponseAttempt:()=>{window.location.href=t}}}search(e){if(!e.query)return vc("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}`),{...yc(`Searching for "${e.query}" on ${t}`),afterResponseAttempt:()=>{window.location.href=r}}}async clickElement(e){if(void 0===e.index)return vc("Index required");const{element:t,error:n}=uc.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),{...yc(`Clicked element ${e.index}`),afterResponseAttempt:()=>t.click()}):vc(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return vc("Index and text required");const t=!1!==e.clear,{element:n,error:r}=uc.getValidatedElement(e.index);if(!n)return vc(r||`Element ${e.index} not found`);if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)n.focus(),this.setNativeValue(n,t?e.text:n.value+e.text),n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}));else if(n.isContentEditable){n.focus();const r=window.getSelection();if(t?r?.selectAllChildren(n):r?.collapse(n,n.childNodes.length),!document.execCommand("insertText",!1,e.text))return vc(`Could not insert text into element ${e.index}`)}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(o){return vc(`Failed to set value on element: ${o instanceof Error?o.message:String(o)}`)}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(o){return vc(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return yc(`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 vc("Invalid direction")}return yc(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return vc("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"}),yc(`Scrolled to "${e.text}"`);return vc(`Text "${e.text}" not found`)}extract(e){const t=!1!==e.extract_links,n={title:document.title,url:window.location.href,text:document.body.innerText.slice(0,1e4),links:t?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]};return bc(n)}goBack(){return window.history.length<=1?vc("No history"):{...yc("Navigated back"),afterResponseAttempt:()=>window.history.back()}}async wait({seconds:e}){return void 0===e?vc("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),yc(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return vc("Index/Option required");const{element:t,error:n}=uc.getValidatedElement(e.index);if(!t)return vc(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return vc(`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})),yc(`Selected ${e.option}`)):vc(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return wc("Index required");const{element:n,error:r}=uc.getValidatedElement(t);if(!n)return wc(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return wc(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return bc({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return vc("Index/Keys required");const{element:t,error:n}=uc.getValidatedElement(e.index);if(!t)return vc(n||`Element ${e.index} not found`);t.focus(),t.dispatchEvent(new KeyboardEvent("keydown",{key:e.keys,bubbles:!0,cancelable:!0})),t.dispatchEvent(new KeyboardEvent("keyup",{key:e.keys,bubbles:!0,cancelable:!0}));const r=this.simulateKeyAction(t,e.keys);return yc(r||`Sent keys ${e.keys}`)}simulateKeyAction(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=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),o=r.indexOf(e),i=-1===o?void 0:r[o+n];return i?(i.focus(),`${t}: moved focus to ${i.tagName.toLowerCase()}${i.id?`#${i.id}`:""}`):`${t}: no ${n>0?"next":"previous"} focusable element`}case"Enter":if(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";const n=e.selectionStart??t.length,r=e.selectionEnd??t.length;let o,i;if(n===r&&n>0)o=t.slice(0,n-1)+t.slice(r),i=n-1;else{if(n===r)return"Backspace: cursor at start, nothing to delete";o=t.slice(0,n)+t.slice(r),i=n}return this.setValueAndCaret(e,o,i),`Backspace: deleted character, value is now "${o}"`}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 o;if(t===n&&t<r.length)o=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";o=r.slice(0,t)+r.slice(n)}return this.setValueAndCaret(e,o,t),`Delete: deleted character, value is now "${o}"`}return"Delete: dispatched event";default:return null}}setNativeValue(e,t){const n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;n?n.call(e,t):e.value=t}setValueAndCaret(e,t,n){this.setNativeValue(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}closeTab(){return window.close(),window.closed?yc("Tab closed"):vc("The browser refused to close a tab this script did not open")}done(e){return yc(e.message||"Task ended")}getHtml(){try{const e=uc.reindexAndSnapshot();return yc(e)}catch(e){return vc(String(e))}}async getScreenshot(){const e=document.createElement("video");try{e.srcObject=await fc(),e.autoplay=!0,e.style.display="none",document.body.appendChild(e),await function(e){return new Promise((t,n)=>{const r=setTimeout(()=>n(/* @__PURE__ */new Error("Screen capture produced no frame")),5e3);e.onloadeddata=()=>{clearTimeout(r),t()},e.onerror=()=>{clearTimeout(r),n(/* @__PURE__ */new Error("Screen capture failed"))}})}(e);const t=document.createElement("canvas");return t.width=e.videoWidth,t.height=e.videoHeight,t.getContext("2d")?.drawImage(e,0,0),yc(t.toDataURL("image/jpeg",.75))}catch(t){return vc(String(t))}finally{e.remove()}}},Sc=e=>({state:e,effects:[]});function kc(e,t,n,r,o,i,s){const a=tc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=ic(e,t);if(r<0)return e;const o=rc(e.parts[r].content),i=rc(n);return oc(e,r,{status:"failed",content:i?`${o} (${i})`:o})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=rc(n),o=ic(e,t);return o>=0?oc(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>sc.get(e)??e)(r)):((e,t)=>oc(e,ic(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&nc.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Cc=e=>({...e,isPlaceholder:!1});function Ec(e,t,n){const r=tc({messages:e.messages,isTaskRunning:e.task.isTaskRunning,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=Cc(n(r.message))),{messages:o,task:{isTaskRunning:!1}}}var Ic={completed:"done",failed:"failed",stopped:"stopped"};function Mc(e,t,n,r){const o=e.messages.map(e=>{if(e.id!==t)return e;const o=[...e.parts],i=o[o.length-1],s="text"===i?.type&&!0===i.streaming,a=r&&s?i.content+n:n,c={type:"text",content:a,...r&&{streaming:!0}};return s?o[o.length-1]=c:o.push(c),{...e,content:a,isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var Tc=(e,t)=>({...e,content:t,parts:[...e.parts,{type:"text",content:t}]}),Rc=(e,t)=>({...Cc(Tc(e,t)),placeholderState:void 0});function Oc(e,t,n){const r=e.messages.map(e=>e.id===t?Rc(e,n):e);return{...e,messages:r}}var Ac=n(void 0),_c=({children:e})=>{const[t,n]=p({isOpen:!1,activeView:"home",currentMode:"tell"}),r=d(()=>({setActiveView:e=>n(t=>({...t,activeView:e})),toggleWidget:()=>n(e=>({...e,isOpen:!e.isOpen})),closeWidget:()=>n(e=>({...e,isOpen:!1})),setMode:e=>n(t=>({...t,currentMode:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]);/* @__PURE__ */
19
+ return y(Ac.Provider,{value:{uiState:t,uiActions:r},children:e})},Dc=()=>{const e=s(Ac);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},Pc=n(void 0),Lc=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=Dc(),[o,s]=p(()=>({messages:[],task:{isTaskRunning:!1}})),c=u(o),l=u(n.currentMode);l.current=n.currentMode;const h=u(/* @__PURE__ */new Set),f=i(e=>{const t=c.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(c.current=n,s(n))},[]),m=i(e=>{f(t=>({...t,messages:[...t.messages,e]}))},[f]),g=i((e,t)=>{f(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[f]),b=i(e=>{f(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[f]),v=i(e=>{f(t=>({...t,messages:e}))},[f]),w=i(()=>{f(e=>({...e,messages:[]}))},[f]),x=i(e=>{f(t=>({...t,task:{isTaskRunning:e}}))},[f]),S=o.messages.filter(e=>e.isPlaceholder).map(e=>e.id).join(" ");a(()=>{const e=S.split(" ").filter(Boolean).map(e=>setTimeout(()=>f(t=>function(e,t){return e.task.isTaskRunning?e:e.messages.find(e=>e.id===t)?.isPlaceholder?Oc(e,t,"This is taking longer than expected. Please try again."):e}(t,e)),12e4));return()=>e.forEach(clearTimeout)},[S,f]);const k=i(async(e,n,r)=>{const o=n??l.current;if(t)return r||m(Xa(e,o)),void m(Ga("This is a preview. In production, I'll respond to your messages here."));const i=De.getCredentialedConfig();if(!i)return console.error("Config not loaded or incomplete"),void m(Ga("Configuration error: Missing API credentials. Please check your widget settings."));r||m(Xa(e,o));const s=`temp-${globalThis.crypto.randomUUID()}`;m({id:s,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:o,isPlaceholder:!0,placeholderState:"thinking",parts:[]});try{await async function(e,t,n,r){const o=await Pe.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:De.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString(),marketrix_id:e.mtxId,marketrix_key:e.mtxKey};e.userId&&(r.user_id=e.userId),Me.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>console.warn("[API Service] Failed to log widget question:",e))}(e,t,n);const i={type:`chat/${n}`,request_id:r,content:t},s=sr.getInstance();await s.ready(o),await s.send(i)}(i,e,o,s)}catch(a){console.error("Failed to send message:",a),f(e=>Oc(e,s,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=sr.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await xc.executeTool(r,o,i,s),c=a.success?void 0:a.error??"Tool execution failed";f(e=>function(e,t,n,r,o,i){return{...e,messages:kc(e.messages,e.task.isTaskRunning,o,t,n,r,i)}}(e,r,s,c?"failed":"completed",l.current,c)),c||"done"!==r||f(e=>function(e,t){return Ec(e,t,e=>({...e,taskStatus:"done"}))}(e,l.current)),await e.send({type:"tool/response",tool_call_id:n,success:a.success,data:JSON.stringify(a.data),error:c}).catch(e=>console.error("Failed to send tool response:",e)),a.afterResponseAttempt?.()},o={onMessage:e=>{if("tool/call"===e.type){const t=e.tool_call_id;if(h.current.has(t))return;h.current.add(t),h.current.size>1e3&&(h.current=new Set([...h.current].slice(-500)))}else"task/status"===e.type&&e.status in Ic&&h.current.clear();let t=[];f(n=>{const r=function(e,t,n){switch(t.type){case"tool/call":{const r=e.task.isTaskRunning?e.task:{isTaskRunning:!0},o=t.explanation||"";return{state:{messages:kc(e.messages,r.isTaskRunning,n,t.browser_tool,o,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:t.mode||n,explanation:o}]}}case"task/status":{if("running"===t.status)return Sc(e);const r=t.status,o=e=>t.message?Tc(e,t.message):e;return{state:Ec(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:Ic[r]})),effects:[]}}case"chat/delta":return{state:Mc(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:Mc(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:Oc(e,t.request_id,`Error: ${t.error}`),effects:[]};default:return Sc(e)}}(n,e,l.current);return t=r.effects,r.state});for(const r of t)n(r).catch(e=>console.error("[Widget] Tool call failed:",e))},onError:e=>{r.setError(e.message),e instanceof ir&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?Rc(e,t):e),task:{isTaskRunning:!1}}}(t,e.message))}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[t,f,r]);const C=i(async()=>{f(e=>function(e,t){return Ec(e,t,e=>({...e,taskStatus:"stopped"}))}(e,l.current)),t||sr.getInstance().send({type:"chat/stop"}).catch(e=>{console.error("Failed to stop task remotely:",e),r.setError("Could not stop the assistant — it may still be working.")})},[t,f,r]),E=d(()=>({addMessage:m,updateMessage:g,removeMessage:b,setMessages:v,clearMessages:w,messageDispatch:k}),[m,g,b,v,w,k]),I=d(()=>({setTaskState:x,stopTask:C}),[x,C]);/* @__PURE__ */
20
+ return y(Pc.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:I},children:e})},Nc=()=>{const e=s(Pc);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},Fc=n(null),zc=()=>{const{uiState:e}=Dc(),{messages:t}=Nc();return a(()=>{const{currentMode:n,isOpen:r}=e;Ya.persist({messages:t,currentMode:n,isOpen:r})},[t,e]),null},$c=({children:e,previewMode:t})=>{const{uiActions:n}=Dc(),{chatActions:r}=Nc(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const t=await Pe.getOrCreateChatId();if(e)return;const{messages:o,...s}=Ya.restore();n.applyState(s),r.setMessages(o),i(!0),sr.getInstance().connect(t).catch(e=>console.error("Initial stream connection failed:",e))})().catch(t=>{e||(console.error("Widget initialization failed:",t),n.setError("Widget failed to initialise — please refresh the page."))}),()=>{e=!0}},[]),/* @__PURE__ */b(g,{children:[e,o&&/* @__PURE__ */y(zc,{})]})},Bc=({children:e,previewMode:t=!1})=>/* @__PURE__ */y(_c,{children:/* @__PURE__ */y(Lc,{previewMode:t,children:/* @__PURE__ */y($c,{previewMode:t,children:e})})});function Wc(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 Uc(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=Wc(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}var Hc={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"};function jc(e={}){const t=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e));return function(e){return{color:{background:e.widget_background_color,foreground:e.widget_text_color,foregroundMuted:Uc(e.widget_text_color,.6),foregroundFaint:Uc(e.widget_text_color,.4),border:e.widget_border_color,primary:e.widget_accent_color,primaryForeground:(t=e.widget_accent_color,function(e){const t=Wc(e);if(!t)return.5;const[n,r,o]=[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*o}(t)>.5?"#000000":"#ffffff"),primaryHover:Uc(e.widget_accent_color,.85),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:Uc(e.widget_secondary_color,.2),secondaryHover:Uc(e.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}};var t}({...Hc,...t})}var qc=n(null),Vc=()=>{const e=s(qc);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},Yc=()=>{const{uiState:e,uiActions:t}=Dc(),{messages:n,chatActions:r,taskState:o,taskActions:s}=Nc(),a=d(()=>({...e,...o,messages:n,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),c=i(()=>{r.clearMessages(),s.setTaskState(!1),t.setError(void 0)},[r,s,t]);return{state:a,actions:d(()=>({...t,...s,...r,clearChatHistory:c}),[t,s,r,c])}},Kc={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},Xc=Object.keys(Kc),Gc=e=>Kc[e],Jc=e=>{const{vertical:t,horizontal:n}=Gc(e);return{[t]:"20px",[n]:"20px"}},Zc=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Gc(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},Qc=class extends t.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`${this.props.label} Error Boundary caught error:`,e,t)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},el="cubic-bezier(0.16, 1, 0.3, 1)",tl=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=Vc(),{state:c,actions:d}=Yc(),h=c.isOpen,f=c.isTaskRunning,m=!!c.error,g=!h&&(c.isAwaitingReply||f),v=!h&&f,w=m?"marketrix-widget-button-error-glow":"marketrix-widget-button-processing-glow",x=m?"marketrix-widget-button-error-activity-ring":"marketrix-widget-button-processing-activity-ring",S=u(null),{isDragging:k,pixelPositionStyle:C,onPointerDown:E,onPointerMove:I,onPointerUp:M,onPointerCancel:T,suppressUntilRef:R}=function({position:e,onPositionCommit:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=p(!1),[c,d]=p({w:56,h:56}),[,h]=p(0),f=u(null),m=u(null),g=u(null),y=u(0),b=u([]),v=u(0),w=()=>{null!==g.current&&window.cancelAnimationFrame(g.current),g.current=null};t.useEffect(()=>w,[]),t.useEffect(()=>{if(r)return;const e=()=>h(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[r]);const x=i(()=>{if(!o.current||"undefined"==typeof window)return;const e=o.current.getBoundingClientRect();d(t=>t.w===e.width&&t.h===e.height?t:{w:e.width,h:e.height})},[o]);l(()=>{x();const e="undefined"!=typeof window&&o.current?new ResizeObserver(x):null;return e&&o.current&&e.observe(o.current),()=>e?.disconnect()},[x,e,o]);const S="undefined"!=typeof window?window.innerWidth:0,k="undefined"!=typeof window?window.innerHeight:0,C=Zc(e,S,k,c.w,c.h),E=!r&&S>0&&k>0?{left:C.x,top:C.y}:void 0,I=(e,t=.999)=>e/1e3*t/(1-t),M=()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="")},T=i((e,t)=>{if(f.current)return;let r=!1;const i=()=>{r||(r=!0,f.current=null,t.style.transition="none",t.style.willChange="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))};f.current=i;const s=window.setTimeout(i,650);t.addEventListener("transitionend",function e(n){n.target===t&&"left"===n.propertyName&&(window.clearTimeout(s),t.removeEventListener("transitionend",e),i())})},[n,o]),R=i((t,r,i)=>{if(!o.current||!E)return M(),n(t),void a(!1);w();const s=o.current,l=Zc(e,S,k,c.w,c.h),d=Zc(t,S,k,c.w,c.h);s.style.transition="none",s.style.transform="none",s.style.willChange="left, top",s.style.left=`${l.x+r}px`,s.style.top=`${l.y+i}px`,requestAnimationFrame(()=>{s.style.transition=`left 600ms ${el}, top 600ms ${el}`,s.style.left=`${d.x}px`,s.style.top=`${d.y}px`}),T(t,s)},[T,n,E,e,S,k,c.w,c.h,o]),O=e=>{M(),m.current=null,a(!1),e.currentTarget.releasePointerCapture(e.pointerId)};return{isDragging:s,pixelPositionStyle:E,onPointerDown:e=>{m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragging:!1,lastX:0,lastY:0},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{const t=m.current;if(t?.pointerId!==e.pointerId)return;const n=e.clientX-t.startX,r=e.clientY-t.startY;if(!t.dragging&&Math.hypot(n,r)>5&&(t.dragging=!0,a(!0),b.current=[],v.current=0,o.current&&(o.current.style.willChange="transform",o.current.style.transition="none")),!t.dragging)return;t.lastX=n,t.lastY=r;const i=Date.now();i-v.current>=10&&(v.current=i,b.current=[...b.current.slice(-5),{x:e.clientX,y:e.clientY,t:i}]),null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null;const e=m.current,t=o.current;t&&e&&(t.style.transform=`translate3d(${e.lastX}px, ${e.lastY}px, 0)`)}))},onPointerUp:t=>{const n=m.current;if(n?.pointerId===t.pointerId){if(n.dragging){const r=(()=>{const e=b.current;if(e.length<2)return{x:0,y:0};const t=e[e.length-1].t-e[0].t;return t<=0?{x:0,y:0}:{x:(e[e.length-1].x-e[0].x)/t*1e3,y:(e[e.length-1].y-e[0].y)/t*1e3}})(),i=I(r.x),s=I(r.y),a={dx:n.lastX+i,dy:n.lastY+s},c=o.current?.getBoundingClientRect(),l=c?((e,t,n,r,o,i)=>{const s=Zc(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,d=1/0;for(const u of Xc){const e=Zc(u,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<d&&(d=t,l=u)}return l})(a,e,window.innerWidth,window.innerHeight,c.width,c.height):e;return R(l,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}O(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&O(e)},suppressUntilRef:y}}({position:s,onPositionCommit:e,isPreviewMode:n,wrapperRef:S});/* @__PURE__ */
21
+ return y(Oa,{ref:S,className:"mtx-fab-anchor","data-animated":k?"false":"true","data-preview":n?"true":"false",style:{zIndex:a,pointerEvents:h?"none":"auto",...Jc(s),...C},children:/* @__PURE__ */b(Oa,{className:"mtx-fab","data-open":h?"true":"false",children:[g&&/* @__PURE__ */y(Oa,{className:w,"aria-hidden":!0}),v&&!k&&/* @__PURE__ */y(Ma,{type:"button",variant:"secondary",size:"sm",className:"mtx-fab-stop","data-side":s.includes("left")?"left":"right",onClick:e=>{e.preventDefault(),e.stopPropagation(),d.stopTask()},children:"Stop"}),
22
+ /* @__PURE__ */y(Ma,{type:"button",variant:"bare",onClick:()=>{Date.now()<R.current||d.toggleWidget()},onDragStart:e=>e.preventDefault(),onPointerDown:E,onPointerMove:I,onPointerUp:M,onPointerCancel:T,className:"mtx-fab-trigger",style:{touchAction:"none",cursor:k?"grabbing":"grab",userSelect:"none",WebkitUserSelect:"none"},"aria-label":h?"Close":"Open","aria-live":"polite",children:/* @__PURE__ */y(Aa,{className:"mtx-fab-center",children:/* @__PURE__ */b(Oa,{className:"mtx-fab-badge",style:{borderRadius:"12px",backgroundColor:h?o:r,boxShadow:la.fab},children:[g&&/* @__PURE__ */y("svg",{className:x,viewBox:"0 0 54 54",fill:"none","aria-hidden":!0,children:/* @__PURE__ */y("rect",{x:"1.25",y:"1.25",width:"51.5",height:"51.5",rx:13,ry:13})}),
23
+ /* @__PURE__ */y(Aa,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(30deg) scale(0)":"rotate(0deg) scale(1)",opacity:h?0:1,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":h,children:/* @__PURE__ */y(Ca,{src:ca,alt:"",className:"mtx-fab-avatar",draggable:!1,onDragStart:e=>e.preventDefault(),style:{borderRadius:"12px",border:"none",outline:"none",backgroundColor:"transparent",pointerEvents:"none",userSelect:"none"}})}),
24
+ /* @__PURE__ */y(Aa,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(0deg) scale(1)":"rotate(-30deg) scale(0)",opacity:h?1:0,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":!h,children:/* @__PURE__ */y(Pa,{name:"chevronDown",size:24,className:"mtx-fab-chevron"})})]})})})]})})},nl=/*#__PURE__*/e.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function rl(t){const{children:n,elementsRef:r,labelsRef:o,onMapChange:i}=t,s=zr(i),[,a]=e.useState(!1),c=Cr(il).current,l=Cr(ol).current,d=e.useRef(0),u=e.useRef(!0),p=e.useRef([]),h=e.useRef(null),f=zr(()=>{u.current||(u.current=!0,a(e=>!e))}),m=zr((e,t)=>{l.set(e,t),f()}),g=zr(e=>{l.delete(e),f()}),b=zr(e=>{const t=/* @__PURE__ */new Map;return r.current.length=0,o&&(o.current.length=0),e.forEach(e=>{t.set(e.element,{...e.registration.metadata??{},index:e.index}),r.current[e.index]=e.element,o&&(o.current[e.index]=void 0!==e.registration.label?e.registration.label:e.registration.textRef?.current?.textContent??e.element.textContent)}),d.current=r.current.length,t}),v=zr(()=>{const[e,t]=function(e){const t=/* @__PURE__ */new Set,n=[],r=[];e.forEach((e,o)=>{if(!o.isConnected)return;const i=e.index,s={index:i??-1,element:o,registration:e};null===i?r.push(s):i>=0&&(t.add(i),n.push(s))});let o=0;return r.sort((e,t)=>al(e.element,t.element)),r.forEach(e=>{for(;t.has(o);)o+=1;e.index=o,n.push(e),o+=1}),t.size>0&&n.sort((e,t)=>e.index-t.index),[n,r.map(e=>e.element)]}(l),n=b(e);!function(e){if(h.current?.disconnect(),h.current=null,"function"!=typeof MutationObserver||e.length<2)return;const t=new MutationObserver(n=>{if(!function(e){for(const t of e)for(let e=0;e<t.removedNodes.length;e+=1)if(t.removedNodes[e].isConnected)return!0;return!1}(n))return;let r=null;for(const o of e)if(o.isConnected){if(r&&al(r,o)>0)return t.disconnect(),void f();r=o}});h.current=t;const n=/* @__PURE__ */new Set;for(let r=1;r<e.length;r+=1){const t=sl(e[r-1],e[r]);t&&n.add(t)}n.forEach(e=>t.observe(e,{childList:!0}))}(t),p.current=e,u.current=!1,c.forEach(e=>e(n)),s(n)});Er(()=>(u.current||b(p.current),()=>{r.current=[],o&&(o.current=[])}),[r,o,b]),Er(()=>{u.current&&v()}),Er(()=>()=>{h.current?.disconnect(),u.current=!0},[]);const w=zr(e=>(c.add(e),()=>{c.delete(e)})),x=e.useMemo(()=>({register:m,unregister:g,subscribeMapChange:w,nextIndexRef:d}),[m,g,w,d]);/*#__PURE__*/
25
+ return y(nl.Provider,{value:x,children:n})}function ol(){/* @__PURE__ */
26
+ return new Map}function il(){/* @__PURE__ */
27
+ return new Set}function sl(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function al(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}var cl=/*#__PURE__*/e.createContext(void 0);function ll(){const t=e.useContext(cl);if(void 0===t)throw new Error(Ir(64));return t}var dl={tabActivationDirection:e=>({"data-activation-direction":e})},ul=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,defaultValue:o=0,onValueChange:i,orientation:s="horizontal",render:a,value:c,style:l,...d}=t,u=void 0!==t.defaultValue,p=e.useRef([]),[h,f]=e.useState(()=>/* @__PURE__ */new Map),[m,g]=function({controlled:t,default:n,name:r,state:o="value"}){const{current:i}=e.useRef(void 0!==t),[s,a]=e.useState(n);return[i?t:s,e.useCallback(e=>{i||a(e)},[])]}({controlled:c,default:o,name:"Tabs",state:"value"}),b=void 0!==c,[v,w]=e.useState(()=>/* @__PURE__ */new Map),x=e.useRef(void 0),S=e.useCallback(e=>pl(v,e),[v]),[k,C]=e.useState(()=>({previousValue:m,tabActivationDirection:"none"})),{previousValue:E,tabActivationDirection:I}=k;let M=I,T=!1;E!==m&&(M=hl(E,m,s,v),T=null!=E&&null!=m&&null==S(m));const R=T?E:m,O=E!==R||I!==M;Er(()=>{O&&C({previousValue:R,tabActivationDirection:M})},[R,O,M]);const A=zr((e,t)=>{t.activationDirection=hl(m,e,s,v),i?.(e,t),t.isCanceled||g(e)}),_=zr((e,t)=>{i?.(e,ls(t,void 0,void 0,{activationDirection:"none"}))}),D=zr((e,t)=>(f(n=>{const r=new Map(n);return r.set(e,t),r}),()=>{f(n=>{if(n.get(e)!==t)return n;const r=new Map(n);return r.delete(e),r})})),P=e.useCallback(e=>h.get(e),[h]),L=e.useCallback(e=>{for(const t of v.values())if(e===t.value)return t.id},[v]),N=e.useMemo(()=>({getTabElementBySelectedValue:S,getTabIdByPanelValue:L,getTabPanelIdByValue:P,onValueChange:A,orientation:s,registerMountedTabPanel:D,setTabMap:w,tabActivationDirection:M,value:m}),[S,L,P,A,s,D,w,M,m]),F=e.useMemo(()=>{for(const e of v.values())if(e.value===m)return e},[v,m]),z=e.useMemo(()=>{for(const e of v.values())if(!e.disabled)return e.value},[v]),$=e.useRef(!u),B=e.useRef(o),W=e.useRef(u),U=e.useRef(!1);Er(()=>{if(b)return;function e(e,t){g(e),C({previousValue:e,tabActivationDirection:"none"}),_(e,t),$.current=!1}if(0===v.size)return void(U.current&&null!==m&&!x.current?.isConnected&&e(null,as));U.current=!0,x.current=v.keys().next().value;const t=F?.disabled,n=null==F&&null!==m;if(t||m!==B.current||(W.current=!1),W.current&&t&&m===B.current)return;const r=$.current;if(t||n){const n=z??null;if(m===n)return void($.current=!1);let o=as;return r?o=cs:t&&(o="disabled"),void e(n,o)}r&&null!=F&&(_(m,cs),$.current=!1)},[z,b,_,F,g,v,m]);const H=Ti("div",t,{state:{orientation:s,tabActivationDirection:M},ref:n,props:d,stateAttributesMapping:dl});/*#__PURE__*/
28
+ return y(cl.Provider,{value:N,children:/*#__PURE__*/y(rl,{elementsRef:p,children:H})})});function pl(e,t){for(const[n,r]of e.entries())if(t===r.value)return n;return null}function hl(e,t,n,r){if(null==e||null==t)return"none";const[o,i,s]="horizontal"===n?["left","left","right"]:["top","up","down"],a=pl(r,e),c=pl(r,t);if(null==a||null==c)return a===c||"number"!=typeof e&&"string"!=typeof e||typeof e!=typeof t?"none":t>e?s:i;const l=a.getBoundingClientRect()[o],d=c.getBoundingClientRect()[o];return d<l?i:d>l?s:"none"}function fl(e){return Vi(e,"base-ui")}var ml="data-composite-item-active";function gl(t={}){const{guess:n,label:r,metadata:o,textRef:i,index:s}=t,{register:a,unregister:c,subscribeMapChange:l,nextIndexRef:d}=e.useContext(nl),u=e.useRef(-1),[p,h]=e.useState(null==s&&n?()=>{if(-1===u.current){const e=d.current;d.current+=1,u.current=e}return u.current}:-1),f=s??p,m=e.useRef(null),g=e.useCallback(e=>{const t=m.current;t&&c(t),m.current=e,e&&a(e,{metadata:o??null,index:s??null,label:r,textRef:i})},[s,a,c,o,r,i]);return Er(()=>{if(null==s)return l(e=>{const t=m.current?e.get(m.current)?.index:null;null!=t&&h(t)})},[s,l]),{ref:g,index:f}}var yl=/*#__PURE__*/e.createContext(void 0),bl=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,disabled:o=!1,render:i,value:s,id:a,nativeButton:c=!0,style:l,...d}=t,{value:u,getTabPanelIdByValue:p,onValueChange:h,orientation:f,tabActivationDirection:m}=ll(),{activateOnFocus:g,registerTabResizeObserverElement:y,tabsListElement:b}=function(){const t=e.useContext(yl);if(void 0===t)throw new Error(Ir(65));return t}(),{highlightedIndex:v,onHighlightedIndexChange:w}=es(),x=fl(a),S=e.useMemo(()=>({disabled:o,id:x,value:s}),[o,x,s]),{compositeProps:k,compositeRef:C,index:E}=function(t={}){const{highlightItemOnHover:n,highlightedIndex:r,onHighlightedIndexChange:o}=es(),{ref:i,index:s}=gl(t),a=r===s,c=e.useRef(null),l=ui(i,c);return{compositeProps:{tabIndex:a?0:-1,onFocus(){o(s)},onMouseMove(){const e=c.current;if(!n||!e)return;const t=e.hasAttribute("disabled")||"true"===e.ariaDisabled;a||t||e.focus()}},compositeRef:l,index:s}}({metadata:S}),I=s===u,M=e.useRef(!1),T=e.useRef(null),R=zr(e=>{T.current?.(),T.current=e?y(e):null});Er(()=>{if(M.current)return void(M.current=!1);if(!(I&&E>-1&&v!==E))return;const e=b;if(null!=e){const t=Co(Qr(e));if(t&&Eo(e,t))return}o||w(E)},[I,E,v,w,o,b]);const{getButtonProps:O,buttonRef:A}=ns({disabled:o,native:c,focusableWhenDisabled:!0}),_=p(s),D=e.useRef(!1),P=e.useRef(!1);function L(e){h(s,ls(ss,e.nativeEvent,void 0,{activationDirection:"none"}))}return Ti("button",t,{state:{disabled:o,active:I,orientation:f,tabActivationDirection:m},ref:[n,A,C,R],props:[k,{role:"tab","aria-controls":_,"aria-selected":I,id:x,onClick:function(e){I||o||L(e)},onFocus:function(e){I||o||!g||D.current&&!P.current||L(e)},onPointerDown:function(e){if(I||o)return;D.current=!0,P.current=0===e.button;const t=Qr(e.currentTarget);function n(){D.current=!1,P.current=!1,t.removeEventListener("pointerup",n),t.removeEventListener("pointercancel",n)}t.addEventListener("pointerup",n),t.addEventListener("pointercancel",n)},[ml]:I?"":void 0,onKeyDownCapture(){M.current=!0}},d,O],stateAttributesMapping:dl})}),vl={...dl,...Fi},wl=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,value:o,render:i,keepMounted:s=!1,style:a,...c}=t,{value:l,getTabIdByPanelValue:d,orientation:u,tabActivationDirection:p,registerMountedTabPanel:h}=ll(),f=fl(),{ref:m,index:g}=gl(),y=o===l,{mounted:b,transitionStatus:v,setMounted:w}=qs(y),x=!b,S=d(o),k={hidden:x,orientation:u,tabActivationDirection:p,transitionStatus:v},C=e.useRef(null),E=Ti("div",t,{state:k,ref:[n,m,C],props:[{"aria-labelledby":S,hidden:x,id:f,role:"tabpanel",tabIndex:y?0:-1,inert:Ai(!y),"data-index":g},c],stateAttributesMapping:vl});return $i({open:y,ref:C,onComplete(){y||w(!1)}}),Er(()=>{if(null!=f&&(!x||s))return h(o,f)},[x,s,o,f,h]),s||b?E:null}),xl="ArrowUp",Sl="ArrowDown",kl="ArrowLeft",Cl="ArrowRight",El=/* @__PURE__ */new Set([xl,Sl,kl,Cl,"Home","End"]),Il=["Shift","Control","Alt","Meta"];function Ml(e){return!(!function(e){return Yr(e)&&"INPUT"===e.tagName}(e)||null==e.selectionStart)||!(!Yr(e)||"TEXTAREA"!==e.tagName)}function Tl(e,t,n,r){if(!e||!t||!t.scrollTo)return;let o=e.scrollLeft,i=e.scrollTop;const s=e.clientWidth<e.scrollWidth,a=e.clientHeight<e.scrollHeight;if(s&&"vertical"!==r){const r=Rl(e,t,"left"),i=Ol(e),s=Ol(t);"ltr"===n&&(r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight?o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight:r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft&&(o=r-s.scrollMarginLeft-i.scrollPaddingLeft)),"rtl"===n&&(r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft?o=r-s.scrollMarginLeft-i.scrollPaddingLeft:r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight&&(o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight))}if(a&&"horizontal"!==r){const n=Rl(e,t,"top"),r=Ol(e),o=Ol(t);n-o.scrollMarginTop<e.scrollTop+r.scrollPaddingTop?i=n-o.scrollMarginTop-r.scrollPaddingTop:n+t.offsetHeight+o.scrollMarginBottom>e.scrollTop+e.clientHeight-r.scrollPaddingBottom&&(i=n+t.offsetHeight+o.scrollMarginBottom-e.clientHeight+r.scrollPaddingBottom)}e.scrollTo({left:o,top:i,behavior:"auto"})}function Rl(e,t,n){const r="left"===n?"offsetLeft":"offsetTop";let o=0;for(;t.offsetParent&&(o+=t[r],t.offsetParent!==e);)t=t.offsetParent;return o}function Ol(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}var Al=[];function _l(t){const{render:n,className:r,style:o,refs:i=wr,props:s=wr,state:a=xr,stateAttributesMapping:c,highlightedIndex:l,onHighlightedIndexChange:d,orientation:u,grid:p,loopFocus:h,onLoop:f,enableHomeAndEndKeys:m,onMapChange:g,stopEventPropagation:b=!0,rootRef:v,disabledIndices:w,modifierKeys:x,highlightItemOnHover:S=!1,tag:k="div",...C}=t,E=e.useContext(ta)?.direction??"ltr",{props:I,highlightedIndex:M,onHighlightedIndexChange:T,elementsRef:R,onMapChange:O,relayKeyboardEvent:A}=function(t){const{loopFocus:n=!0,orientation:r="both",grid:o,onLoop:i,direction:s,highlightedIndex:a,onHighlightedIndexChange:c,rootRef:l,enableHomeAndEndKeys:d=!1,stopEventPropagation:u,disabledIndices:p,modifierKeys:h=Al}=t,[f,m]=e.useState(0),g=null!=o,y=e.useRef(null),b=ui(y,l),v=e.useRef([]),w=e.useRef(!1),x=a??f,S=zr((e,t=!1)=>{if((c??m)(e),t){const t=v.current[e];Tl(y.current,t,s,r)}}),k=zr(e=>{if(0===e.size||w.current)return;w.current=!0;const t=Array.from(e.keys()),n=t.find(e=>e?.hasAttribute("data-composite-item-active"))??null,o=n?e.get(n)?.index??-1:-1;if(-1!==o)S(o);else if(No(t,x,p)){const e=Lo(t,{disabledIndices:p});Po(t,e)||S(e)}Tl(y.current,n,s,r)});Er(()=>{if(null==p||null!=a||!w.current)return;const e=v.current;if(No(e,x,p)){const t=Lo(e,{disabledIndices:p});Po(e,t)||S(t)}},[p,a,x,v,S]);const C=zr((e,t,n)=>i?i(e,t,n,v):n),E=zr(e=>{const t="Home"===e.key||"End"===e.key;if(!El.has(e.key)||!d&&t)return;if(function(e,t){for(const n of Il)if(!t.includes(n)&&e.getModifierState(n))return!0;return!1}(e,h))return;if(!y.current)return;const a="rtl"===s,c=a?kl:Cl,l=a?Cl:kl,f="vertical"===r?Sl:c,m="vertical"===r?xl:l,b=Io(e.nativeEvent);if(null!=b&&Ml(b)&&null!=(w=b)&&!w.hasAttribute("disabled")&&"true"!==w.getAttribute("aria-disabled")){const t=b.selectionStart,n=b.selectionEnd,r=b.value;if(null==t||e.shiftKey||t!==n)return;if(e.key!==m&&t<r.length)return;if(e.key!==f&&t>0)return}var w;let k=x;const E=function(e,t){return Lo(e.current,{disabledIndices:t})}(v,p),I=function(e,t){return Lo(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}(v,p);null!=o&&(k=o({disabledIndices:p,elementsRef:v,event:e,highlightedIndex:x,loopFocus:n,maxIndex:I,minIndex:E,onLoop:C,orientation:r,rtl:a}));const M="vertical"!==r&&e.key===c||"horizontal"!==r&&"ArrowDown"===e.key,T="vertical"!==r&&e.key===l||"horizontal"!==r&&"ArrowUp"===e.key;d&&("Home"===e.key?k=E:"End"===e.key&&(k=I)),k===x&&(M||T)&&(n&&k===I&&M?(k=E,i&&(k=i(e,x,k,v))):n&&k===E&&T?(k=I,i&&(k=i(e,x,k,v))):k=Lo(v.current,{startingIndex:k,decrement:T,disabledIndices:p})),k===x||Po(v.current,k)||(u&&e.stopPropagation(),(g||t||M||T)&&e.preventDefault(),S(k,!0),queueMicrotask(()=>{v.current[k]?.focus()}))});return{props:{ref:b,onFocus(e){const t=y.current,n=Io(e.nativeEvent);t&&null!=n&&Ml(n)&&n.setSelectionRange(0,n.value.length)},onKeyDown:E},highlightedIndex:x,onHighlightedIndexChange:S,elementsRef:v,onMapChange:k,relayKeyboardEvent:E}}({grid:p,loopFocus:h,onLoop:f,orientation:u,highlightedIndex:l,onHighlightedIndexChange:d,rootRef:v,stopEventPropagation:b,enableHomeAndEndKeys:m,direction:E,disabledIndices:w,modifierKeys:x}),_=Ti(k,t,{state:a,ref:i,props:[I,...s,C],stateAttributesMapping:c}),D=e.useMemo(()=>({highlightedIndex:M,onHighlightedIndexChange:T,highlightItemOnHover:S,relayKeyboardEvent:A}),[M,T,S,A]);/*#__PURE__*/
29
+ return y(Qi.Provider,{value:D,children:/*#__PURE__*/y(rl,{elementsRef:R,onMapChange:e=>{g?.(e),O(e)},children:_})})}var Dl=/*#__PURE__*/e.forwardRef(function(t,n){const{activateOnFocus:r=!1,className:o,loopFocus:i=!0,render:s,style:a,...c}=t,{orientation:l,setTabMap:d,tabActivationDirection:u}=ll(),[p,h]=e.useState(0),[f,m]=e.useState(null),g=e.useRef(/* @__PURE__ */new Set),b=e.useRef(/* @__PURE__ */new Set),v=e.useRef(null);Er(()=>{if("undefined"==typeof ResizeObserver)return;const e=new ResizeObserver(()=>{g.current.forEach(e=>{e()})});return v.current=e,f&&e.observe(f),b.current.forEach(t=>{e.observe(t)}),()=>{e.disconnect(),v.current=null}},[f]);const w=zr(e=>(g.current.add(e),()=>{g.current.delete(e)})),x=zr(e=>(b.current.add(e),v.current?.observe(e),()=>{b.current.delete(e),v.current?.unobserve(e)})),S={orientation:l,tabActivationDirection:u},k={"aria-orientation":"vertical"===l?"vertical":void 0,role:"tablist"},C=e.useMemo(()=>({activateOnFocus:r,registerIndicatorUpdateListener:w,registerTabResizeObserverElement:x,tabsListElement:f}),[r,w,x,f]);/*#__PURE__*/
30
+ return y(yl.Provider,{value:C,children:/*#__PURE__*/y(_l,{render:s,className:o,style:a,state:S,refs:[n,m],props:[k,c],stateAttributesMapping:dl,highlightedIndex:p,enableHomeAndEndKeys:!0,loopFocus:i,orientation:l,onHighlightedIndexChange:h,onMapChange:d,disabledIndices:wr})})});function Pl(e){const t=e.getRootNode();return(t instanceof ShadowRoot?t.activeElement:document.activeElement)??null}function Ll(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!e.hasAttribute("aria-hidden"))}function Nl(e,t,n){return Math.min(Math.max(e,t),n)}function Fl({width:e,height:t}){return{width:Nl(e,280,600),height:Nl(t,320,Math.floor(.85*window.innerHeight))}}function zl(e,t){const n=/^\s*(\d+(?:\.\d+)?)px\s*$/.exec(e??"");return n?Number(n[1]):t}var $l={"top-left":{growX:-1,growY:-1,cursor:"nwse-resize"},"top-right":{growX:1,growY:-1,cursor:"nesw-resize"},"bottom-left":{growX:-1,growY:1,cursor:"nesw-resize"},"bottom-right":{growX:1,growY:1,cursor:"nwse-resize"}},Bl=({title:e,subtitle:t,onClose:n,controls:r})=>/* @__PURE__ */b(Aa,{align:"center",justify:"between",paddingX:"lg",paddingY:"md",border:"bottom",shrink:!1,elevation:"section",children:[/* @__PURE__ */b(Aa,{align:"center",gap:"md",minWidth:"0",grow:!0,children:[/* @__PURE__ */y(Ca,{src:ca,alt:"",size:"md",rounded:"theme",elevation:"card"}),/* @__PURE__ */b(Na,{minWidth:"0",children:[/* @__PURE__ */y(Ba,{size:"sm",weight:"semibold",truncate:!0,leading:"tight",children:e}),null!=t&&/* @__PURE__ */y(Ba,{as:"p",size:"xs",variant:"muted",truncate:!0,children:t})]})]}),/* @__PURE__ */b(Aa,{align:"center",gap:"2xs",shrink:!1,children:[r,/* @__PURE__ */y(La,{size:"sm",label:"Close",onClick:n,children:/* @__PURE__ */y(Pa,{name:"close",size:16})})]})]});function Wl(e){const t=u(e);return t.current=e,t}function Ul(...e){return t=>{e.forEach(e=>{"function"==typeof e?e(t):e&&(e.current=t)})}}function Hl({value:e,onChange:t,onSubmit:n,modes:r=[],activeMode:o,onModeChange:s,disabled:c=!1,taskRunning:l=!1,onStop:d,ref:p}){const h=u(null);a(()=>{const e=h.current;if(!e)return;e.style.height="auto";const{scrollHeight:t}=e;e.style.height=`${Math.min(t,66)}px`,e.style.overflowY=t>66?"auto":"hidden"},[e]);const f=i(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())},[n]),m=Boolean(e.trim())&&!c;/* @__PURE__ */
31
+ return b(Na,{background:"card",rounded:"xl",border:!0,overflow:"hidden",className:"mtx-composer",children:[/* @__PURE__ */y("textarea",{ref:Ul(h,p),value:e,onChange:e=>t(e.target.value),onKeyDown:f,placeholder:"Ask anything",disabled:c,rows:1,className:"mtx-composer-input",style:{lineHeight:"20px",paddingTop:"4px",paddingBottom:"2px",minHeight:"unset"}}),/* @__PURE__ */b(Aa,{align:"center",justify:"between",paddingX:"sm",paddingTop:"xs",paddingBottom:"sm",children:[/* @__PURE__ */y(Aa,{align:"center",gap:"xs",children:r.map(e=>{const t=o===e.id;/* @__PURE__ */
32
+ return b("button",{type:"button",className:"mtx-mode-chip","data-active":t?"true":"false",onClick:t=>{t.preventDefault(),t.stopPropagation(),s?.(e.id)},children:[/* @__PURE__ */y(Pa,{name:e.icon,size:12}),/* @__PURE__ */y(Ba,{as:"span",inheritColor:!0,children:e.label})]},e.id)})}),/* @__PURE__ */y(La,{variant:l?"secondary":"primary",size:"sm",disabled:!l&&!m,label:l?"Stop the assistant":"Send message",onClick:e=>{e.preventDefault(),e.stopPropagation(),l&&d?d():n()},children:/* @__PURE__ */y(Pa,l?{name:"stop",size:14}:{name:"send",size:16})})]})]})}var jl=/*#__PURE__*/e.createContext(void 0);function ql(t){const n=e.useContext(jl);if(!t&&void 0===n)throw new Error(Ir(27));return n}var Vl=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,forceRender:i=!1,...s}=e,a=ql(),c=a.useState("open"),l=a.useState("nested"),d=a.useState("mounted");return Ti("div",e,{state:{open:c,transitionStatus:a.useState("transitionStatus")},ref:[a.context.backdropRef,t],stateAttributesMapping:sa,props:[{role:"presentation",hidden:!d,style:{userSelect:"none",WebkitUserSelect:"none"}},s],enabled:i||!l})}),Yl=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=ql(),c=fl(i);return a.useSyncedValueWithCleanup("descriptionElementId",c),Ti("p",e,{ref:t,props:[{id:c},s]})}),Kl=/*#__PURE__*/e.createContext(void 0),Xl={...ia,...Fi,nestedDialogOpen:e=>e?{"data-nested-dialog-open":""}:null},Gl=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,finalFocus:s,initialFocus:a,...c}=t,l=ql(),d=l.useState("descriptionElementId"),u=l.useState("disablePointerDismissal"),p=l.useState("floatingRootContext"),h=l.useState("popupProps"),f=l.useState("modal"),m=l.useState("mounted"),g=l.useState("nested"),b=l.useState("nestedOpenDialogCount"),v=l.useState("open"),w=l.useState("openMethod"),x=l.useState("titleElementId"),S=l.useState("transitionStatus"),k=l.useState("role"),C=p.useState("floatingId");!function(){if(void 0===e.useContext(Kl))throw new Error(Ir(26))}(),$i({open:v,ref:l.context.popupRef,onComplete(){v&&l.context.onOpenChangeComplete?.(!0)}});const E=void 0===a?(I=l.context.popupRef,e=>"touch"!==e||I.current):a;var I;const M=b>0,T=l.useStateSetter("popupElement"),R=Ti("div",t,{state:{open:v,nested:g,transitionStatus:S,nestedDialogOpen:M},props:[h,{id:C,"aria-labelledby":x,"aria-describedby":d,role:k,...Vs,hidden:!m,onKeyDown(e){El.has(e.key)&&e.stopPropagation()},style:{"--nested-dialogs":b}},c],ref:[n,l.context.popupRef,T],stateAttributesMapping:Xl});/*#__PURE__*/
33
+ return y(Ws,{context:p,openInteractionType:w,disabled:!m,closeOnFocusOut:!u,initialFocus:E,returnFocus:s,modal:!1!==f,restoreFocus:"popup",children:R})}),Jl=/*#__PURE__*/e.forwardRef(function(e,t){const{cutout:n,...r}=e;let o;if(n){const e=n.getBoundingClientRect();o=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${e.left}px ${e.top}px,${e.left}px ${e.bottom}px,${e.right}px ${e.bottom}px,${e.right}px ${e.top}px,${e.left}px ${e.top}px)`}/*#__PURE__*/
34
+ return y("div",{ref:t,role:"presentation","data-base-ui-inert":"",...r,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:o}})}),Zl=/*#__PURE__*/e.forwardRef(function(e,t){const{keepMounted:n=!1,...r}=e,o=ql(),i=o.useState("mounted"),s=o.useState("modal"),a=o.useState("open");return i||n?/*#__PURE__*/y(Kl.Provider,{value:n,children:/*#__PURE__*/b(ms,{ref:t,...r,children:[i&&!0===s&&/*#__PURE__*/y(Jl,{ref:o.context.internalBackdropRef,inert:Ai(!a)}),e.children]})}):null}),Ql={},ed={},td="";function nd(e,t){return function(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Gr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==o&&"contents"!==o}(e)?e:t}function rd(e,t,n){return/hidden|clip/.test(e.getComputedStyle(nd(t,n)).overflowY)}var od=new class{lockCount=0;restore=null;timeoutLock=io.create();timeoutUnlock=io.create();acquire(e){return this.lockCount+=1,1===this.lockCount&&null===this.restore&&this.timeoutLock.start(0,()=>this.lock(e)),this.release}release=()=>{this.lockCount-=1,0===this.lockCount&&this.restore&&this.timeoutUnlock.start(0,this.unlock)};unlock=()=>{0===this.lockCount&&this.restore&&(this.restore?.(),this.restore=null)};lock(e){if(0===this.lockCount||null!==this.restore)return;const t=Qr(e),n=t.documentElement,r=t.body,o=jr(n);if(rd(o,n,r)){const t=new o.MutationObserver(()=>{rd(o,n,r)||(t.disconnect(),this.restore=null,this.lock(e))}),i={attributes:!0};return t.observe(n,i),t.observe(r,i),void(this.restore=()=>t.disconnect())}const i=mo||!function(e){if("undefined"==typeof document)return!1;const t=Qr(e);return jr(t).innerWidth-t.documentElement.clientWidth>0}(e);this.restore=i?function(e){const t=Qr(e),n=nd(t.documentElement,t.body),r={overflowY:n.style.overflowY,overflowX:n.style.overflowX};return Object.assign(n.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(n.style,r)}}(e):function(e){const t=Qr(e),n=t.documentElement,r=t.body,o=jr(n);let i=0,s=0,a=!1;const c=ro.create();if(wo&&1!==(o.visualViewport?.scale??1))return()=>{};function l(){const t=o.getComputedStyle(n),c=o.getComputedStyle(r),l=(t.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";i=n.scrollTop,s=n.scrollLeft,Ql={scrollbarGutter:n.style.scrollbarGutter,overflowY:n.style.overflowY,overflowX:n.style.overflowX},td=n.style.scrollBehavior,ed={position:r.style.position,height:r.style.height,width:r.style.width,boxSizing:r.style.boxSizing,overflowY:r.style.overflowY,overflowX:r.style.overflowX,scrollBehavior:r.style.scrollBehavior};const d=n.scrollHeight>n.clientHeight,u=n.scrollWidth>n.clientWidth,p="scroll"===t.overflowY||"scroll"===c.overflowY,h="scroll"===t.overflowX||"scroll"===c.overflowX,f=Math.max(0,o.innerWidth-r.clientWidth),m=Math.max(0,o.innerHeight-r.clientHeight),g=parseFloat(c.marginTop)+parseFloat(c.marginBottom),y=parseFloat(c.marginLeft)+parseFloat(c.marginRight),b=nd(n,r);if(a=function(e){if("undefined"==typeof CSS||!CSS.supports||!CSS.supports("scrollbar-gutter","stable")||"undefined"==typeof document)return!1;const t=Qr(e),n=t.documentElement,r=nd(n,t.body),o=r.style.overflowY,i=n.style.scrollbarGutter;n.style.scrollbarGutter="stable",r.style.overflowY="scroll";const s=r.offsetWidth;r.style.overflowY="hidden";const a=r.offsetWidth;return r.style.overflowY=o,n.style.scrollbarGutter=i,s===a}(e),a)return n.style.scrollbarGutter=l,b.style.overflowY="hidden",void(b.style.overflowX="hidden");Object.assign(n.style,{scrollbarGutter:l,overflowY:"hidden",overflowX:"hidden"}),(d||p)&&(n.style.overflowY="scroll"),(u||h)&&(n.style.overflowX="scroll"),Object.assign(r.style,{position:"relative",height:g||m?`calc(100dvh - ${g+m}px)`:"100dvh",width:y||f?`calc(100vw - ${y+f}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),r.scrollTop=i,r.scrollLeft=s,n.setAttribute("data-base-ui-scroll-locked",""),n.style.scrollBehavior="unset"}function d(){Object.assign(n.style,Ql),Object.assign(r.style,ed),a||(n.scrollTop=i,n.scrollLeft=s,n.removeAttribute("data-base-ui-scroll-locked"),n.style.scrollBehavior=td)}l();const u=eo(o,"resize",function(){d(),c.request(l)});return()=>{c.cancel(),d(),"function"==typeof o.removeEventListener&&u()}}(e)}};function id({store:t,parentContext:n,isDrawer:r}){const o=t.useState("open"),i=t.useState("disablePointerDismissal"),s=t.useState("modal"),a=t.useState("popupElement"),c=t.useState("floatingRootContext"),[l,d]=e.useState(0),[u,p]=e.useState(0),h=0===l,f=function(t,n={}){const{enabled:r=!0,escapeKey:o=!0,outsidePress:i=!0,outsidePressEvent:s="sloppy",referencePress:a=Us,bubbles:c,externalTree:l}=n,d="rootStore"in t?t.rootStore:t,u=d.useState("open"),p=d.useState("floatingElement"),{dataRef:h}=d.context,f=Ls(l),m=zr("function"==typeof i?i:()=>!1),g="function"==typeof i?m:i,y=!1!==g,b=zr(()=>s),{escapeKey:v,outsidePress:w}={escapeKey:"boolean"==typeof(x=c)?x:x?.escapeKey??!1,outsidePress:"boolean"==typeof x?x:x?.outsidePress??!0};var x;const S=e.useRef(!1),k=e.useRef(!1),C=e.useRef(!1),E=e.useRef(!1),I=e.useRef(""),M=e.useRef(null),T=so(),R=so(),O=zr(()=>{R.clear(),h.current.insideReactTree=!1}),A=zr(e=>{const t=h.current.floatingContext?.nodeId;return(f?_o(f.nodesRef.current,t):[]).some(t=>t.context?.open&&!t.context.dataRef.current[e])}),_=zr(e=>Mo(e,d.select("floatingElement"))||Mo(e,d.select("domReferenceElement"))),D=zr(e=>{a()&&d.setOpen(!1,ls("trigger-press",e.nativeEvent))}),P=zr(e=>{if(!u||!r||!o||"Escape"!==e.key)return;if(E.current)return;if(!v&&A("__escapeKeyBubbles"))return;const t=ls("escape-key",function(e){return"nativeEvent"in e}(e)?e.nativeEvent:e);d.setOpen(!1,t),t.isCanceled||e.preventDefault(),v||t.isPropagationAllowed||e.stopPropagation()}),L=zr(()=>{h.current.insideReactTree=!0,R.start(0,O)}),N=zr(e=>{if(!u||!r||0!==e.button)return;const t=Io(e.nativeEvent);Eo(d.select("floatingElement"),t)&&(S.current||(S.current=!0,k.current=!1))}),F=zr(e=>{u&&r&&(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&S.current&&(k.current=!0)});e.useEffect(()=>{if(!u||!r)return O;h.current.__escapeKeyBubbles=v,h.current.__outsidePressBubbles=w;const e=new io,t=new io;function n(){C.current=!0,t.start(0,()=>{C.current=!1})}function i(){S.current=!1,k.current=!1}function s(){const e=I.current,t="pen"!==e&&e?e:"mouse",n=b(),r="function"==typeof n?n():n;return"string"==typeof r?r:r[t]}function a(e){const t=h.current.floatingContext?.nodeId,n=f&&_o(f.nodesRef.current,t).some(t=>Mo(e,t.context?.elements.floating));return _(e)||n}function c(e){if(function(e){const t=s();return"intentional"===t&&"click"!==e.type||"sloppy"===t&&"click"===e.type}(e))return"click"===e.type||_(e)||(t.clear(),C.current=!1),void O();if(h.current.insideReactTree)return void O();const n=Io(e),r=`[${ds("inert")}]`,o=Vr(n)?n.getRootNode():null,i=Array.from((Kr(o)?o:Qr(d.select("floatingElement"))).querySelectorAll(r)),c=d.context.triggerElements;if(n&&(c.hasElement(n)||c.hasMatchingElement(e=>Eo(e,n))))return;let l=Vr(n)?n:null;for(;l&&!Xr(l);){const e=Jr(l);if(Xr(e)||!Vr(e))break;l=e}if(!i.length||!Vr(n)||n.matches("html,body")||Eo(n,d.select("floatingElement"))||!i.every(e=>!Eo(l,e))){if(Yr(n)&&!("touches"in e)){const t=Xr(n),r=Gr(n),o=/auto|scroll/,i=t||o.test(r.overflowX),s=t||o.test(r.overflowY),a=i&&n.clientWidth>0&&n.scrollWidth>n.clientWidth,c=s&&n.clientHeight>0&&n.scrollHeight>n.clientHeight,l="rtl"===r.direction,d=c&&(l?e.offsetX<=n.offsetWidth-n.clientWidth:e.offsetX>n.clientWidth),u=a&&e.offsetY>n.clientHeight;if(d||u)return}if(!a(e))return"intentional"===s()&&C.current?(t.clear(),void(C.current=!1)):void(("function"!=typeof g||g(e))&&(A("__outsidePressBubbles")||(d.setOpen(!1,ls("outside-press",e)),O())))}}function l(e){if("sloppy"!==s()||!d.select("open")||!r||_(e))return;const t=e.touches[0];t&&(M.current={startTime:Date.now(),startX:t.clientX,startY:t.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},T.start(1e3,()=>{M.current&&(M.current.dismissOnTouchEnd=!1,M.current.dismissOnMouseDown=!1)}))}function m(e,t){const n=Io(e);if(!n)return;const r=eo(n,e.type,()=>{t(e),r()})}function x(e){T.clear(),"pointerdown"===e.type&&(I.current=e.pointerType),"mousedown"===e.type&&M.current&&!M.current.dismissOnMouseDown||m(e,e=>{"pointerdown"===e.type?function(e){"sloppy"===s()&&"touch"!==e.pointerType&&d.select("open")&&r&&!_(e)&&c(e)}(e):c(e)})}function R(e){if(!S.current)return;const r=k.current;i(),"intentional"===s()&&("pointercancel"!==e.type?a(e)||(r?n():("function"!=typeof g||g(e))&&(t.clear(),C.current=!0,O())):r&&n())}function D(e){if("sloppy"!==s()||!M.current||_(e))return;const t=e.touches[0];if(!t)return;const n=Math.abs(t.clientX-M.current.startX),r=Math.abs(t.clientY-M.current.startY),o=Math.sqrt(n*n+r*r);o>5&&(M.current.dismissOnTouchEnd=!0),o>10&&(c(e),T.clear(),M.current=null)}function L(e){"sloppy"===s()&&M.current&&!_(e)&&(M.current.dismissOnTouchEnd&&c(e),T.clear(),M.current=null)}const N=Qr(p),F=Zr(o&&Zr(eo(N,"keydown",P),eo(N,"compositionstart",function(){e.clear(),E.current=!0}),eo(N,"compositionend",function(){e.start(wo?5:0,()=>{E.current=!1})})),y&&Zr(eo(N,"click",x,!0),eo(N,"pointerdown",x,!0),eo(N,"pointerup",R,!0),eo(N,"pointercancel",R,!0),eo(N,"mousedown",x,!0),eo(N,"mouseup",R,!0),eo(N,"touchstart",function(e){I.current="touch",m(e,l)},!0),eo(N,"touchmove",function(e){m(e,D)},!0),eo(N,"touchend",function(e){m(e,L)},!0)));return()=>{F(),e.clear(),t.clear(),i(),C.current=!1,O()}},[h,p,o,y,g,u,r,v,w,P,O,b,A,_,f,d,T]);const z=e.useMemo(()=>({onKeyDown:P,onPointerDown:D,onClick:D}),[P,D]),$=e.useMemo(()=>({onKeyDown:P,onPointerDown:F,onMouseDown:F,onClickCapture:L,onMouseDownCapture(e){L(),N(e)},onPointerDownCapture(e){L(),N(e)},onMouseUpCapture:L,onTouchEndCapture:L,onTouchMoveCapture:L}),[P,L,N,F]);return e.useMemo(()=>r?{reference:z,floating:$,trigger:z}:{},[r,z,$])}(c,{outsidePressEvent:()=>t.context.internalBackdropRef.current||t.context.backdropRef.current?"intentional":{mouse:"trap-focus"===s?"sloppy":"intentional",touch:"sloppy"},outsidePress(e){if(!t.context.outsidePressEnabledRef.current)return!1;if("button"in e&&0!==e.button)return!1;if("touches"in e)if("touchend"===e.type){if(1!==e.changedTouches.length||0!==e.touches.length)return!1}else if(1!==e.touches.length)return!1;const n=Io(e);if(h&&!i){if(s){const e=t.context.internalBackdropRef.current,r=t.context.backdropRef.current;return!e&&!r||e===n||r===n||Eo(n,a)&&!n?.hasAttribute("data-base-ui-portal")}return!0}return!1},escapeKey:h});return function(e=!0,t=null){Er(()=>{if(e)return od.acquire(t)},[e,t])}(o&&!0===s,a),t.useContextCallback("onNestedDialogOpen",(e,t)=>{d(e),p(t)}),Er(()=>(n?.onNestedDialogOpen&&(o?n.onNestedDialogOpen(l+1,u+(r?1:0)):n.onNestedDialogOpen(0,0)),()=>{n?.onNestedDialogOpen&&o&&n.onNestedDialogOpen(0,0)}),[r,o,l,u,n]),function(e,t){e.useSyncedValues(t),Er(()=>()=>{e.update({activeTriggerProps:xr,inactiveTriggerProps:xr,popupProps:xr})},[e])}(t,{activeTriggerProps:f.reference,inactiveTriggerProps:f.trigger,popupProps:f.floating,nestedOpenDialogCount:l,nestedOpenDrawerCount:u}),null}var sd={...ea,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role},ad=class extends Wr{constructor(t,n,r){const o=new Ks,i=function(e,t,n,r=!1){const o={open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new js({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new Ks,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0}),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:xr,inactiveTriggerProps:xr,popupProps:xr,modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e};return o.floatingRootContext=function(e,t,n=!1){return new js({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:n,onOpenChange:void 0})}(t,n,r),o}(t,o,n,r);super(i,function(t){return{popupRef:/*#__PURE__*/e.createRef(),backdropRef:/*#__PURE__*/e.createRef(),internalBackdropRef:/*#__PURE__*/e.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:t,onOpenChange:void 0,onOpenChangeComplete:void 0}}(o),sd)}setOpen=(e,t)=>{if(t.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},e||null!=t.trigger||null==this.state.activeTriggerId||(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);const n={open:e};!function(e,t,n,r=!1){t?e.preventUnmountingOnClose=!1:r&&(e.preventUnmountingOnClose=!0);const o=n?.id??null;(o||t)&&(e.activeTriggerId=o,e.activeTriggerElement=n??null)}(n,e,t.trigger),this.update(n)}};function cd(t){return function(t,n){const{children:r,open:o,defaultOpen:i=!1,onOpenChange:s,onOpenChangeComplete:a,disablePointerDismissal:c=!1,modal:l=!0,actionsRef:d,handle:u,triggerId:p,defaultTriggerId:h=null}=n,f="drawer"===t,m="alert-dialog"===t,g=!!m||l,v=m||c,w=m?"alertdialog":"dialog",x=ql(!0),S={modal:g,disablePointerDismissal:v,nested:null!=x,role:w},k=function(t,n=!1){const r=Vi(),o=null!=(e.useContext(Ds)?.id||null),i=Cr(()=>t(r,o)).current;return function(t){const{popupStore:n,treatPopupAsFloatingElement:r=!1,floatingRootContext:o,floatingId:i,nested:s,onOpenChange:a}=t,c=n.useState("open"),l=n.useState("activeTriggerElement"),d=n.useState(r?"popupElement":"positionerElement"),u=n.context.triggerElements,p=a,h=e.useRef(null);void 0===o&&null===h.current&&(h.current=new js({open:c,transitionStatus:void 0,referenceElement:l,floatingElement:d,triggerElements:u,onOpenChange:p,floatingId:i,syncOnly:!0,nested:s}));const f=o??h.current;n.useSyncedValue("floatingId",i),Er(()=>{const e={open:c,floatingId:i,referenceElement:l,floatingElement:d};Vr(l)&&(e.domReferenceElement=l),f.state.positionReference===f.state.referenceElement&&(e.positionReference=l),f.update(e)},[c,i,l,d,f]),f.context.onOpenChange=p,f.context.nested=s}({popupStore:i,treatPopupAsFloatingElement:n,floatingRootContext:i.state.floatingRootContext,floatingId:r,nested:o,onOpenChange:i.setOpen}),i}((e,t)=>new ad({open:i,openProp:o,activeTriggerId:h,triggerIdProp:p,...S},e,t),!0);k.useControlledProp("openProp",o),k.useControlledProp("triggerIdProp",p),k.useSyncedValues(S),k.useContextCallback("onOpenChange",s),k.useContextCallback("onOpenChangeComplete",a);const C=k.useState("open"),E=k.useState("mounted"),I=k.useState("payload");!function(e,t){Er(()=>{t||null===e.state.openMethod||e.set("openMethod",null)},[t,e]),Er(()=>()=>{null!==e.state.openMethod&&e.set("openMethod",null)},[e])}(k,C),function(t,n={}){const{closeOnActiveTriggerUnmount:r=!1}=n,o=e.useRef(null),i=t.useState("open"),s=t.useState("triggerCount"),a=t.useState("activeTriggerId"),c=t.useState("activeTriggerElement");Er(()=>{if(!i)return o.current=null,void(0!==t.state.triggerCount&&t.set("triggerCount",0));const e=t.context.triggerElements.size,n={};t.state.triggerCount!==e&&(n.triggerCount=e);const s=t.select("activeTriggerId");let a=null;if(s){const e=t.context.triggerElements.getById(s);if(e)o.current=s,e!==t.state.activeTriggerElement&&(n.activeTriggerElement=e);else{for(const[e,r]of t.context.triggerElements.entries())if(r===t.state.activeTriggerElement){n.activeTriggerId=e,n.activeTriggerElement=r,o.current=e;break}void 0===n.activeTriggerId&&(o.current===s?a=s:o.current=null)}}else o.current=null;if(!a&&!s&&1===e){const e=t.context.triggerElements.entries().next();if(!e.done){const[t,r]=e.value;n.activeTriggerId=t,n.activeTriggerElement=r,o.current=t}}void 0===n.triggerCount&&void 0===n.activeTriggerId&&void 0===n.activeTriggerElement||t.update(n),a&&r&&queueMicrotask(()=>{if(t.select("open")&&t.select("activeTriggerId")===a&&!t.context.triggerElements.getById(a)){const e=ls(ss);t.setOpen(!1,e),e.isCanceled||t.update({activeTriggerId:null,activeTriggerElement:null})}})},[i,t,s,a,c,r])}(k);const{forceUnmount:M}=function(e,t){const{mounted:n,setMounted:r,transitionStatus:o}=qs(e),i=t.useState("preventUnmountingOnClose"),s=!e&&i;t.useSyncedValues({mounted:n,transitionStatus:o,preventUnmountingOnClose:s});const a=zr(()=>{r(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),t.context.onOpenChangeComplete?.(!1)});return $i({enabled:n&&!e&&!s,open:e,ref:t.context.popupRef,onComplete(){e||a()}}),{forceUnmount:a,transitionStatus:o}}(C,k);e.useImperativeHandle(d,()=>({unmount:M,close:()=>k.setOpen(!1,ls("imperative-action"))}),[M,k]);const T=C||E;/*#__PURE__*/
35
+ return b(jl.Provider,{value:k,children:[u&&/*#__PURE__*/y(Ys,{handle:u,store:k}),T&&/*#__PURE__*/y(id,{store:k,parentContext:x?.context,isDrawer:f}),"function"==typeof r?r({payload:I}):r]})}("dialog",t)}var ld=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=ql(),c=fl(i);return a.useSyncedValueWithCleanup("titleElementId",c),Ti("h2",e,{ref:t,props:[{id:c},s]})}),dd=({open:e,onClose:t,title:n,description:r,onConfirm:o,confirmLabel:i="Confirm",cancelLabel:a="Cancel",finalFocusRef:c})=>{const l=s(Fc)??document.body;/* @__PURE__ */
36
+ return y(cd,{open:e,onOpenChange:(e,n)=>{e||"none"===n.reason||t()},children:/* @__PURE__ */b(Zl,{container:l,children:[/* @__PURE__ */y(Vl,{className:"mtx-dialog-backdrop",style:{zIndex:ma}}),/* @__PURE__ */b(Gl,{className:"mtx-dialog-popup",finalFocus:c,style:{...fa("panel"),zIndex:ma},children:[
37
+ /* @__PURE__ */y(ld,{className:"mtx-dialog-title",children:n}),null!=r&&/* @__PURE__ */y(Yl,{className:"mtx-dialog-description",children:r}),
38
+ /* @__PURE__ */b(Aa,{gap:"md",justify:"end",children:[/* @__PURE__ */y(Ma,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),t()},children:a}),/* @__PURE__ */y(Ma,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),o?.()},children:i})]})]})]})})},ud={sm:{width:"14px",height:"14px",borderWidth:"1.5px"},md:{width:"20px",height:"20px",borderWidth:"2px"},lg:{width:"24px",height:"24px",borderWidth:"2px"}};function pd({size:e="md",style:t,ref:n}){/* @__PURE__ */
39
+ return b("div",{ref:n,"data-size":e,role:"status",style:{display:"inline-flex",alignItems:"center",gap:"6px",...t},children:[/* @__PURE__ */y("div",{"aria-hidden":"true",className:"mtx-spinner-ring",style:ud[e]}),/* @__PURE__ */y("span",{className:"mtx-visually-hidden",children:"Loading"})]})}var hd=({isWaitingForUser:e})=>/* @__PURE__ */b(Aa,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */y(pd,{size:"sm"}),/* @__PURE__ */y(Ba,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),fd=({message:e,isLastMessage:t})=>{const{isTaskRunning:n}=Yc().state,r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return e.parts.length>0?/* @__PURE__ */b(Na,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */y(Ba,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap",marginBottom:"4px"},children:e.content},`part-${t}`):null:"progress"===e.type?/* @__PURE__ */y(Aa,{align:"start",gap:"md",children:/* @__PURE__ */y(Ba,{as:"span",size:"xs",weight:"medium",style:{flex:1,whiteSpace:"pre-wrap"},children:e.content})},`part-${t}`):null),(e.isPlaceholder&&!e.parts.some(e=>"text"===e.type)||o)&&/* @__PURE__ */y(hd,{isWaitingForUser:r})]}):e.isPlaceholder||n&&t&&("show"===e.mode||"do"===e.mode)?/* @__PURE__ */y(hd,{isWaitingForUser:r}):e.content?/* @__PURE__ */y(Ba,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap"},children:e.content}):/* @__PURE__ */y(Oa,{})},md={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},gd=({status:e})=>{const{name:t,opacity:n}=md[e];/* @__PURE__ */
40
+ return y(Pa,{name:t,size:14,style:{color:Uc(Vc().widget_accent_color,n),flexShrink:0}})},yd="8px 8px 0 0",bd=({label:e,children:t})=>/* @__PURE__ */y(Aa,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"#111827",borderRadius:yd,zIndex:10},children:/* @__PURE__ */b(Aa,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */y(Ba,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),vd=({stream:e})=>{const t=u(null),n=u(null),[r,o]=p(!1),[i,s]=p(!1),c=()=>{n.current?.catch(()=>{}),n.current=null};return a(()=>{if(t.current&&e){const r=t.current;o(!1),s(!1),c(),r.srcObject=e;const i=()=>{o(!0)},a=()=>{s(!0),o(!1)};r.addEventListener("loadedmetadata",i),r.addEventListener("error",a);const l=r.play();return n.current=l,l.then(()=>{o(!0)}).catch(e=>{e instanceof Error&&"AbortError"!==e.name&&(console.error("Error playing video stream:",e),s(!0)),n.current=null}),()=>{r.removeEventListener("loadedmetadata",i),r.removeEventListener("error",a)}}return()=>{c(),t.current&&(t.current.srcObject=null),o(!1),s(!1)}},[e]),e?/* @__PURE__ */b(Oa,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:yd,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&&!i&&/* @__PURE__ */y(bd,{label:"Loading stream...",children:/* @__PURE__ */y(pd,{size:"lg",style:{color:"white"}})}),i&&/* @__PURE__ */y(bd,{label:"Failed to load stream",children:/* @__PURE__ */y(Pa,{name:"alertCircle",size:32,style:{color:"#9ca3af"}})}),
41
+ /* @__PURE__ */y("video",{ref:t,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"auto",maxHeight:"192px",objectFit:"contain",borderRadius:yd,transition:"opacity 500ms",opacity:r?1:0,minHeight:"120px",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"}}),r&&!i&&/* @__PURE__ */b(Aa,{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__ */b(Aa,{position:"relative",align:"center",justify:"center",children:[/* @__PURE__ */y(Oa,{position:"absolute",rounded:"full",animate:"ping",style:{width:"8px",height:"8px",backgroundColor:"white",opacity:.75}}),/* @__PURE__ */y(Oa,{position:"relative",rounded:"full",style:{width:"6px",height:"6px",backgroundColor:"white"}})]}),/* @__PURE__ */y(Ba,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
42
+ /* @__PURE__ */y(Aa,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:yd,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */y(Oa,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */y(Ba,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]}):null},wd=({message:e,index:t,isLastMessage:n,onScreenAccessAllow:r,onScreenAccessDeny:o})=>{if(e.isSystemMessage)/* @__PURE__ */return y(Aa,{justify:"center",align:"center",children:/* @__PURE__ */y(Ba,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})},`message-${e.id}-${t}`);const i="user"===e.sender,s=i?"show"===e.mode||"do"===e.mode?"mousePointerClick":void 0:e.isScreenAccessRequest||"waiting-for-user"===e.placeholderState?"checkCircle":void 0;/* @__PURE__ */
43
+ return b(Na,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":i?"You said…":"Agent says…",animate:n?"fadeIn":void 0,children:[/* @__PURE__ */b(Aa,{align:"start",gap:"sm",width:"full",children:[
44
+ /* @__PURE__ */y(Aa,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!i&&/* @__PURE__ */y(Ca,{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%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"}})}),
45
+ /* @__PURE__ */b(Na,{grow:!0,position:"relative",rounded:"theme",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:i?"var(--primary)":void 0,color:i?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */y(vd,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */b(Aa,{align:"start",gap:"sm",children:[/* @__PURE__ */y(Aa,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */y(Pa,{name:s,size:13})}),/* @__PURE__ */y(Na,{grow:!0,children:/* @__PURE__ */y(fd,{message:e,isLastMessage:n})})]}):/* @__PURE__ */y(fd,{message:e,isLastMessage:n})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */b(Aa,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */y(Ma,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"Yes"}),/* @__PURE__ */y(Ma,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>o?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */y(Ba,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"Check HTML Instead"}),!i&&e.taskStatus&&/* @__PURE__ */y(Aa,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */y(gd,{status:e.taskStatus})})]}),
46
+ /* @__PURE__ */y(Aa,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */y(Ba,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:(a=e.timestamp,(a??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))})]},`message-${e.id}-${t}`);var a},xd={boxShadow:la.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Sd=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=Vc(),{state:o,actions:i}=Yc(),{messages:s}=o,c=r.isPreviewMode??!1,[l,h]=p(!1),[f,m]=p(!1),g=u(null),v=d(()=>({id:"welcome",content:r.widget_body,sender:"agent",timestamp:/* @__PURE__ */new Date,isPlaceholder:!1,parts:[]}),[r.widget_body]),w=d(()=>[v,...s],[v,s]),x=()=>{if(g.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=g.current;h(e>200);const r=Math.abs(t-e-n)<50;m(!r&&t>n)}};a(()=>{window.requestAnimationFrame(()=>{e.current&&(!c&&e.current.scrollIntoView({behavior:"auto"}),!c&&x())})},[s.length,c]);const S=s[s.length-1]?.content?.length??0;return a(()=>{const t=g.current;t&&!c&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[S,c,e]),/* @__PURE__ */b(Oa,{position:"relative",height:"full",children:[
47
+ /* @__PURE__ */b(Oa,{ref:g,onScroll:x,role:"log","aria-relevant":"additions",height:"full",overflowY:"auto",paddingX:"lg",paddingY:"sm",style:{backgroundColor:r.widget_background_color.includes("gradient")?"transparent":r.widget_background_color,backgroundImage:r.widget_background_color.includes("gradient")?r.widget_background_color:`linear-gradient(135deg, ${r.widget_background_color} 0%, ${r.widget_background_color} 100%)`,scrollbarColor:`${Uc(r.widget_border_color,.3)} ${Uc(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[w.map((e,r)=>/* @__PURE__ */y(wd,{message:e,index:r,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */y(Aa,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */y(Ma,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */y(Ba,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
48
+ /* @__PURE__ */y(Oa,{ref:e},"scroll-anchor")]},"message-list-container"),l&&/* @__PURE__ */y(Aa,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */y(La,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{g.current?.scrollTo({top:0,behavior:"smooth"})},style:xd,children:/* @__PURE__ */y(Pa,{name:"arrowUp",size:10,style:{color:r.widget_accent_color}})})}),f&&/* @__PURE__ */y(Aa,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */y(La,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{e.current&&!c&&e.current.scrollIntoView({behavior:"smooth"})},style:xd,children:/* @__PURE__ */y(Pa,{name:"arrowDown",size:10,style:{color:r.widget_accent_color}})})})]})},kd=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],Cd=({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,messageInputRef:r})=>{const o=Vc(),{state:i,actions:s}=Yc(),{currentMode:l,isTaskRunning:d,isAwaitingReply:h}=i,[f,m]=p(""),g=u(null),[v,w]=p(null),{isScreenSharing:x,isAwaitingScreenAccess:S,showScreenAccessDialog:k,handleScreenAccessDialogAllow:C,handleScreenAccessDialogDismiss:E,handleScreenAccessRequestAllow:I,handleScreenAccessRequestDeny:M,requestScreenAccess:T}=function({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,onAddMessage:r,onUpdateMessage:o,onRemoveMessage:i,onSendMessage:s,pendingMessage:l,setPendingMessage:d}){const[u,h]=p(!1),[f,m]=p(null),[g,y]=p(null),[b,v]=p(!1),w=Wl(u),x=Wl(f),S=Wl(e),k=e=>{e&&i?.(e),r(Ja("Stopped screenshare","show","user","stopped-sharing")),m(null)},C=Wl(k);a(()=>{const e=()=>{const e=null!==hc(),t=w.current,n=x.current;e!==t&&(w.current=e,h(e),S.current?.(e)),t&&!e&&n&&C.current(n)};e();const t=setInterval(e,1e3);return()=>clearInterval(t)},[]);const E=()=>{v(!0)},I=()=>{if(!l)return;const e=l;d(null),s(e.content,e.mode,e.alreadyAdded)},M=e=>{g&&(o(g,{screenShareStatus:e}),y(null))},T=async()=>{try{const t=await fc();h(!0),e?.(!0),M("allowed"),r(Ja("Started screenshare","show","user","started-screenshare"));const n=((e,t="show")=>Ka("screenshare","user","",{mode:t,videoStream:e}))(t,"show");m(n.id),r(n)}catch(t){console.error("Failed to start screen sharing:",t),h(!1),e?.(!1),M("denied")}I()},R=T,O=()=>{pc&&(pc.getTracks().forEach(e=>e.stop()),pc=null),h(!1),e?.(!1),k(f)};return c(t,()=>E),c(n,()=>O),{isScreenSharing:u,isAwaitingScreenAccess:null!==g,showScreenAccessDialog:b,handleScreenAccessDialogAllow:async()=>{v(!1),await T()},handleScreenAccessDialogDismiss:()=>{v(!1)},handleScreenAccessRequestAllow:R,handleScreenAccessRequestDeny:()=>{M("denied"),I()},requestScreenAccess:e=>{if(g)return;const t=(e=>Ka("screen-access-request","agent","Can I take a look at your screen?",{mode:e,isScreenAccessRequest:!0}))(e);y(t.id),r(t)}}}({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,onAddMessage:s.addMessage,onUpdateMessage:s.updateMessage,onRemoveMessage:s.removeMessage,onSendMessage:s.messageDispatch,pendingMessage:v,setPendingMessage:w}),R=S||h;/* @__PURE__ */
49
+ return b(Na,{height:"full",children:[k&&/* @__PURE__ */y(dd,{open:k,onClose:E,title:"Can I take a look at your screen?",description:"By allowing screen access, Marketrix can understand your current context to guide you better and complete tasks on your behalf.",onConfirm:C,confirmLabel:"Yes",cancelLabel:"No",finalFocusRef:r}),
50
+ /* @__PURE__ */y(Oa,{grow:!0,overflow:"hidden",paddingY:"2xs",style:{display:"flex",flexDirection:"column",minHeight:0},children:/* @__PURE__ */y(Qc,{label:"Chat",fallback:/* @__PURE__ */y(Ba,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */y(Sd,{messagesEndRef:g,onScreenAccessAllow:I,onScreenAccessDeny:M})})}),
51
+ /* @__PURE__ */y(Oa,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */y(Hl,{ref:r,value:f,onChange:m,onSubmit:()=>{if(!f.trim()||R)return;const e=f.trim();m(""),s.addMessage(Xa(e,l)),!1===o.use_screenshare||"show"!==l&&"do"!==l||x?s.messageDispatch(e,l,!0):(w({content:e,mode:l,alreadyAdded:!0}),T(l))},modes:kd.filter(({flag:e})=>o[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:Qa(e)})),activeMode:l,onModeChange:e=>{e!==l&&(s.addMessage(Ja(`Switched to ${Qa(e)} mode`,e,"agent","mode-change")),s.setMode(e))},disabled:R,taskRunning:d,onStop:()=>{gc.cleanup(),s.stopTask()}})})]})},Ed=[{id:"show-add-product",text:"Show me how to add a new product",type:"show"},{id:"show-login",text:"Show me how to login",type:"show"},{id:"do-login",text:"Do the login process for me",type:"do"},{id:"show-revenue",text:"Show me the revenue metrics",type:"show"},{id:"tell-conversion-rate",text:"What does my conversion rate mean and how can I improve it?",type:"tell"}],Id=({actions:e,onActionClick:t})=>{const n=Vc();return 0===e.length?null:/* @__PURE__ */y(Na,{gap:"sm",children:e.map((e,r)=>/* @__PURE__ */y(Ma,{elevation:"card",shape:"theme",size:"sm",variant:"chip",full:!0,onClick:n=>t(e,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */y(Ba,{as:"span",weight:"normal",leading:"tight",children:"show"===e.type?/* @__PURE__ */b(g,{children:["Show me ",e.text.replace(/^Show me\s*/i,"")]}):"do"===e.type?/* @__PURE__ */b(g,{children:["Do ",e.text.replace(/^Do\s*/i,"")]}):e.text})},`welcome-chip-${e.id}-${r}`))})},Md=({onNavigateToChat:e,onChipClick:t})=>{const n=Vc(),{messages:r}=Yc().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>({id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:e.chip_text,type:e.chip_mode})):Ed}(n);/* @__PURE__ */
52
+ return b(Na,{height:"full",overflow:"hidden",children:[/* @__PURE__ */b(Na,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */b(Oa,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */y(Ba,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */y(Ba,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */b(Na,{gap:"sm",children:[/* @__PURE__ */b(Ma,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */y(Pa,{name:"chat",size:16}),"Ask a question"]}),/* @__PURE__ */y(Id,{actions:o,onActionClick:async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)}})]})]}),r.length>0&&/* @__PURE__ */b(Oa,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px"},children:[
53
+ /* @__PURE__ */y(Ba,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
54
+ /* @__PURE__ */y(Ba,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1].content||"Message"}),
55
+ /* @__PURE__ */y(Ba,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation"})]})]})};function Td(e){const t=e.startsWith("top"),n=e.endsWith("left");return{position:"absolute",width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:t?"flex-start":"flex-end",justifyContent:n?"flex-start":"flex-end",cursor:$l[e].cursor,top:t?0:void 0,bottom:t?void 0:0,left:n?0:void 0,right:n?void 0:0}}var Rd=({onResizeStart:e})=>/* @__PURE__ */y(g,{children:Object.keys($l).map(t=>/* @__PURE__ */y("div",{role:"separator","aria-label":`Resize widget from ${t.replace("-"," ")}`,title:"Drag to resize",style:Td(t),onMouseDown:e(t)},t))}),Od=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],Ad=()=>/* @__PURE__ */y(Dl,{render:/* @__PURE__ */y(Aa,{align:"center",justify:"around",shrink:!1,border:"top"}),style:{height:48},children:Od.map(e=>/* @__PURE__ */b(bl,{value:e.id,render:/* @__PURE__ */y(Ma,{stacked:!0,variant:"tab"}),children:[
58
56
  /* @__PURE__ */y("span",{className:"mtx-tab-underline"}),
59
- /* @__PURE__ */y(bf,{as:"span",inheritColor:!0,"aria-hidden":"true",children:/* @__PURE__ */y(hf,{name:e.icon,size:20})}),
60
- /* @__PURE__ */y(bf,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))}),_y=()=>{const e=Mm(),{state:t,actions:n}=Om(),{isOpen:r,activeView:o}=t,s=e.isPreviewMode??!1,{widthPx:c,heightPx:l,onResizeStart:u,containerRef:h}=Tg(e.widget_width,e.widget_height,Ll(e),s),f=d(null),m="chat"===o?"forward":"back";!function(e,t,n){const r=d(!1),o=d(null),s=i(()=>{const t=e.current;if(!t)return;const r=n?.focusTargetRef?.current;if(r)return void r.focus({preventScroll:!0});const o=xg(t);o[0]&&o[0].focus({preventScroll:!0})},[e,n?.focusTargetRef]);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=wg(i)),r.current=!0,s();const a=e=>{if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const t=xg(i);if(0===t.length)return;const r=wg(i),o=r?t.indexOf(r):-1;-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),t[t.length-1].focus()):o===t.length-1&&(e.preventDefault(),t[0].focus()))};return document.addEventListener("keydown",a,!0),()=>document.removeEventListener("keydown",a,!0)},[t,e,s,n?.onEscape])}(h,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?f:void 0});const g=Nm(e.widget_position),[b,w]=p(!1),x=d(null),S=d(null);if(!r)return null;const k=e.widget_background_color.includes("gradient")?e.widget_background_color:`linear-gradient(135deg, ${e.widget_background_color} 0%, ${e.widget_background_color} 100%)`,{vertical:_,horizontal:E}=Pm(e.widget_position),C="chat"===o&&!1!==e.use_screenshare?()=>{b?S.current?.():x.current?.()}:void 0;/* @__PURE__ */
61
- return v(mf,{ref:h,position:s?"absolute":"fixed",rounded:"theme",border:!0,overflow:"hidden",style:{zIndex:e.widget_position_z_index,backgroundImage:k,transformOrigin:`${_} ${E}`,width:c,height:l,fontSize:"14px",...g,pointerEvents:"auto",scrollbarWidth:"thin",animation:"messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)",boxShadow:Lh.panel},children:[
62
- /* @__PURE__ */y(Mg,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:C&&/* @__PURE__ */v(ff,{variant:"ghost",size:"sm",label:b?"Stop screen sharing":"Start screen sharing",onClick:C,children:[b&&/* @__PURE__ */v("span",{className:"mtx-screenshare-dot",children:[/* @__PURE__ */y("span",{className:"mtx-screenshare-dot-ping"}),/* @__PURE__ */y("span",{className:"mtx-screenshare-dot-core"})]}),/* @__PURE__ */y(hf,{name:"screenShare",size:16})]})}),
63
- /* @__PURE__ */v(Jm,{value:o,onValueChange:e=>n.setActiveView(e),style:{display:"flex",flexDirection:"column",flex:"1 1 0%",minHeight:0},children:[/* @__PURE__ */v(lf,{grow:!0,overflow:"hidden",style:{display:"flex",flexDirection:"column",minHeight:0},children:[/* @__PURE__ */y(ig,{value:"home","data-view-transition":!0,"data-direction":m,style:{width:"100%",height:"100%"},children:/* @__PURE__ */y(by,{onNavigateToChat:()=>{n.setActiveView("chat")},onChipClick:e=>{n.addMessage(Tf(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */y(ig,{value:"chat","data-view-transition":!0,"data-direction":m,style:{width:"100%",height:"100%"},children:/* @__PURE__ */y(gy,{onScreenSharingChange:w,startScreenShareRef:x,stopScreenShareRef:S,messageInputRef:f})})]}),/* @__PURE__ */y(ky,{})]}),!s&&/* @__PURE__ */y(xy,{onResizeStart:u})]})},Ey=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=Om(),c=Pl.getInstance(),l=e.isPreviewMode??!1,u=Gs.safeParse(e);var d;d=i.isOpen,a(()=>{if(!d)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[d]);const[h,f]=p(e.widget_position??"bottom_right"),m=`marketrix_widget_position_${Ll(e)}`;a(()=>{const t=l?null:aa(m);(e=>Am.includes(e))(t)?f(t):f(e.widget_position??"bottom_right")},[l,m,e.widget_position]),a(()=>{if(i.isOpen||l||"default"!==e.widget_appearance||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,l,e.widget_appearance,e.widget_greeting_toast]);const g=u.success?null:Dl(u.error);a(()=>{g&&console.error(`Marketrix Widget: ${g}`)},[g]);if(g)return null;const b=!e.widget_enabled||!1===e.show_widget||"hidden"===e.widget_appearance;if(!l&&b)return null;const w=Math.max(e.widget_position_z_index??0,Zh),x={...e,widget_position:h,widget_position_z_index:w},S=i.isAwaitingReply||i.isTaskRunning,k={"--background":(_=Im(e)).color.background,"--foreground":_.color.foreground,"--card":_.color.background,"--card-foreground":_.color.foreground,"--primary":_.color.primary,"--foreground-muted":_.color.foregroundMuted,"--foreground-faint":_.color.foregroundFaint,"--primary-foreground":_.color.primaryForeground,"--primary-hover":_.color.primaryHover,"--secondary":_.color.secondary,"--secondary-foreground":_.color.secondaryForeground,"--secondary-bg":_.color.secondaryBg,"--secondary-hover":_.color.secondaryHover,"--border":_.color.border,"--ring":_.color.primary,"--radius":_.radius,"--duration-animation":_.motion.durationAnimation,"--duration-fade":_.motion.durationFade};var _;/* @__PURE__ */
64
- return y(Tm,{value:x,children:/* @__PURE__ */y(lf,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...k,...l&&{width:"100%",height:"100%"}},children:/* @__PURE__ */y(bm,{value:r,children:/* @__PURE__ */v(xf,{container:r,offsetBottom:"top"===Pm(h).vertical?20:90,children:[S&&/* @__PURE__ */y(lf,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${Em(x.widget_accent_color,.72)}, inset 0 0 46px 10px ${Em(x.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:Hh}}),
65
- /* @__PURE__ */y($m,{label:"Widget",children:/* @__PURE__ */y(_y,{})}),
66
- /* @__PURE__ */y(jm,{onPositionCommit:e=>{f(e),l||ca(m,e)}}),
67
- /* @__PURE__ */y(kf,{error:i.error,onClearError:()=>s.setError(void 0),...c.canReconnect()&&{onRetry:()=>{s.setError(void 0),c.reconnectNow()}},greeting:t&&!i.error?e.widget_greeting:void 0,greetingBody:e.widget_body,onGreetingDismiss:()=>n(!1)})]})})})})},Cy={mount:null},Iy=null,Ty=(e,t)=>{const n=e.attachShadow({mode:"closed"}),r=document.createElement("style");r.textContent=':root,:host{--background:oklch(100% 0 0);--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--border:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--foreground-muted:#1f293799;--foreground-faint:#1f293766;--primary-hover:#3b82f6d9;--secondary-bg:#6b728033;--secondary-hover:#6b72804d;--font-sans:"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--radius:.625rem;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--duration-animation:.3s;--duration-fade:.2s}*,:before,:after{box-sizing:border-box;border:0 solid var(--border);margin:0;padding:0}:host,[data-marketrix-widget]{font-family:var(--font-sans);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;line-height:1.5}[data-marketrix-widget] h1,[data-marketrix-widget] h2,[data-marketrix-widget] h3{font-size:inherit;font-weight:inherit}[data-marketrix-widget] img,[data-marketrix-widget] svg,[data-marketrix-widget] video,[data-marketrix-widget] canvas{vertical-align:middle;display:block}[data-marketrix-widget] img,[data-marketrix-widget] video{max-width:100%;height:auto}[data-marketrix-widget] button,[data-marketrix-widget] input,[data-marketrix-widget] textarea{font:inherit;color:inherit;background:0 0;border-radius:0}[data-marketrix-widget] button{appearance:button}[data-marketrix-widget] textarea{resize:vertical}[data-marketrix-widget] [hidden]{display:none!important}[data-marketrix-widget],[data-marketrix-widget] *{pointer-events:auto;transition:color .2s ease-in-out,background-color .2s ease-in-out,border-color .2s ease-in-out,opacity .2s ease-in-out,box-shadow .2s ease-in-out,transform .2s ease-in-out}[data-resizing=true],[data-resizing=true] *{transition:none!important}@media (prefers-reduced-motion:reduce){[data-marketrix-widget]{--duration-animation:0s!important;--duration-fade:0s!important}}.mtx-button{cursor:pointer;border:1px solid #0000;justify-content:center;align-items:center;gap:8px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}.mtx-button[data-size=sm]{min-height:28px;padding:4px 8px;font-size:.75rem}.mtx-button[data-size=md]{min-height:36px;padding:8px 16px;font-size:.875rem}.mtx-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-button[data-variant=primary]:hover{background:color-mix(in oklab, var(--primary) 90%, transparent)}.mtx-button[data-variant=secondary]{background:var(--secondary);color:var(--secondary-foreground)}.mtx-button[data-variant=secondary]:hover{background:color-mix(in oklab, var(--secondary) 80%, transparent)}.mtx-button[data-variant=ghost]{color:var(--foreground);border-color:var(--border);background:0 0}.mtx-button[data-variant=ghost]:hover{background:var(--border)}.mtx-button[data-variant=chip]{background:var(--secondary-bg);color:var(--foreground)}.mtx-button[data-variant=chip]:hover{background:var(--primary);color:var(--primary-foreground);border-color:var(--primary)}.mtx-button[data-variant=bare],.mtx-button[data-variant=tab]{background:0 0;border-color:#0000;min-height:0;padding:0}.mtx-button[data-variant=bare]{color:inherit}.mtx-button[data-variant=tab]{color:var(--foreground-muted);flex:1;min-width:0;height:100%;position:relative}.mtx-button[data-variant=tab]:hover{color:var(--foreground)}.mtx-button[data-variant=tab][data-selected]{color:var(--primary);font-weight:600}.mtx-button[data-stacked=true]{flex-direction:column;gap:2px}.mtx-button[data-full=true]{width:100%}.mtx-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon-button{cursor:pointer;border:none;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;transition:all .2s ease-in-out;display:inline-flex}.mtx-icon-button[data-size=xs]{width:20px;min-width:20px;height:20px}.mtx-icon-button[data-size=sm]{width:28px;min-width:28px;height:28px}.mtx-icon-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-icon-button[data-variant=primary]:hover{background:var(--primary-hover)}.mtx-icon-button[data-variant=secondary]{background:var(--secondary-bg);color:var(--foreground)}.mtx-icon-button[data-variant=secondary]:hover{background:var(--secondary-hover)}.mtx-icon-button[data-variant=ghost]{color:var(--foreground);opacity:.6;background:0 0}.mtx-icon-button[data-variant=ghost]:hover{opacity:1}.mtx-icon-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon{flex-shrink:0;display:inline-block}.mtx-avatar{flex-shrink:0}.mtx-spinner-ring{border-style:solid;border-color:#0000 currentColor currentColor;border-radius:9999px;flex-shrink:0;animation:1s linear infinite mtx-spin}.mtx-visually-hidden{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.mtx-composer:focus-within{border-color:var(--foreground-faint)}.mtx-composer-input{resize:none;width:100%;min-height:0;color:var(--foreground);background:0 0;border:none;padding-left:12px;padding-right:12px;font-size:.875rem;display:block}.mtx-composer-input::placeholder{color:var(--foreground-faint)}.mtx-composer-input:focus{outline:none}.mtx-composer-input:disabled{cursor:not-allowed;opacity:.5}.mtx-mode-chip{cursor:pointer;background:var(--secondary-bg);color:var(--foreground-muted);border:none;border-radius:9999px;align-items:center;gap:2px;padding:2px 8px;font-size:11px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-mode-chip[data-active=true]{background:var(--primary);color:var(--primary-foreground);box-shadow:var(--shadow-sm)}.mtx-toast-viewport{flex-direction:column;gap:8px;max-width:420px;display:flex;position:fixed;left:50%;transform:translate(-50%)}.mtx-toast{animation:mtx-fade-in var(--duration-animation) ease-out}.mtx-toast[data-ending-style]{opacity:0;transition:opacity var(--duration-animation) ease-out}.mtx-dialog-backdrop{animation:mtx-dialog-overlay-in var(--duration-fade) ease-out;background:#0003;position:fixed;inset:0}.mtx-dialog-popup{border-radius:var(--radius);background:var(--card);width:100%;max-width:24rem;max-height:85vh;animation:mtx-dialog-content-in var(--duration-animation) ease-out;flex-direction:column;padding:16px;display:flex;position:fixed;top:50%;left:50%;overflow:auto;transform:translate(-50%,-50%)}.mtx-dialog-title{color:var(--foreground);margin-bottom:4px;font-size:1rem;font-weight:600}.mtx-dialog-description{color:var(--foreground-muted);margin-bottom:16px;font-size:.875rem;line-height:1.625}.mtx-fab-anchor{position:fixed}.mtx-fab-anchor[data-preview=true]{position:absolute}.mtx-fab-anchor[data-animated=true]{transition:transform var(--duration-animation) ease-in-out}.mtx-fab{width:56px;height:56px;transition:all var(--duration-animation) ease-in-out;position:relative;overflow:visible}.mtx-fab[data-open=false]:hover{transform:scale(1.1)}.mtx-fab[data-open=true]{opacity:0;pointer-events:none;transform:scale(0)}.mtx-fab-trigger{z-index:10;width:56px;min-width:56px;height:56px;position:relative}.mtx-fab-center{justify-content:center;align-items:center;width:100%;height:100%;position:relative}.mtx-fab-badge{width:48px;height:48px;transition:transform .167s cubic-bezier(.33,0,0,1),opacity .167s cubic-bezier(.33,0,0,1),background-color .167s cubic-bezier(.33,0,0,1);animation:.25s ease-out forwards mtx-launcher-entrance;position:relative;overflow:hidden}.mtx-fab-badge:hover{transition-duration:.25s;transform:scale(1.1)}.mtx-fab-badge:active{transition-duration:.134s;transition-timing-function:cubic-bezier(.45,0,.2,1);transform:scale(.85)}.mtx-fab-icon-layer{justify-content:center;align-items:center;position:absolute;inset:0}.mtx-fab-avatar{z-index:10;object-fit:contain;width:100%;height:100%;position:relative}.mtx-fab-chevron{z-index:10;color:var(--foreground);pointer-events:none;position:relative}.mtx-fab-stop{z-index:20;text-transform:uppercase;letter-spacing:.025em;color:#fff;box-shadow:var(--shadow-lg);opacity:0;pointer-events:none;background:#111827;border:1px solid #ffffff40;border-radius:9999px;padding:4px 10px;font-size:11px;font-weight:600;transition:opacity .15s ease-in-out;position:absolute;top:50%;transform:translateY(-50%)}.mtx-fab-stop[data-side=left]{margin-left:8px;left:100%}.mtx-fab-stop[data-side=right]{margin-right:8px;right:100%}.mtx-fab:hover .mtx-fab-stop,.mtx-fab:focus-within .mtx-fab-stop{opacity:1;pointer-events:auto}.mtx-tab-underline{background:var(--primary);opacity:0;border-radius:9999px;height:2px;position:absolute;top:0;left:25%;right:25%}[data-selected]>.mtx-tab-underline{opacity:1}.mtx-screenshare-dot{width:6px;height:6px;display:inline-flex;position:absolute;top:2px;right:2px}.mtx-screenshare-dot-ping{opacity:.75;background:currentColor;border-radius:9999px;width:100%;height:100%;animation:1s cubic-bezier(0,0,.2,1) infinite mtx-ping;display:inline-flex;position:absolute}.mtx-screenshare-dot-core{background:currentColor;border-radius:9999px;width:6px;height:6px;display:inline-flex;position:relative}.marketrix-widget-button-processing-glow,.marketrix-widget-button-error-glow{pointer-events:none;filter:blur(14px);will-change:transform, opacity;border-radius:50%;width:140%;height:140%;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.marketrix-widget-button-processing-activity-ring,.marketrix-widget-button-error-activity-ring{pointer-events:none;z-index:0;position:absolute;inset:-3px;overflow:visible}.marketrix-widget-button-processing-activity-ring rect,.marketrix-widget-button-error-activity-ring rect{fill:none;stroke-width:2.5px;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:40 120;animation:1.9s cubic-bezier(.4,0,.2,1) infinite widget-activity-dash-travel}.marketrix-widget-button-processing-activity-ring rect{stroke:#31d06d;filter:drop-shadow(0 0 3px #31d06db3)}.marketrix-widget-button-error-activity-ring rect{stroke:#d0342c;filter:drop-shadow(0 0 3px #d0342cb3)}.marketrix-widget-button-processing-glow{animation:2s ease-in-out infinite widget-glow-green}.marketrix-widget-button-error-glow{animation:1.5s ease-in-out infinite widget-glow-red}[data-screen-edge-glow]{animation:1.6s ease-in-out infinite marketrix-screen-edge-pulse}[data-view-transition][data-direction=forward]{animation:.3s both viewSlideForward}[data-view-transition][data-direction=back]{animation:.3s both viewSlideBack}@keyframes mtx-spin{to{transform:rotate(360deg)}}@keyframes mtx-ping{75%,to{opacity:0;transform:scale(2)}}@keyframes mtx-pulse{50%{opacity:.5}}@keyframes mtx-dialog-overlay-in{0%{opacity:0}to{opacity:1}}@keyframes mtx-dialog-content-in{0%{opacity:0;scale:.96}to{opacity:1;scale:1}}@keyframes mtx-fade-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes mtx-launcher-entrance{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes marketrix-screen-edge-pulse{0%,to{opacity:.55}50%{opacity:1}}@keyframes widget-activity-dash-travel{0%{stroke-dashoffset:0;opacity:.5}18%{stroke-dashoffset:-112px;opacity:1}35%{stroke-dashoffset:-160px;opacity:.65}60%{stroke-dashoffset:-160px;opacity:.45}82%{stroke-dashoffset:-272px;opacity:1}to{stroke-dashoffset:-320px;opacity:.6}}@keyframes widget-glow-green{0%,to{opacity:.72;background:radial-gradient(circle,#31d06d00 38%,#31d06d61 58%,#31d06d3d 68%,#0000 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:1;background:radial-gradient(circle,#31d06d00 34%,#31d06d8c 56%,#31d06d54 68%,#0000 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes widget-glow-red{0%,to{opacity:.65;background:radial-gradient(circle,#d0342c00 38%,#d0342c57 58%,#d0342c38 68%,#0000 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:.95;background:radial-gradient(circle,#d0342c00 34%,#d0342c80 56%,#d0342c4d 68%,#0000 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes viewSlideForward{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes viewSlideBack{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}',n.appendChild(r);const o=document.createElement("div");return o.id=t,n.appendChild(o),{shadowRoot:n,mountEl:o}},My=e=>{const t=e??document.body,n=document.createElement("div");n.className="marketrix-widget-container",n.style.pointerEvents="auto",e&&Object.assign(n.style,{width:"100%",height:"100%",position:"relative",overflow:"visible"}),t.appendChild(n);const{shadowRoot:r,mountEl:o}=Ty(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},Oy=(e,n,r=!1)=>{const o=f(e);return o.render(/* @__PURE__ */y(t.StrictMode,{children:/* @__PURE__ */y(Sm,{previewMode:r,children:/* @__PURE__ */y(Ey,{config:n})})})),o},Ry=()=>null!==Cy.mount,zy=()=>Cy.mount?.config??null,Ay=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;Py();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=Ty(r,"marketrix-widget-notice-root");(Iy=f(o)).render(/* @__PURE__ */y(t.StrictMode,{children:/* @__PURE__ */y(xf,{container:o,children:/* @__PURE__ */y(kf,{error:"error"===n?e:void 0,onClearError:Py,greeting:"error"===n?void 0:e,onGreetingDismiss:Py})})}))},Py=()=>{Iy?.unmount(),Iy=null,document.getElementById("marketrix-widget-notice-container")?.remove()},Ny=e=>{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__mtx?.state)return;const t=document.querySelectorAll("script[mtx-id]"),n=t[t.length-1];if(!(n&&(r=n,r instanceof HTMLScriptElement)))return;var r;const o=n.getAttribute("mtx-id"),i=n.getAttribute("mtx-key"),s=n.getAttribute("mtx-api-host");if(!o||!i||!s){if(Ry())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void Ay("Please configure mtx-id, mtx-key and mtx-api-host","error")}const a={mtxId:o,mtxKey:i,mtxApiHost:s};"false"===n.getAttribute("mtx-use-screenshare")&&(a.use_screenshare=!1),e(a).catch(e=>console.error("[AutoInit] Failed to initialize widget:",e))},Dy=null,$y=0,Ly=null;function Fy(e,t,n=!1){const{container:r,mountEl:o}=My(t),i=Oy(o,e,n);Cy.mount={instance:i,config:e,container:r,host:t,previewMode:n}}async function jy(e,t,n){let r;window.__mtx={state:"initializing"},Ay("Loading widget settings...");try{(e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==na&&(na=e,ra=ta(e))})(e.mtxApiHost??""),r=await Ul(e)}catch(ko){if(n!==$y)return;return console.error("Marketrix Widget initialization failed:",ko),Ay(ko instanceof Error?ko.message:"Failed to initialize widget","error"),void(window.__mtx=void 0)}n===$y&&(Py(),ua.setConfig(r),Fy(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await da.getOrCreateChatId();if(n!==$y)return;const t=new Nl(e,r.mtxApp);Ly=t,await t.start(),n!==$y&&(t.stop(),Ly===t&&(Ly=null))}catch(ko){n===$y&&console.error("Failed to start session recording:",ko)}})())}var Uy=(e,t)=>{if(Dy)return Dy;if(window.__mtx?.state)return Promise.resolve();if(Ry())return console.warn("Marketrix Widget: already initialized"),Promise.resolve();const n=jy(e,t,++$y);return Dy=n,n.then(()=>{Dy===n&&(Dy=null)},()=>{Dy===n&&(Dy=null)}),n},Wy=()=>{$y++,Pl.getInstance().disconnect(),Ly?.stop(),Ly=null;const e=Cy.mount;Cy.mount=null,e&&(e.instance.unmount(),e.container.remove()),Dy=null,window.__mtx=void 0,Py()},By=async e=>{const t=Cy.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};Wy(),o?Fy(i,r,!0):await Uy(i,r)},Hy=({settings:e,container:t})=>{const n=d(null),r=d(null),o=d(null);return a(()=>{const i=t??n?.current?.parentElement??document.body;if(!(i&&(s=i,s instanceof HTMLElement)))return void console.error("MarketrixWidget: Invalid container");var s;const{container:a,mountEl:c}=My(i);return o.current=a,r.current=Oy(c,{...$l(e),isPreviewMode:!0},!0),()=>{r.current&&(r.current.unmount(),r.current=null),o.current&&(o.current.remove(),o.current=null)}},[e,t]),t?null:/* @__PURE__ */y("div",{ref:n,style:{width:"100%",height:"100%",position:"relative"}})},Zy=async e=>{const t=e.container;if(void 0!==e.settings){Wy();const{settings:n,container:r,...o}=e;Fy({...$l(n,o),isPreviewMode:!0},t,!0)}else{if(void 0===e.mtxId||void 0===e.mtxKey)throw new Error("Invalid configuration: provide either settings (preview) or mtxId+mtxKey (production)");{const{container:n,...r}=e;await Uy(r,t)}}};"undefined"!=typeof window&&setTimeout(()=>{try{Ny(Uy)}catch(ko){console.error("Marketrix Widget: Auto-init registration failed",ko)}},0);var qy={MarketrixWidget:Hy,mountWidget:Zy,initWidget:Uy,unmountWidget:Wy,updateMarketrixConfig:By,getCurrentConfig:zy};export{Hy as MarketrixWidget,qy as default,zy as getCurrentConfig,Uy as initWidget,Zy as mountWidget,Wy as unmountWidget,By as updateMarketrixConfig};
57
+ /* @__PURE__ */y(Ba,{as:"span",inheritColor:!0,"aria-hidden":"true",children:/* @__PURE__ */y(Pa,{name:e.icon,size:20})}),
58
+ /* @__PURE__ */y(Ba,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))}),_d=()=>{const e=Vc(),{state:t,actions:n}=Yc(),{isOpen:r,activeView:o}=t,s=e.isPreviewMode??!1,{widthPx:c,heightPx:l,onResizeStart:d,containerRef:h}=function(e,t,n,r){const o=`marketrix_widget_size_${n}`,s=u(null),[a,c]=p(()=>function(e){try{const t=JSON.parse(Oe(e)??"null");return"number"!=typeof t?.width||"number"!=typeof t?.height?null:Fl({width:t.width,height:t.height})}catch(t){return console.warn("[useResize] Ignoring an unparseable stored size:",t),null}}(o)??Fl({width:zl(e,360),height:zl(t,450)})),l=u(a);l.current=a;const d=i(e=>t=>{if(t.preventDefault(),t.stopPropagation(),r)return;const n=t.clientX,i=t.clientY,a=l.current.width,d=l.current.height,{growX:u,growY:p,cursor:h}=$l[e];s.current&&(s.current.dataset.resizing="true");const f=e=>{const t=Fl({width:a+(e.clientX-n)*u,height:d+(e.clientY-i)*p});l.current=t,s.current&&(s.current.style.width=`${t.width}px`,s.current.style.height=`${t.height}px`)},m=()=>{if(document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",m),document.body.style.cursor="",document.body.style.userSelect="",s.current&&delete s.current.dataset.resizing,c({...l.current}),!r){const{width:e,height:t}=l.current;Ae(o,JSON.stringify({width:e,height:t}))}};document.body.style.cursor=h,document.body.style.userSelect="none",document.addEventListener("mousemove",f),document.addEventListener("mouseup",m)},[r,o]);return{widthPx:`${a.width}px`,heightPx:`${a.height}px`,onResizeStart:d,containerRef:s}}(e.widget_width,e.widget_height,gr(e),s),f=u(null),m="chat"===o?"forward":"back";!function(e,t,n){const r=u(!1),o=u(null),s=i(()=>{const t=e.current;if(!t)return;const r=n?.focusTargetRef?.current;if(r)return void r.focus({preventScroll:!0});const o=Ll(t);o[0]&&o[0].focus({preventScroll:!0})},[e,n?.focusTargetRef]);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=Pl(i)),r.current=!0,s();const a=e=>{if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const t=Ll(i);if(0===t.length)return;const r=Pl(i),o=r?t.indexOf(r):-1;-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),t[t.length-1].focus()):o===t.length-1&&(e.preventDefault(),t[0].focus()))};return document.addEventListener("keydown",a,!0),()=>document.removeEventListener("keydown",a,!0)},[t,e,s,n?.onEscape])}(h,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?f:void 0});const g=Jc(e.widget_position),[v,w]=p(!1),x=u(null),S=u(null);if(!r)return null;const k=e.widget_background_color.includes("gradient")?e.widget_background_color:`linear-gradient(135deg, ${e.widget_background_color} 0%, ${e.widget_background_color} 100%)`,{vertical:C,horizontal:E}=Gc(e.widget_position),I="chat"===o&&!1!==e.use_screenshare?()=>{v?S.current?.():x.current?.()}:void 0;/* @__PURE__ */
59
+ return b(Na,{ref:h,position:s?"absolute":"fixed",rounded:"theme",border:!0,overflow:"hidden",style:{zIndex:e.widget_position_z_index,backgroundImage:k,transformOrigin:`${C} ${E}`,width:c,height:l,fontSize:"14px",...g,pointerEvents:"auto",scrollbarWidth:"thin",animation:"messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)",boxShadow:la.panel},children:[
60
+ /* @__PURE__ */y(Bl,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:I&&/* @__PURE__ */b(La,{variant:"ghost",size:"sm",label:v?"Stop screen sharing":"Start screen sharing",onClick:I,children:[v&&/* @__PURE__ */b("span",{className:"mtx-screenshare-dot",children:[/* @__PURE__ */y("span",{className:"mtx-screenshare-dot-ping"}),/* @__PURE__ */y("span",{className:"mtx-screenshare-dot-core"})]}),/* @__PURE__ */y(Pa,{name:"screenShare",size:16})]})}),
61
+ /* @__PURE__ */b(ul,{value:o,onValueChange:e=>n.setActiveView(e),style:{display:"flex",flexDirection:"column",flex:"1 1 0%",minHeight:0},children:[/* @__PURE__ */b(Oa,{grow:!0,overflow:"hidden",style:{display:"flex",flexDirection:"column",minHeight:0},children:[/* @__PURE__ */y(wl,{value:"home","data-view-transition":!0,"data-direction":m,style:{width:"100%",height:"100%"},children:/* @__PURE__ */y(Md,{onNavigateToChat:()=>{n.setActiveView("chat")},onChipClick:e=>{n.addMessage(Xa(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */y(wl,{value:"chat","data-view-transition":!0,"data-direction":m,style:{width:"100%",height:"100%"},children:/* @__PURE__ */y(Cd,{onScreenSharingChange:w,startScreenShareRef:x,stopScreenShareRef:S,messageInputRef:f})})]}),/* @__PURE__ */y(Ad,{})]}),!s&&/* @__PURE__ */y(Rd,{onResizeStart:d})]})},Dd=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=Yc(),c=sr.getInstance(),l=e.isPreviewMode??!1,d=hr(e);var u;u=i.isOpen,a(()=>{if(!u)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[u]);const[h,f]=p(e.widget_position??"bottom_right"),m=`marketrix_widget_position_${gr(e)}`;a(()=>{const t=l?null:Oe(m);(e=>Xc.includes(e))(t)?f(t):f(e.widget_position??"bottom_right")},[l,m,e.widget_position]),a(()=>{if(i.isOpen||l||"default"!==e.widget_appearance||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,l,e.widget_appearance,e.widget_greeting_toast]);const g=d.invalidFields?fr(d.invalidFields):null;if(a(()=>{g&&console.error(`Marketrix Widget: ${g}`)},[g]),g)return null;const v=!e.widget_enabled||!1===e.show_widget||"hidden"===e.widget_appearance;if(!l&&v)return null;const w=Math.max(e.widget_position_z_index??0,2147483002),x={...e,widget_position:h,widget_position_z_index:w},S=i.isAwaitingReply||i.isTaskRunning,k={"--background":(C=jc(e)).color.background,"--foreground":C.color.foreground,"--card":C.color.background,"--card-foreground":C.color.foreground,"--primary":C.color.primary,"--foreground-muted":C.color.foregroundMuted,"--foreground-faint":C.color.foregroundFaint,"--primary-foreground":C.color.primaryForeground,"--primary-hover":C.color.primaryHover,"--secondary":C.color.secondary,"--secondary-foreground":C.color.secondaryForeground,"--secondary-bg":C.color.secondaryBg,"--secondary-hover":C.color.secondaryHover,"--border":C.color.border,"--ring":C.color.primary,"--radius":C.radius,"--duration-animation":C.motion.durationAnimation,"--duration-fade":C.motion.durationFade};var C;/* @__PURE__ */
62
+ return y(qc,{value:x,children:/* @__PURE__ */y(Oa,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...k,...l&&{width:"100%",height:"100%"}},children:/* @__PURE__ */y(Fc,{value:r,children:/* @__PURE__ */b(Ua,{container:r,offsetBottom:"top"===Gc(h).vertical?20:90,children:[S&&/* @__PURE__ */y(Oa,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${Uc(x.widget_accent_color,.72)}, inset 0 0 46px 10px ${Uc(x.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:2147483001}}),
63
+ /* @__PURE__ */y(Qc,{label:"Widget",children:/* @__PURE__ */y(_d,{})}),
64
+ /* @__PURE__ */y(tl,{onPositionCommit:e=>{f(e),l||Ae(m,e)}}),
65
+ /* @__PURE__ */y(ja,{error:i.error,onClearError:()=>s.setError(void 0),...c.canReconnect()&&{onRetry:()=>{s.setError(void 0),c.reconnectNow()}},greeting:t&&!i.error?e.widget_greeting:void 0,greetingBody:e.widget_body,onGreetingDismiss:()=>n(!1)})]})})})})},Pd={mount:null},Ld=null,Nd=(e,t)=>{const n=e.attachShadow({mode:"closed"}),r=document.createElement("style");r.textContent=':root,:host{--background:oklch(100% 0 0);--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--border:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--foreground-muted:#1f293799;--foreground-faint:#1f293766;--primary-hover:#3b82f6d9;--secondary-bg:#6b728033;--secondary-hover:#6b72804d;--font-sans:"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--radius:.625rem;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--duration-animation:.3s;--duration-fade:.2s}*,:before,:after{box-sizing:border-box;border:0 solid var(--border);margin:0;padding:0}:host,[data-marketrix-widget]{font-family:var(--font-sans);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;line-height:1.5}[data-marketrix-widget] h1,[data-marketrix-widget] h2,[data-marketrix-widget] h3{font-size:inherit;font-weight:inherit}[data-marketrix-widget] img,[data-marketrix-widget] svg,[data-marketrix-widget] video,[data-marketrix-widget] canvas{vertical-align:middle;display:block}[data-marketrix-widget] img,[data-marketrix-widget] video{max-width:100%;height:auto}[data-marketrix-widget] button,[data-marketrix-widget] input,[data-marketrix-widget] textarea{font:inherit;color:inherit;background:0 0;border-radius:0}[data-marketrix-widget] button{appearance:button}[data-marketrix-widget] textarea{resize:vertical}[data-marketrix-widget] [hidden]{display:none!important}[data-marketrix-widget],[data-marketrix-widget] *{pointer-events:auto;transition:color .2s ease-in-out,background-color .2s ease-in-out,border-color .2s ease-in-out,opacity .2s ease-in-out,box-shadow .2s ease-in-out,transform .2s ease-in-out}[data-resizing=true],[data-resizing=true] *{transition:none!important}@media (prefers-reduced-motion:reduce){[data-marketrix-widget]{--duration-animation:0s!important;--duration-fade:0s!important}}.mtx-button{cursor:pointer;border:1px solid #0000;justify-content:center;align-items:center;gap:8px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}.mtx-button[data-size=sm]{min-height:28px;padding:4px 8px;font-size:.75rem}.mtx-button[data-size=md]{min-height:36px;padding:8px 16px;font-size:.875rem}.mtx-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-button[data-variant=primary]:hover{background:color-mix(in oklab, var(--primary) 90%, transparent)}.mtx-button[data-variant=secondary]{background:var(--secondary);color:var(--secondary-foreground)}.mtx-button[data-variant=secondary]:hover{background:color-mix(in oklab, var(--secondary) 80%, transparent)}.mtx-button[data-variant=ghost]{color:var(--foreground);border-color:var(--border);background:0 0}.mtx-button[data-variant=ghost]:hover{background:var(--border)}.mtx-button[data-variant=chip]{background:var(--secondary-bg);color:var(--foreground)}.mtx-button[data-variant=chip]:hover{background:var(--primary);color:var(--primary-foreground);border-color:var(--primary)}.mtx-button[data-variant=bare],.mtx-button[data-variant=tab]{background:0 0;border-color:#0000;min-height:0;padding:0}.mtx-button[data-variant=bare]{color:inherit}.mtx-button[data-variant=tab]{color:var(--foreground-muted);flex:1;min-width:0;height:100%;position:relative}.mtx-button[data-variant=tab]:hover{color:var(--foreground)}.mtx-button[data-variant=tab][data-selected]{color:var(--primary);font-weight:600}.mtx-button[data-stacked=true]{flex-direction:column;gap:2px}.mtx-button[data-full=true]{width:100%}.mtx-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon-button{cursor:pointer;border:none;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;transition:all .2s ease-in-out;display:inline-flex}.mtx-icon-button[data-size=xs]{width:20px;min-width:20px;height:20px}.mtx-icon-button[data-size=sm]{width:28px;min-width:28px;height:28px}.mtx-icon-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-icon-button[data-variant=primary]:hover{background:var(--primary-hover)}.mtx-icon-button[data-variant=secondary]{background:var(--secondary-bg);color:var(--foreground)}.mtx-icon-button[data-variant=secondary]:hover{background:var(--secondary-hover)}.mtx-icon-button[data-variant=ghost]{color:var(--foreground);opacity:.6;background:0 0}.mtx-icon-button[data-variant=ghost]:hover{opacity:1}.mtx-icon-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon{flex-shrink:0;display:inline-block}.mtx-avatar{flex-shrink:0}.mtx-spinner-ring{border-style:solid;border-color:#0000 currentColor currentColor;border-radius:9999px;flex-shrink:0;animation:1s linear infinite mtx-spin}.mtx-visually-hidden{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.mtx-composer:focus-within{border-color:var(--foreground-faint)}.mtx-composer-input{resize:none;width:100%;min-height:0;color:var(--foreground);background:0 0;border:none;padding-left:12px;padding-right:12px;font-size:.875rem;display:block}.mtx-composer-input::placeholder{color:var(--foreground-faint)}.mtx-composer-input:focus{outline:none}.mtx-composer-input:disabled{cursor:not-allowed;opacity:.5}.mtx-mode-chip{cursor:pointer;background:var(--secondary-bg);color:var(--foreground-muted);border:none;border-radius:9999px;align-items:center;gap:2px;padding:2px 8px;font-size:11px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-mode-chip[data-active=true]{background:var(--primary);color:var(--primary-foreground);box-shadow:var(--shadow-sm)}.mtx-toast-viewport{flex-direction:column;gap:8px;max-width:420px;display:flex;position:fixed;left:50%;transform:translate(-50%)}.mtx-toast{animation:mtx-fade-in var(--duration-animation) ease-out}.mtx-toast[data-ending-style]{opacity:0;transition:opacity var(--duration-animation) ease-out}.mtx-dialog-backdrop{animation:mtx-dialog-overlay-in var(--duration-fade) ease-out;background:#0003;position:fixed;inset:0}.mtx-dialog-popup{border-radius:var(--radius);background:var(--card);width:100%;max-width:24rem;max-height:85vh;animation:mtx-dialog-content-in var(--duration-animation) ease-out;flex-direction:column;padding:16px;display:flex;position:fixed;top:50%;left:50%;overflow:auto;transform:translate(-50%,-50%)}.mtx-dialog-title{color:var(--foreground);margin-bottom:4px;font-size:1rem;font-weight:600}.mtx-dialog-description{color:var(--foreground-muted);margin-bottom:16px;font-size:.875rem;line-height:1.625}.mtx-fab-anchor{position:fixed}.mtx-fab-anchor[data-preview=true]{position:absolute}.mtx-fab-anchor[data-animated=true]{transition:transform var(--duration-animation) ease-in-out}.mtx-fab{width:56px;height:56px;transition:all var(--duration-animation) ease-in-out;position:relative;overflow:visible}.mtx-fab[data-open=false]:hover{transform:scale(1.1)}.mtx-fab[data-open=true]{opacity:0;pointer-events:none;transform:scale(0)}.mtx-fab-trigger{z-index:10;width:56px;min-width:56px;height:56px;position:relative}.mtx-fab-center{justify-content:center;align-items:center;width:100%;height:100%;position:relative}.mtx-fab-badge{width:48px;height:48px;transition:transform .167s cubic-bezier(.33,0,0,1),opacity .167s cubic-bezier(.33,0,0,1),background-color .167s cubic-bezier(.33,0,0,1);animation:.25s ease-out forwards mtx-launcher-entrance;position:relative;overflow:hidden}.mtx-fab-badge:hover{transition-duration:.25s;transform:scale(1.1)}.mtx-fab-badge:active{transition-duration:.134s;transition-timing-function:cubic-bezier(.45,0,.2,1);transform:scale(.85)}.mtx-fab-icon-layer{justify-content:center;align-items:center;position:absolute;inset:0}.mtx-fab-avatar{z-index:10;object-fit:contain;width:100%;height:100%;position:relative}.mtx-fab-chevron{z-index:10;color:var(--foreground);pointer-events:none;position:relative}.mtx-fab-stop{z-index:20;text-transform:uppercase;letter-spacing:.025em;color:#fff;box-shadow:var(--shadow-lg);opacity:0;pointer-events:none;background:#111827;border:1px solid #ffffff40;border-radius:9999px;padding:4px 10px;font-size:11px;font-weight:600;transition:opacity .15s ease-in-out;position:absolute;top:50%;transform:translateY(-50%)}.mtx-fab-stop[data-side=left]{margin-left:8px;left:100%}.mtx-fab-stop[data-side=right]{margin-right:8px;right:100%}.mtx-fab:hover .mtx-fab-stop,.mtx-fab:focus-within .mtx-fab-stop{opacity:1;pointer-events:auto}.mtx-tab-underline{background:var(--primary);opacity:0;border-radius:9999px;height:2px;position:absolute;top:0;left:25%;right:25%}[data-selected]>.mtx-tab-underline{opacity:1}.mtx-screenshare-dot{width:6px;height:6px;display:inline-flex;position:absolute;top:2px;right:2px}.mtx-screenshare-dot-ping{opacity:.75;background:currentColor;border-radius:9999px;width:100%;height:100%;animation:1s cubic-bezier(0,0,.2,1) infinite mtx-ping;display:inline-flex;position:absolute}.mtx-screenshare-dot-core{background:currentColor;border-radius:9999px;width:6px;height:6px;display:inline-flex;position:relative}.marketrix-widget-button-processing-glow,.marketrix-widget-button-error-glow{pointer-events:none;filter:blur(14px);will-change:transform, opacity;border-radius:50%;width:140%;height:140%;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.marketrix-widget-button-processing-activity-ring,.marketrix-widget-button-error-activity-ring{pointer-events:none;z-index:0;position:absolute;inset:-3px;overflow:visible}.marketrix-widget-button-processing-activity-ring rect,.marketrix-widget-button-error-activity-ring rect{fill:none;stroke-width:2.5px;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:40 120;animation:1.9s cubic-bezier(.4,0,.2,1) infinite widget-activity-dash-travel}.marketrix-widget-button-processing-activity-ring rect{stroke:#31d06d;filter:drop-shadow(0 0 3px #31d06db3)}.marketrix-widget-button-error-activity-ring rect{stroke:#d0342c;filter:drop-shadow(0 0 3px #d0342cb3)}.marketrix-widget-button-processing-glow{animation:2s ease-in-out infinite widget-glow-green}.marketrix-widget-button-error-glow{animation:1.5s ease-in-out infinite widget-glow-red}[data-screen-edge-glow]{animation:1.6s ease-in-out infinite marketrix-screen-edge-pulse}[data-view-transition][data-direction=forward]{animation:.3s both viewSlideForward}[data-view-transition][data-direction=back]{animation:.3s both viewSlideBack}@keyframes mtx-spin{to{transform:rotate(360deg)}}@keyframes mtx-ping{75%,to{opacity:0;transform:scale(2)}}@keyframes mtx-pulse{50%{opacity:.5}}@keyframes mtx-dialog-overlay-in{0%{opacity:0}to{opacity:1}}@keyframes mtx-dialog-content-in{0%{opacity:0;scale:.96}to{opacity:1;scale:1}}@keyframes mtx-fade-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes mtx-launcher-entrance{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes marketrix-screen-edge-pulse{0%,to{opacity:.55}50%{opacity:1}}@keyframes widget-activity-dash-travel{0%{stroke-dashoffset:0;opacity:.5}18%{stroke-dashoffset:-112px;opacity:1}35%{stroke-dashoffset:-160px;opacity:.65}60%{stroke-dashoffset:-160px;opacity:.45}82%{stroke-dashoffset:-272px;opacity:1}to{stroke-dashoffset:-320px;opacity:.6}}@keyframes widget-glow-green{0%,to{opacity:.72;background:radial-gradient(circle,#31d06d00 38%,#31d06d61 58%,#31d06d3d 68%,#0000 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:1;background:radial-gradient(circle,#31d06d00 34%,#31d06d8c 56%,#31d06d54 68%,#0000 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes widget-glow-red{0%,to{opacity:.65;background:radial-gradient(circle,#d0342c00 38%,#d0342c57 58%,#d0342c38 68%,#0000 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:.95;background:radial-gradient(circle,#d0342c00 34%,#d0342c80 56%,#d0342c4d 68%,#0000 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes viewSlideForward{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes viewSlideBack{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}',n.appendChild(r);const o=document.createElement("div");return o.id=t,n.appendChild(o),{shadowRoot:n,mountEl:o}},Fd=e=>{const t=e??document.body,n=document.createElement("div");n.className="marketrix-widget-container",n.style.pointerEvents="auto",e&&Object.assign(n.style,{width:"100%",height:"100%",position:"relative",overflow:"visible"}),t.appendChild(n);const{shadowRoot:r,mountEl:o}=Nd(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},zd=(e,n,r=!1)=>{const o=f(e);return o.render(/* @__PURE__ */y(t.StrictMode,{children:/* @__PURE__ */y(Bc,{previewMode:r,children:/* @__PURE__ */y(Dd,{config:n})})})),o},$d=()=>null!==Pd.mount,Bd=()=>Pd.mount?.config??null,Wd=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;Ud();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=Nd(r,"marketrix-widget-notice-root");(Ld=f(o)).render(/* @__PURE__ */y(t.StrictMode,{children:/* @__PURE__ */y(Ua,{container:o,children:/* @__PURE__ */y(ja,{error:"error"===n?e:void 0,onClearError:Ud,greeting:"error"===n?void 0:e,onGreetingDismiss:Ud})})}))},Ud=()=>{Ld?.unmount(),Ld=null,document.getElementById("marketrix-widget-notice-container")?.remove()},Hd=null,jd=0,qd=null;function Vd(e,t,n=!1){const{container:r,mountEl:o}=Fd(t),i=zd(o,e,n);Pd.mount={instance:i,config:e,container:r,host:t,previewMode:n}}var Yd=(e,t)=>{if(Hd)return Hd;if(window.__mtx?.state)return Promise.resolve();if($d())return console.warn("Marketrix Widget: already initialized"),Promise.resolve();const n=async function(e,t,n){let r;window.__mtx={state:"initializing"},Wd("Loading widget settings...");try{(e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==Ee&&(Ee=e,Ie=Ce(e))})(e.mtxApiHost??""),r=await async function(e){const{mtxId:t,mtxKey:n}=e;if(!t||!n)throw new Error("Please provide mtxId + mtxKey");let r;try{({items:r}=await Me.widgetSearch({marketrix_id:t,marketrix_key:n}))}catch(a){throw function(e,t){const n=yr(e);return n.includes("Failed to fetch")||n.includes("ERR_CONNECTION_REFUSED")||n.includes("NetworkError")||n.includes("Network request failed")?br(`Cannot connect to API server. Please ensure the API server is running at ${t.mtxApiHost||"configured API server"}. Error: ${n}`,e):br(`Widget validation failed: ${n}`,e)}(a,e)}if(!r.length)throw new Error("Widget not found or invalid credentials");const o=r.find(e=>"active"===e.status);if(!o){const e=r.map(e=>e.status).join(", ");throw new Error(`Found widget(s) but none are active. Current status(es): ${e}. Please activate the widget in the dashboard.`)}if(!o.application_id)throw new Error("Widget missing application_id");try{await Me.applicationGet({application_id:o.application_id})}catch(a){throw br(`Failed to validate application: ${yr(a)}`,a)}let i;try{i=await Me.widgetDefaultGet({type:"widget"})}catch(a){throw br(`Failed to fetch widget settings from API: ${yr(a)}`,a)}const s=hr({...i,...o.settings});if(s.invalidFields)throw new Error(fr(s.invalidFields));return{...mr(s.settings,e),mtxId:t,mtxKey:n,mtxApp:o.application_id}}(e)}catch(o){if(n!==jd)return;return console.error("Marketrix Widget initialization failed:",o),Wd(o instanceof Error?o.message:"Failed to initialize widget","error"),void(window.__mtx=void 0)}n===jd&&(Ud(),De.setConfig(r),Vd(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await Pe.getOrCreateChatId();if(n!==jd)return;const t=new ar(e,r.mtxApp);qd=t,await t.start(),n!==jd&&(t.stop(),qd===t&&(qd=null))}catch(o){n===jd&&console.error("Failed to start session recording:",o)}})())}(e,t,++jd);return Hd=n,n.then(()=>{Hd===n&&(Hd=null)},()=>{Hd===n&&(Hd=null)}),n},Kd=()=>{jd++,sr.getInstance().disconnect(),qd?.stop(),qd=null;const e=Pd.mount;Pd.mount=null,e&&(e.instance.unmount(),e.container.remove()),Hd=null,window.__mtx=void 0,Ud()},Xd=async e=>{const t=Pd.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};Kd(),o?Vd(i,r,!0):await Yd(i,r)},Gd=({settings:e,container:t})=>{const n=u(null),r=u(null),o=u(null);return a(()=>{const i=t??n?.current?.parentElement??document.body;if(!(i&&(s=i,s instanceof HTMLElement)))return void console.error("MarketrixWidget: Invalid container");var s;const{container:a,mountEl:c}=Fd(i);return o.current=a,r.current=zd(c,{...mr(e),isPreviewMode:!0},!0),()=>{r.current&&(r.current.unmount(),r.current=null),o.current&&(o.current.remove(),o.current=null)}},[e,t]),t?null:/* @__PURE__ */y("div",{ref:n,style:{width:"100%",height:"100%",position:"relative"}})},Jd=async e=>{const t=e.container;if(void 0!==e.settings){Kd();const{settings:n,container:r,...o}=e;Vd({...mr(n,o),isPreviewMode:!0},t,!0)}else{if(void 0===e.mtxId||void 0===e.mtxKey)throw new Error("Invalid configuration: provide either settings (preview) or mtxId+mtxKey (production)");{const{container:n,...r}=e;await Yd(r,t)}}};"undefined"!=typeof window&&setTimeout(()=>{try{(e=>{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__mtx?.state)return;const t=document.querySelectorAll("script[mtx-id]"),n=t[t.length-1];if(!(n&&(r=n,r instanceof HTMLScriptElement)))return;var r;const o=n.getAttribute("mtx-id"),i=n.getAttribute("mtx-key"),s=n.getAttribute("mtx-api-host");if(!o||!i||!s){if($d())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void Wd("Please configure mtx-id, mtx-key and mtx-api-host","error")}const a={mtxId:o,mtxKey:i,mtxApiHost:s};"false"===n.getAttribute("mtx-use-screenshare")&&(a.use_screenshare=!1),e(a).catch(e=>console.error("[AutoInit] Failed to initialize widget:",e))})(Yd)}catch(e){console.error("Marketrix Widget: Auto-init registration failed",e)}},0);var Zd={MarketrixWidget:Gd,mountWidget:Jd,initWidget:Yd,unmountWidget:Kd,updateMarketrixConfig:Xd,getCurrentConfig:Bd};export{Gd as MarketrixWidget,Zd as default,Bd as getCurrentConfig,Yd as initWidget,Jd as mountWidget,Kd as unmountWidget,Xd as updateMarketrixConfig};