palmier 1.1.25 → 1.1.26

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.
@@ -84,7 +84,7 @@ ${d}`),g(S);return}f(null,j),s.strategy===jr.Count&&(m--,m===0&&g()),s.strategy=
84
84
 
85
85
  ${f.stack}`),d.unsubscribe(),c.reject(m)):(m=gx(y),m?(f&&(m.stack+=`
86
86
 
87
- ${f.stack}`),c.reject(m)):c.resolve(y))}});return d.requestSubject=t,this.protocol.publish(t,r,{reply:o,headers:s.headers}),c}else{const o=new xx(this.protocol.muxSubscriptions,t,s,l);this.protocol.request(o);try{this.publish(t,r,{reply:`${this.protocol.muxSubscriptions.baseInbox}${o.token}`,headers:s.headers})}catch(f){o.cancel(f)}const c=Promise.race([o.timer,o.deferred]);return c.catch(()=>{o.cancel()}),c}}flush(){return this.isClosed()?Promise.reject(Le.errorForCode(Ee.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(Le.errorForCode(Ee.ConnectionClosed)):this.isDraining()?Promise.reject(Le.errorForCode(Ee.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const t=this.protocol.getServer();return t?t.listen:""}status(){const t=new pn;return t.iterClosed.then(()=>{const r=this.listeners.indexOf(t);this.listeners.splice(r,1)}),this.listeners.push(t),t}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((r,s)=>r==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(t={}){const r=new $k(this,t);if(t.checkAPI!==!1)try{await r.getAccountInfo()}catch(s){const l=s;throw l.code===Ee.NoResponders&&(l.code=Ee.JetStreamNotEnabled),l}return r}jetstream(t={}){return new Id(this,t)}getServerVersion(){const t=this.info;return t?ws(t.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw Le.errorForCode(Ee.Disconnect);const t=Date.now();return await this.flush(),Date.now()-t}get features(){return this.protocol.features}get services(){return this._services||(this._services=new Jk(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(Le.errorForCode(Ee.ConnectionClosed)):this.isDraining()?Promise.reject(Le.errorForCode(Ee.ConnectionDraining)):this.protocol.reconnect()}}class Jk{constructor(t){A(this,"nc");this.nc=t}add(t){try{return new Xl(this.nc,t).start()}catch(r){return Promise.reject(r)}}client(t,r){return new Ak(this.nc,t,r)}}class Xk{constructor(t,r,s){A(this,"bucket");A(this,"sm");A(this,"prefixLen");this.bucket=t,this.prefixLen=r,this.sm=s}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(Pu)||"PUT"}get length(){const t=this.sm.header.get(Dn.MessageSizeHdr)||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Kk{constructor(t,r,s){A(this,"bucket");A(this,"key");A(this,"sm");this.bucket=t,this.key=r,this.sm=s}get value(){return this.sm.data}get created(){return new Date(Ud(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var t;return((t=this.sm.headers)==null?void 0:t.get(Pu))||"PUT"}get delta(){return this.sm.info.pending}get length(){var r;const t=((r=this.sm.headers)==null?void 0:r.get(Dn.MessageSizeHdr))||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Rx extends A2{constructor(r,s,l){super(r.nc,s,l);A(this,"js");A(this,"monitor");this.js=r,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(r){this.sub.info=r}get info(){return this.sub.info}_resetOrderedConsumer(r){if(this.info===null||this.sub.isClosed())return;const s=pi(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const o=this.info;o.config.name=Qi.next(),o.ordered_consumer_sequence.delivery_seq=0,o.flow_control.heartbeat_count=0,o.flow_control.fc_count=0,o.flow_control.consumer_restarts++,o.deliver=s,o.config.deliver_subject=s,o.config.deliver_policy=en.StartSequence,o.config.opt_start_seq=r;const c={};c.stream_name=this.info.stream,c.config=o.config;const f=`${o.api.prefix}.CONSUMER.CREATE.${o.stream}`;this.js._request(f,c,{retries:-1}).then(d=>{const m=d,y=this.sub.info;y.last=m,this.info.config=m.config,this.info.name=m.name}).catch(d=>{const m=new Le(`unable to recreate ordered consumer ${o.stream} at seq ${r}`,Ee.RequestError,d);this.sub.callback(m,{})})}_maybeSetupHbMonitoring(){var s,l;const r=((l=(s=this.info)==null?void 0:s.config)==null?void 0:l.idle_heartbeat)||0;r&&this._setupHbMonitoring(Ud(r))}_setupHbMonitoring(r,s=0){const l={cancelAfter:0,maxOut:2};s&&(l.cancelAfter=s);const o=this.sub,c=f=>{var y,g,x,v;const d=l2(409,`${br.IdleHeartbeatMissed}: ${f}`,this.sub.subject);if(!((y=this.info)==null?void 0:y.ordered))this.sub.callback(null,d);else{if(!this.js.nc.protocol.connected)return!1;const S=((x=(g=this.info)==null?void 0:g.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(S+1),(v=this.monitor)==null||v.restart(),!1}return!o.noIterator};this.monitor=new Bd(r,c,l)}_checkHbOrderConsumer(r){const s=r.headers.get(Dn.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const l=parseInt(r.headers.get(Dn.LastConsumerSeqHdr),10),o=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,l!==o.delivery_seq&&this._resetOrderedConsumer(o.stream_seq+1),!1}_checkOrderedConsumer(r){const s=this.info.ordered_consumer_sequence,l=r.info.streamSequence,o=r.info.deliverySequence;return o!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=o,s.stream_seq=l,!0)}async destroy(){this.isClosed()||await this.drain();const r=this.sub.info,s=r.config.durable_name||r.name,l=`${r.api.prefix}.CONSUMER.DELETE.${r.stream}.${s}`;await r.api._request(l)}async consumerInfo(){const r=this.sub.info,s=r.config.durable_name||r.name,l=`${r.api.prefix}.CONSUMER.INFO.${r.stream}.${s}`,o=await r.api._request(l);return r.last=o,o}}class Qk extends Rx{constructor(t,r,s){super(t,r,s)}pull(t={batch:1}){const{stream:r,config:s,name:l}=this.sub.info,o=s.durable_name??l,c={};if(c.batch=t.batch||1,c.no_wait=t.no_wait||!1,(t.max_bytes??0)>0){const m=this.js.nc.features.get(bt.JS_PULL_MAX_BYTES);if(!m.ok)throw new Error(`max_bytes is only supported on servers ${m.min} or better`);c.max_bytes=t.max_bytes}let f=0;t.expires&&t.expires>0&&(f=t.expires,c.expires=qt(f));let d=0;if(t.idle_heartbeat&&t.idle_heartbeat>0&&(d=t.idle_heartbeat,c.idle_heartbeat=qt(d)),d&&f===0)throw new Error("idle_heartbeat requires expires");if(d>f)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),f&&d&&(this.monitor?this.monitor._change(d,f):this._setupHbMonitoring(d,f));const m=this.info.api,y=`${m.prefix}.CONSUMER.MSG.NEXT.${r}.${o}`,g=this.sub.subject;m.nc.publish(y,m.jc.encode(c),{reply:g})}}}function Zk(e,t){return e?eE(t):Wk(t)}function Wk(e){return(t,r)=>t?[t,null]:(t=pa(r),t?[t,null]:[null,Fl(r,e)])}function eE(e){return(t,r)=>{if(t)return[t,null];const s=pa(r);return s!==null?[Mx(s),null]:[null,Fl(r,e)]}}function Mx(e){if(e!==null)switch(e.code){case Ee.JetStream404NoMessages:case Ee.JetStream408RequestTimeout:return null;case Ee.JetStream409:return o2(e)?e:null;default:return e}return null}function tE(e){e&&e.ack()}function nE(e){const t=e.split(".");if(t.length===9&&t.splice(2,0,"_",""),t.length<11||t[0]!=="$JS"||t[1]!=="ACK")throw new Error("not js message");const r={};return r.domain=t[2]==="_"?"":t[2],r.account_hash=t[3],r.stream=t[4],r.consumer=t[5],r.deliveryCount=parseInt(t[6],10),r.redeliveryCount=r.deliveryCount,r.redelivered=r.deliveryCount>1,r.streamSequence=parseInt(t[7],10),r.deliverySequence=parseInt(t[8],10),r.timestampNanos=parseInt(t[9],10),r.pending=parseInt(t[10],10),r}class rE{constructor(t,r){A(this,"msg");A(this,"di");A(this,"didAck");A(this,"timeout");this.msg=t,this.didAck=!1,this.timeout=r}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=nE(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(t){this.didAck||(this.didAck=!this.isWIP(t),this.msg.respond(t))}isWIP(t){return t.length===4&&t[0]===Sl[0]&&t[1]===Sl[1]&&t[2]===Sl[2]&&t[3]===Sl[3]}async ackAck(t){var s;t=t||{},t.timeout=t.timeout||this.timeout;const r=It();if(this.didAck)r.resolve(!1);else if(this.didAck=!0,this.msg.reply){const o=this.msg.publisher,c=!((s=o.options)!=null&&s.noAsyncTraces),f=new xx(o.muxSubscriptions,this.msg.reply,{timeout:t.timeout},c);o.request(f);try{o.publish(this.msg.reply,B0,{reply:`${o.muxSubscriptions.baseInbox}${f.token}`})}catch(d){f.cancel(d)}try{await Promise.race([f.timer,f.deferred]),r.resolve(!0)}catch(d){f.cancel(d),r.reject(d)}}else r.resolve(!1);return r}ack(){this.doAck(B0)}nak(t){let r=Uk;t&&(r=Ru().encode(`-NAK ${JSON.stringify({delay:qt(t)})}`)),this.doAck(r)}working(){this.doAck(Sl)}next(t,r={batch:1}){const s={};s.batch=r.batch||1,s.no_wait=r.no_wait||!1,r.expires&&r.expires>0&&(s.expires=qt(r.expires));const l=Nr().encode(s),o=Sa.concat(Pk,Hk,l),c=t?{reply:t}:void 0;this.msg.respond(o,c)}term(t=""){let r=Bk;(t==null?void 0:t.length)>0&&(r=Ru().encode(`+TERM ${t}`)),this.doAck(r)}json(){return this.msg.json()}string(){return this.msg.string()}}const iE="1.30.3",sE="nats.ws";class aE{constructor(){A(this,"version");A(this,"lang");A(this,"closeError");A(this,"connected");A(this,"done");A(this,"socket");A(this,"options");A(this,"socketClosed");A(this,"encrypted");A(this,"peeked");A(this,"yields");A(this,"signal");A(this,"closedNotification");this.version=iE,this.lang=sE,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=It(),this.closedNotification=It()}async connect(t,r){const s=It();if(r.tls)return s.reject(new Le("tls",Ee.InvalidOption)),s;this.options=r;const l=t.src;if(r.wsFactory){const{socket:o,encrypted:c}=await r.wsFactory(t.src,r);this.socket=o,this.encrypted=c}else this.encrypted=l.indexOf("wss://")===0,this.socket=new WebSocket(l);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=o=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(o.data)),this.peeked){this.signal.resolve();return}const c=Sa.concat(...this.yields),f=M2(c);if(f!==""){const d=xk.exec(f);if(!d){r.debug&&console.error("!!!",fu(c)),s.reject(new Error("unexpected response from server"));return}try{const m=JSON.parse(d[1]);yk(m,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(m){s.reject(m);return}}},this.socket.onclose=o=>{if(this.isDiscarded())return;this.socketClosed=!0;let c;this.done||(o.wasClean||(c=new Error(o.reason)),this._closed(c))},this.socket.onerror=o=>{if(this.isDiscarded())return;const c=o,f=new Le(c.message,Ee.Unknown,new Error(c.error));s.reject(f)},s}disconnect(){this._closed(void 0,!0)}async _closed(t,r=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=t,!t)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await ja(100);this.done=!0;try{this.socket.close(t?1002:1e3,t?t.message:void 0)}catch{}r&&this.closedNotification.resolve(t)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const t=this.yields;this.yields=[];for(let r=0;r<t.length;r++)this.options.debug&&console.info(`> ${fu(t[r])}`),yield t[r];if(this.done)break;this.yields.length===0&&(t.length=0,this.yields=t,this.signal=It())}}isEncrypted(){return this.connected&&this.encrypted}send(t){if(!this.isDiscarded())try{this.socket.send(t.buffer),this.options.debug&&console.info(`< ${fu(t)}`);return}catch(r){this.options.debug&&console.error(`!!! ${fu(t)}: ${r}`)}}close(t){return this._closed(t,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var t;this.done=!0;try{(t=this.socket)==null||t.close()}catch{}}}function lE(e,t){/^(.*:\/\/)(.*)/.test(e)||(typeof t=="boolean"?e=`${t===!0?"https":"http"}://${e}`:e=`https://${e}`);let s=new URL(e);const l=s.protocol.toLowerCase();l==="ws:"&&(t=!1),l==="wss:"&&(t=!0),l!=="https:"&&l!=="http"&&(e=e.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${e}`));let o,c;const f=s.hostname,d=s.pathname,m=s.search||"";switch(l){case"http:":case"ws:":case"nats:":c=s.port||"80",o="ws:";break;case"https:":case"wss:":case"tls:":c=s.port||"443",o="wss:";break;default:c=s.port||t===!0?"443":"80",o=t===!0?"wss:":"ws:";break}return`${o}//${f}:${c}${d}${m}`}function Dx(e={}){return j2({defaultPort:443,urlParseFn:lE,factory:()=>new aE}),Fd.connect(e)}/*! Capacitor: https://capacitorjs.com/ - MIT License */var _a;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(_a||(_a={}));class Nh extends Error{constructor(t,r,s){super(t),this.message=t,this.code=r,this.data=s}}const oE=e=>{var t,r;return e!=null&&e.androidBridge?"android":!((r=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||r===void 0)&&r.bridge?"ios":"web"},uE=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},s=r.Plugins=r.Plugins||{},l=()=>t!==null?t.name:oE(e),o=()=>l()!=="web",c=g=>{const x=m.get(g);return!!(x!=null&&x.platforms.has(l())||f(g))},f=g=>{var x;return(x=r.PluginHeaders)===null||x===void 0?void 0:x.find(v=>v.name===g)},d=g=>e.console.error(g),m=new Map,y=(g,x={})=>{const v=m.get(g);if(v)return console.warn(`Capacitor plugin "${g}" already registered. Cannot register plugins twice.`),v.proxy;const S=l(),j=f(g);let D;const R=async()=>(!D&&S in x?D=typeof x[S]=="function"?D=await x[S]():D=x[S]:t!==null&&!D&&"web"in x&&(D=typeof x.web=="function"?D=await x.web():D=x.web),D),O=(G,B)=>{var z,K;if(j){const I=j==null?void 0:j.methods.find(oe=>B===oe.name);if(I)return I.rtype==="promise"?oe=>r.nativePromise(g,B.toString(),oe):(oe,ee)=>r.nativeCallback(g,B.toString(),oe,ee);if(G)return(z=G[B])===null||z===void 0?void 0:z.bind(G)}else{if(G)return(K=G[B])===null||K===void 0?void 0:K.bind(G);throw new Nh(`"${g}" plugin is not implemented on ${S}`,_a.Unimplemented)}},F=G=>{let B;const z=(...K)=>{const I=R().then(oe=>{const ee=O(oe,G);if(ee){const te=ee(...K);return B=te==null?void 0:te.remove,te}else throw new Nh(`"${g}.${G}()" is not implemented on ${S}`,_a.Unimplemented)});return G==="addListener"&&(I.remove=async()=>B()),I};return z.toString=()=>`${G.toString()}() { [capacitor code] }`,Object.defineProperty(z,"name",{value:G,writable:!1,configurable:!1}),z},ue=F("addListener"),H=F("removeListener"),P=(G,B)=>{const z=ue({eventName:G},B),K=async()=>{const oe=await z;H({eventName:G,callbackId:oe},B)},I=new Promise(oe=>z.then(()=>oe({remove:K})));return I.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await K()},I},W=new Proxy({},{get(G,B){switch(B){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return j?P:ue;case"removeListener":return H;default:return F(B)}}});return s[g]=W,m.set(g,{name:g,proxy:W,platforms:new Set([...Object.keys(x),...j?[S]:[]])}),W};return r.convertFileSrc||(r.convertFileSrc=g=>g),r.getPlatform=l,r.handleError=d,r.isNativePlatform=o,r.isPluginAvailable=c,r.registerPlugin=y,r.Exception=Nh,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},cE=e=>e.Capacitor=uE(e),In=cE(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ks=In.registerPlugin;class $d{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,r){let s=!1;this.listeners[t]||(this.listeners[t]=[],s=!0),this.listeners[t].push(r);const o=this.windowListeners[t];o&&!o.registered&&this.addWindowListener(o),s&&this.sendRetainedArgumentsForEvent(t);const c=async()=>this.removeListener(t,r);return Promise.resolve({remove:c})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,r,s){const l=this.listeners[t];if(!l){if(s){let o=this.retainedEventArguments[t];o||(o=[]),o.push(r),this.retainedEventArguments[t]=o}return}l.forEach(o=>o(r))}hasListeners(t){var r;return!!(!((r=this.listeners[t])===null||r===void 0)&&r.length)}registerWindowListener(t,r){this.windowListeners[r]={registered:!1,windowEventName:t,pluginEventName:r,handler:s=>{this.notifyListeners(r,s)}}}unimplemented(t="not implemented"){return new In.Exception(t,_a.Unimplemented)}unavailable(t="not available"){return new In.Exception(t,_a.Unavailable)}async removeListener(t,r){const s=this.listeners[t];if(!s)return;const l=s.indexOf(r);this.listeners[t].splice(l,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const r=this.retainedEventArguments[t];r&&(delete this.retainedEventArguments[t],r.forEach(s=>{this.notifyListeners(t,s)}))}}const q0=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),I0=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class fE extends $d{async getCookies(){const t=document.cookie,r={};return t.split(";").forEach(s=>{if(s.length<=0)return;let[l,o]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");l=I0(l).trim(),o=I0(o).trim(),r[l]=o}),r}async setCookie(t){try{const r=q0(t.key),s=q0(t.value),l=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",o=(t.path||"/").replace("path=",""),c=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${r}=${s||""}${l}; path=${o}; ${c};`}catch(r){return Promise.reject(r)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(r){return Promise.reject(r)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const r of t)document.cookie=r.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}ks("CapacitorCookies",{web:()=>new fE});const hE=async e=>new Promise((t,r)=>{const s=new FileReader;s.onload=()=>{const l=s.result;t(l.indexOf(",")>=0?l.split(",")[1]:l)},s.onerror=l=>r(l),s.readAsDataURL(e)}),dE=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(l=>l.toLocaleLowerCase()).reduce((l,o,c)=>(l[o]=e[t[c]],l),{})},mE=(e,t=!0)=>e?Object.entries(e).reduce((s,l)=>{const[o,c]=l;let f,d;return Array.isArray(c)?(d="",c.forEach(m=>{f=t?encodeURIComponent(m):m,d+=`${o}=${f}&`}),d.slice(0,-1)):(f=t?encodeURIComponent(c):c,d=`${o}=${f}`),`${s}&${d}`},"").substr(1):null,pE=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),l=dE(e.headers)["content-type"]||"";if(typeof e.data=="string")r.body=e.data;else if(l.includes("application/x-www-form-urlencoded")){const o=new URLSearchParams;for(const[c,f]of Object.entries(e.data||{}))o.set(c,f);r.body=o.toString()}else if(l.includes("multipart/form-data")||e.data instanceof FormData){const o=new FormData;if(e.data instanceof FormData)e.data.forEach((f,d)=>{o.append(d,f)});else for(const f of Object.keys(e.data))o.append(f,e.data[f]);r.body=o;const c=new Headers(r.headers);c.delete("content-type"),r.headers=c}else(l.includes("application/json")||typeof e.data=="object")&&(r.body=JSON.stringify(e.data));return r};class gE extends $d{async request(t){const r=pE(t,t.webFetchExtra),s=mE(t.params,t.shouldEncodeUrlParams),l=s?`${t.url}?${s}`:t.url,o=await fetch(l,r),c=o.headers.get("content-type")||"";let{responseType:f="text"}=o.ok?t:{};c.includes("application/json")&&(f="json");let d,m;switch(f){case"arraybuffer":case"blob":m=await o.blob(),d=await hE(m);break;case"json":d=await o.json();break;case"document":case"text":default:d=await o.text()}const y={};return o.headers.forEach((g,x)=>{y[x]=g}),{data:d,headers:y,status:o.status,url:o.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}ks("CapacitorHttp",{web:()=>new gE});var F0;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(F0||(F0={}));var $0;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})($0||($0={}));class yE extends $d{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}ks("SystemBars",{web:()=>new yE});const bE="modulepreload",xE=function(e){return"/"+e},V0={},Vd=function(t,r,s){let l=Promise.resolve();if(r&&r.length>0){let c=function(m){return Promise.all(m.map(y=>Promise.resolve(y).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const f=document.querySelector("meta[property=csp-nonce]"),d=(f==null?void 0:f.nonce)||(f==null?void 0:f.getAttribute("nonce"));l=c(r.map(m=>{if(m=xE(m),m in V0)return;V0[m]=!0;const y=m.endsWith(".css"),g=y?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${g}`))return;const x=document.createElement("link");if(x.rel=y?"stylesheet":bE,y||(x.as="script"),x.crossOrigin="",x.href=m,d&&x.setAttribute("nonce",d),document.head.appendChild(x),y)return new Promise((v,S)=>{x.addEventListener("load",v),x.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${m}`)))})}))}function o(c){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=c,window.dispatchEvent(f),!f.defaultPrevented)throw c}return l.then(c=>{for(const f of c||[])f.status==="rejected"&&o(f.reason);return t().catch(o)})},gd=ks("App",{web:()=>Vd(()=>import("./web-YYfGpkCq.js"),[]).then(e=>new e.AppWeb)}),vE=ks("Network",{web:()=>Vd(()=>import("./web-Flj1nZsf.js"),[]).then(e=>new e.NetworkWeb)}),Bu=In.isNativePlatform()?"https://app.palmier.me":"";async function Lx(e,t,r,s){const l=`${Bu}${t}`;console.log(`[API] ${e} ${l}`);const c=await fetch(l,{method:e,headers:{"Content-Type":"application/json"},body:r!=null?JSON.stringify(r):void 0});if(!c.ok){const f=await c.text();let d;try{const m=JSON.parse(f);d=m.error??m.message??f}catch{d=f}throw console.error(`[API] ${e} ${t} failed:`,c.status,d),new Error(d||`Request failed with status ${c.status}`)}return console.log(`[API] ${e} ${t} ->`,c.status),c.json()}function wE(e,t,r){return Lx("POST",e,t)}function SE(e,t){return Lx("GET",e,void 0)}const Y0=In.isNativePlatform(),zx=E.createContext(null),_E=2e3,Th=6e3,kE=1500,EE=6e4;function CE({children:e,activeHost:t}){const[r,s]=E.useState(null),[l,o]=E.useState(!1),c=E.useRef(null),[f,d]=E.useState(!1),[m,y]=E.useState(!1),[g,x]=E.useState(!1),[v,S]=E.useState(!1),j=E.useRef(Ru()),D=E.useRef(new Set),R=E.useRef(0),O=!!t.directUrl,F=Y0&&!O&&!!t.lanUrl&&v,ue=m||g?"disconnected":O?f?"direct":"connecting":l?F?"lan":"nats":"connecting",H=ue!=="connecting"&&ue!=="disconnected";E.useEffect(()=>{if(!Y0||O||!t.lanUrl){S(!1);return}let G=!1;const B=t.lanUrl,z=t.hostId;async function K(){console.log("[HOST/LAN] probing",B);try{const te=await fetch(`${B}/health`,{signal:AbortSignal.timeout(kE)});if(G)return;if(!te.ok){console.log("[HOST/LAN] probe got non-ok:",te.status),S(!1);return}const V=await te.json(),X=V.hostId===z;X?console.log("[HOST/LAN] reachable"):console.log("[HOST/LAN] hostId mismatch — got:",V.hostId,"expected:",z),S(X)}catch(te){G||(console.log("[HOST/LAN] probe failed:",te instanceof Error?te.message:te),S(!1))}}K();const I=window.setInterval(K,EE),oe=gd.addListener("appStateChange",te=>{te.isActive&&K()}),ee=vE.addListener("networkStatusChange",()=>K());return()=>{G=!0,clearInterval(I),oe.then(te=>te.remove()),ee.then(te=>te.remove())}},[t.hostId,t.lanUrl,O]),E.useEffect(()=>{if(O){c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),o(!1));return}let G=!1,B=1e3;const z=3e4;async function K(){for(;!G;)try{const I=await fetch(`${Bu}/api/nats-credentials/${t.hostId}`);if(G)return;if(I.status===401||I.status===403||I.status===404){console.error("[NATS] Host not found or rejected by relay:",I.status),x(!0);return}if(!I.ok)throw new Error(`credentials fetch ${I.status}`);const oe=await I.json();if(!oe.natsWsUrl){console.error("[NATS] Relay returned empty natsWsUrl — treating as terminal"),x(!0);return}if(G)return;console.log("[NATS] Connecting to",oe.natsWsUrl);const ee=await Dx({servers:oe.natsWsUrl,authenticator:Ex(oe.natsJwt,new TextEncoder().encode(oe.natsNkeySeed)),pingInterval:3e4,maxPingOut:2});if(G){ee.close().catch(()=>{});return}if(console.log("[NATS] Connected"),c.current=ee,s(ee),o(!0),B=1e3,await ee.closed(),G)return;console.log("[NATS] Connection closed, will reconnect"),c.current=null,s(null),o(!1)}catch(I){if(G)return;console.warn(`[NATS] Connect failed, retrying in ${B}ms:`,I),o(!1),await new Promise(oe=>setTimeout(oe,B)),B=Math.min(B*2,z)}}return K(),()=>{G=!0,c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),o(!1))}},[O,t]),E.useEffect(()=>{if(O)return;const G=gd.addListener("appStateChange",B=>{if(!B.isActive||!c.current)return;const z=c.current;Promise.race([z.flush(),new Promise((K,I)=>setTimeout(()=>I(new Error("ping timeout")),2e3))]).catch(()=>{console.log("[NATS] Resume probe failed — cycling conn"),z.close().catch(()=>{})})});return()=>{G.then(B=>B.remove())}},[O]),E.useEffect(()=>{if(!O){d(!1);return}const G=new AbortController;async function B(){var oe;const K=new AbortController,I=setTimeout(()=>K.abort(),_E);G.signal.addEventListener("abort",()=>K.abort());try{const ee=await fetch(`${t.directUrl}/events`,{headers:{Authorization:`Bearer ${t.clientToken}`},signal:K.signal});return clearTimeout(I),ee.ok?((oe=ee.body)==null?void 0:oe.getReader())??null:null}catch{return clearTimeout(I),null}}async function z(K){d(!0),console.log("[HOST] SSE connected to",t.directUrl),R.current=Date.now();function I(){setTimeout(()=>{G.signal.aborted||Date.now()-R.current<Th||(console.log("[HOST] Heartbeat timeout — no data for",Th/1e3,"s"),G.abort(),d(!1),console.log("[HOST] Direct host unreachable"))},Th)}I();const oe=new TextDecoder;let ee="";try{for(;;){const{done:te,value:V}=await K.read();if(te)break;ee+=oe.decode(V,{stream:!0}),R.current=Date.now(),I();const X=ee.split(`
87
+ ${f.stack}`),c.reject(m)):c.resolve(y))}});return d.requestSubject=t,this.protocol.publish(t,r,{reply:o,headers:s.headers}),c}else{const o=new xx(this.protocol.muxSubscriptions,t,s,l);this.protocol.request(o);try{this.publish(t,r,{reply:`${this.protocol.muxSubscriptions.baseInbox}${o.token}`,headers:s.headers})}catch(f){o.cancel(f)}const c=Promise.race([o.timer,o.deferred]);return c.catch(()=>{o.cancel()}),c}}flush(){return this.isClosed()?Promise.reject(Le.errorForCode(Ee.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(Le.errorForCode(Ee.ConnectionClosed)):this.isDraining()?Promise.reject(Le.errorForCode(Ee.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const t=this.protocol.getServer();return t?t.listen:""}status(){const t=new pn;return t.iterClosed.then(()=>{const r=this.listeners.indexOf(t);this.listeners.splice(r,1)}),this.listeners.push(t),t}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((r,s)=>r==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(t={}){const r=new $k(this,t);if(t.checkAPI!==!1)try{await r.getAccountInfo()}catch(s){const l=s;throw l.code===Ee.NoResponders&&(l.code=Ee.JetStreamNotEnabled),l}return r}jetstream(t={}){return new Id(this,t)}getServerVersion(){const t=this.info;return t?ws(t.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw Le.errorForCode(Ee.Disconnect);const t=Date.now();return await this.flush(),Date.now()-t}get features(){return this.protocol.features}get services(){return this._services||(this._services=new Jk(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(Le.errorForCode(Ee.ConnectionClosed)):this.isDraining()?Promise.reject(Le.errorForCode(Ee.ConnectionDraining)):this.protocol.reconnect()}}class Jk{constructor(t){A(this,"nc");this.nc=t}add(t){try{return new Xl(this.nc,t).start()}catch(r){return Promise.reject(r)}}client(t,r){return new Ak(this.nc,t,r)}}class Xk{constructor(t,r,s){A(this,"bucket");A(this,"sm");A(this,"prefixLen");this.bucket=t,this.prefixLen=r,this.sm=s}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(Pu)||"PUT"}get length(){const t=this.sm.header.get(Dn.MessageSizeHdr)||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Kk{constructor(t,r,s){A(this,"bucket");A(this,"key");A(this,"sm");this.bucket=t,this.key=r,this.sm=s}get value(){return this.sm.data}get created(){return new Date(Ud(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var t;return((t=this.sm.headers)==null?void 0:t.get(Pu))||"PUT"}get delta(){return this.sm.info.pending}get length(){var r;const t=((r=this.sm.headers)==null?void 0:r.get(Dn.MessageSizeHdr))||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Rx extends A2{constructor(r,s,l){super(r.nc,s,l);A(this,"js");A(this,"monitor");this.js=r,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(r){this.sub.info=r}get info(){return this.sub.info}_resetOrderedConsumer(r){if(this.info===null||this.sub.isClosed())return;const s=pi(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const o=this.info;o.config.name=Qi.next(),o.ordered_consumer_sequence.delivery_seq=0,o.flow_control.heartbeat_count=0,o.flow_control.fc_count=0,o.flow_control.consumer_restarts++,o.deliver=s,o.config.deliver_subject=s,o.config.deliver_policy=en.StartSequence,o.config.opt_start_seq=r;const c={};c.stream_name=this.info.stream,c.config=o.config;const f=`${o.api.prefix}.CONSUMER.CREATE.${o.stream}`;this.js._request(f,c,{retries:-1}).then(d=>{const m=d,y=this.sub.info;y.last=m,this.info.config=m.config,this.info.name=m.name}).catch(d=>{const m=new Le(`unable to recreate ordered consumer ${o.stream} at seq ${r}`,Ee.RequestError,d);this.sub.callback(m,{})})}_maybeSetupHbMonitoring(){var s,l;const r=((l=(s=this.info)==null?void 0:s.config)==null?void 0:l.idle_heartbeat)||0;r&&this._setupHbMonitoring(Ud(r))}_setupHbMonitoring(r,s=0){const l={cancelAfter:0,maxOut:2};s&&(l.cancelAfter=s);const o=this.sub,c=f=>{var y,g,x,v;const d=l2(409,`${br.IdleHeartbeatMissed}: ${f}`,this.sub.subject);if(!((y=this.info)==null?void 0:y.ordered))this.sub.callback(null,d);else{if(!this.js.nc.protocol.connected)return!1;const S=((x=(g=this.info)==null?void 0:g.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(S+1),(v=this.monitor)==null||v.restart(),!1}return!o.noIterator};this.monitor=new Bd(r,c,l)}_checkHbOrderConsumer(r){const s=r.headers.get(Dn.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const l=parseInt(r.headers.get(Dn.LastConsumerSeqHdr),10),o=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,l!==o.delivery_seq&&this._resetOrderedConsumer(o.stream_seq+1),!1}_checkOrderedConsumer(r){const s=this.info.ordered_consumer_sequence,l=r.info.streamSequence,o=r.info.deliverySequence;return o!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=o,s.stream_seq=l,!0)}async destroy(){this.isClosed()||await this.drain();const r=this.sub.info,s=r.config.durable_name||r.name,l=`${r.api.prefix}.CONSUMER.DELETE.${r.stream}.${s}`;await r.api._request(l)}async consumerInfo(){const r=this.sub.info,s=r.config.durable_name||r.name,l=`${r.api.prefix}.CONSUMER.INFO.${r.stream}.${s}`,o=await r.api._request(l);return r.last=o,o}}class Qk extends Rx{constructor(t,r,s){super(t,r,s)}pull(t={batch:1}){const{stream:r,config:s,name:l}=this.sub.info,o=s.durable_name??l,c={};if(c.batch=t.batch||1,c.no_wait=t.no_wait||!1,(t.max_bytes??0)>0){const m=this.js.nc.features.get(bt.JS_PULL_MAX_BYTES);if(!m.ok)throw new Error(`max_bytes is only supported on servers ${m.min} or better`);c.max_bytes=t.max_bytes}let f=0;t.expires&&t.expires>0&&(f=t.expires,c.expires=qt(f));let d=0;if(t.idle_heartbeat&&t.idle_heartbeat>0&&(d=t.idle_heartbeat,c.idle_heartbeat=qt(d)),d&&f===0)throw new Error("idle_heartbeat requires expires");if(d>f)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),f&&d&&(this.monitor?this.monitor._change(d,f):this._setupHbMonitoring(d,f));const m=this.info.api,y=`${m.prefix}.CONSUMER.MSG.NEXT.${r}.${o}`,g=this.sub.subject;m.nc.publish(y,m.jc.encode(c),{reply:g})}}}function Zk(e,t){return e?eE(t):Wk(t)}function Wk(e){return(t,r)=>t?[t,null]:(t=pa(r),t?[t,null]:[null,Fl(r,e)])}function eE(e){return(t,r)=>{if(t)return[t,null];const s=pa(r);return s!==null?[Mx(s),null]:[null,Fl(r,e)]}}function Mx(e){if(e!==null)switch(e.code){case Ee.JetStream404NoMessages:case Ee.JetStream408RequestTimeout:return null;case Ee.JetStream409:return o2(e)?e:null;default:return e}return null}function tE(e){e&&e.ack()}function nE(e){const t=e.split(".");if(t.length===9&&t.splice(2,0,"_",""),t.length<11||t[0]!=="$JS"||t[1]!=="ACK")throw new Error("not js message");const r={};return r.domain=t[2]==="_"?"":t[2],r.account_hash=t[3],r.stream=t[4],r.consumer=t[5],r.deliveryCount=parseInt(t[6],10),r.redeliveryCount=r.deliveryCount,r.redelivered=r.deliveryCount>1,r.streamSequence=parseInt(t[7],10),r.deliverySequence=parseInt(t[8],10),r.timestampNanos=parseInt(t[9],10),r.pending=parseInt(t[10],10),r}class rE{constructor(t,r){A(this,"msg");A(this,"di");A(this,"didAck");A(this,"timeout");this.msg=t,this.didAck=!1,this.timeout=r}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=nE(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(t){this.didAck||(this.didAck=!this.isWIP(t),this.msg.respond(t))}isWIP(t){return t.length===4&&t[0]===Sl[0]&&t[1]===Sl[1]&&t[2]===Sl[2]&&t[3]===Sl[3]}async ackAck(t){var s;t=t||{},t.timeout=t.timeout||this.timeout;const r=It();if(this.didAck)r.resolve(!1);else if(this.didAck=!0,this.msg.reply){const o=this.msg.publisher,c=!((s=o.options)!=null&&s.noAsyncTraces),f=new xx(o.muxSubscriptions,this.msg.reply,{timeout:t.timeout},c);o.request(f);try{o.publish(this.msg.reply,B0,{reply:`${o.muxSubscriptions.baseInbox}${f.token}`})}catch(d){f.cancel(d)}try{await Promise.race([f.timer,f.deferred]),r.resolve(!0)}catch(d){f.cancel(d),r.reject(d)}}else r.resolve(!1);return r}ack(){this.doAck(B0)}nak(t){let r=Uk;t&&(r=Ru().encode(`-NAK ${JSON.stringify({delay:qt(t)})}`)),this.doAck(r)}working(){this.doAck(Sl)}next(t,r={batch:1}){const s={};s.batch=r.batch||1,s.no_wait=r.no_wait||!1,r.expires&&r.expires>0&&(s.expires=qt(r.expires));const l=Nr().encode(s),o=Sa.concat(Pk,Hk,l),c=t?{reply:t}:void 0;this.msg.respond(o,c)}term(t=""){let r=Bk;(t==null?void 0:t.length)>0&&(r=Ru().encode(`+TERM ${t}`)),this.doAck(r)}json(){return this.msg.json()}string(){return this.msg.string()}}const iE="1.30.3",sE="nats.ws";class aE{constructor(){A(this,"version");A(this,"lang");A(this,"closeError");A(this,"connected");A(this,"done");A(this,"socket");A(this,"options");A(this,"socketClosed");A(this,"encrypted");A(this,"peeked");A(this,"yields");A(this,"signal");A(this,"closedNotification");this.version=iE,this.lang=sE,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=It(),this.closedNotification=It()}async connect(t,r){const s=It();if(r.tls)return s.reject(new Le("tls",Ee.InvalidOption)),s;this.options=r;const l=t.src;if(r.wsFactory){const{socket:o,encrypted:c}=await r.wsFactory(t.src,r);this.socket=o,this.encrypted=c}else this.encrypted=l.indexOf("wss://")===0,this.socket=new WebSocket(l);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=o=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(o.data)),this.peeked){this.signal.resolve();return}const c=Sa.concat(...this.yields),f=M2(c);if(f!==""){const d=xk.exec(f);if(!d){r.debug&&console.error("!!!",fu(c)),s.reject(new Error("unexpected response from server"));return}try{const m=JSON.parse(d[1]);yk(m,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(m){s.reject(m);return}}},this.socket.onclose=o=>{if(this.isDiscarded())return;this.socketClosed=!0;let c;this.done||(o.wasClean||(c=new Error(o.reason)),this._closed(c))},this.socket.onerror=o=>{if(this.isDiscarded())return;const c=o,f=new Le(c.message,Ee.Unknown,new Error(c.error));s.reject(f)},s}disconnect(){this._closed(void 0,!0)}async _closed(t,r=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=t,!t)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await ja(100);this.done=!0;try{this.socket.close(t?1002:1e3,t?t.message:void 0)}catch{}r&&this.closedNotification.resolve(t)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const t=this.yields;this.yields=[];for(let r=0;r<t.length;r++)this.options.debug&&console.info(`> ${fu(t[r])}`),yield t[r];if(this.done)break;this.yields.length===0&&(t.length=0,this.yields=t,this.signal=It())}}isEncrypted(){return this.connected&&this.encrypted}send(t){if(!this.isDiscarded())try{this.socket.send(t.buffer),this.options.debug&&console.info(`< ${fu(t)}`);return}catch(r){this.options.debug&&console.error(`!!! ${fu(t)}: ${r}`)}}close(t){return this._closed(t,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var t;this.done=!0;try{(t=this.socket)==null||t.close()}catch{}}}function lE(e,t){/^(.*:\/\/)(.*)/.test(e)||(typeof t=="boolean"?e=`${t===!0?"https":"http"}://${e}`:e=`https://${e}`);let s=new URL(e);const l=s.protocol.toLowerCase();l==="ws:"&&(t=!1),l==="wss:"&&(t=!0),l!=="https:"&&l!=="http"&&(e=e.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${e}`));let o,c;const f=s.hostname,d=s.pathname,m=s.search||"";switch(l){case"http:":case"ws:":case"nats:":c=s.port||"80",o="ws:";break;case"https:":case"wss:":case"tls:":c=s.port||"443",o="wss:";break;default:c=s.port||t===!0?"443":"80",o=t===!0?"wss:":"ws:";break}return`${o}//${f}:${c}${d}${m}`}function Dx(e={}){return j2({defaultPort:443,urlParseFn:lE,factory:()=>new aE}),Fd.connect(e)}/*! Capacitor: https://capacitorjs.com/ - MIT License */var _a;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(_a||(_a={}));class Nh extends Error{constructor(t,r,s){super(t),this.message=t,this.code=r,this.data=s}}const oE=e=>{var t,r;return e!=null&&e.androidBridge?"android":!((r=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||r===void 0)&&r.bridge?"ios":"web"},uE=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},s=r.Plugins=r.Plugins||{},l=()=>t!==null?t.name:oE(e),o=()=>l()!=="web",c=g=>{const x=m.get(g);return!!(x!=null&&x.platforms.has(l())||f(g))},f=g=>{var x;return(x=r.PluginHeaders)===null||x===void 0?void 0:x.find(v=>v.name===g)},d=g=>e.console.error(g),m=new Map,y=(g,x={})=>{const v=m.get(g);if(v)return console.warn(`Capacitor plugin "${g}" already registered. Cannot register plugins twice.`),v.proxy;const S=l(),j=f(g);let D;const R=async()=>(!D&&S in x?D=typeof x[S]=="function"?D=await x[S]():D=x[S]:t!==null&&!D&&"web"in x&&(D=typeof x.web=="function"?D=await x.web():D=x.web),D),O=(G,B)=>{var z,K;if(j){const I=j==null?void 0:j.methods.find(oe=>B===oe.name);if(I)return I.rtype==="promise"?oe=>r.nativePromise(g,B.toString(),oe):(oe,ee)=>r.nativeCallback(g,B.toString(),oe,ee);if(G)return(z=G[B])===null||z===void 0?void 0:z.bind(G)}else{if(G)return(K=G[B])===null||K===void 0?void 0:K.bind(G);throw new Nh(`"${g}" plugin is not implemented on ${S}`,_a.Unimplemented)}},F=G=>{let B;const z=(...K)=>{const I=R().then(oe=>{const ee=O(oe,G);if(ee){const te=ee(...K);return B=te==null?void 0:te.remove,te}else throw new Nh(`"${g}.${G}()" is not implemented on ${S}`,_a.Unimplemented)});return G==="addListener"&&(I.remove=async()=>B()),I};return z.toString=()=>`${G.toString()}() { [capacitor code] }`,Object.defineProperty(z,"name",{value:G,writable:!1,configurable:!1}),z},ue=F("addListener"),H=F("removeListener"),P=(G,B)=>{const z=ue({eventName:G},B),K=async()=>{const oe=await z;H({eventName:G,callbackId:oe},B)},I=new Promise(oe=>z.then(()=>oe({remove:K})));return I.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await K()},I},W=new Proxy({},{get(G,B){switch(B){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return j?P:ue;case"removeListener":return H;default:return F(B)}}});return s[g]=W,m.set(g,{name:g,proxy:W,platforms:new Set([...Object.keys(x),...j?[S]:[]])}),W};return r.convertFileSrc||(r.convertFileSrc=g=>g),r.getPlatform=l,r.handleError=d,r.isNativePlatform=o,r.isPluginAvailable=c,r.registerPlugin=y,r.Exception=Nh,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},cE=e=>e.Capacitor=uE(e),In=cE(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ks=In.registerPlugin;class $d{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,r){let s=!1;this.listeners[t]||(this.listeners[t]=[],s=!0),this.listeners[t].push(r);const o=this.windowListeners[t];o&&!o.registered&&this.addWindowListener(o),s&&this.sendRetainedArgumentsForEvent(t);const c=async()=>this.removeListener(t,r);return Promise.resolve({remove:c})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,r,s){const l=this.listeners[t];if(!l){if(s){let o=this.retainedEventArguments[t];o||(o=[]),o.push(r),this.retainedEventArguments[t]=o}return}l.forEach(o=>o(r))}hasListeners(t){var r;return!!(!((r=this.listeners[t])===null||r===void 0)&&r.length)}registerWindowListener(t,r){this.windowListeners[r]={registered:!1,windowEventName:t,pluginEventName:r,handler:s=>{this.notifyListeners(r,s)}}}unimplemented(t="not implemented"){return new In.Exception(t,_a.Unimplemented)}unavailable(t="not available"){return new In.Exception(t,_a.Unavailable)}async removeListener(t,r){const s=this.listeners[t];if(!s)return;const l=s.indexOf(r);this.listeners[t].splice(l,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const r=this.retainedEventArguments[t];r&&(delete this.retainedEventArguments[t],r.forEach(s=>{this.notifyListeners(t,s)}))}}const q0=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),I0=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class fE extends $d{async getCookies(){const t=document.cookie,r={};return t.split(";").forEach(s=>{if(s.length<=0)return;let[l,o]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");l=I0(l).trim(),o=I0(o).trim(),r[l]=o}),r}async setCookie(t){try{const r=q0(t.key),s=q0(t.value),l=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",o=(t.path||"/").replace("path=",""),c=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${r}=${s||""}${l}; path=${o}; ${c};`}catch(r){return Promise.reject(r)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(r){return Promise.reject(r)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const r of t)document.cookie=r.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}ks("CapacitorCookies",{web:()=>new fE});const hE=async e=>new Promise((t,r)=>{const s=new FileReader;s.onload=()=>{const l=s.result;t(l.indexOf(",")>=0?l.split(",")[1]:l)},s.onerror=l=>r(l),s.readAsDataURL(e)}),dE=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(l=>l.toLocaleLowerCase()).reduce((l,o,c)=>(l[o]=e[t[c]],l),{})},mE=(e,t=!0)=>e?Object.entries(e).reduce((s,l)=>{const[o,c]=l;let f,d;return Array.isArray(c)?(d="",c.forEach(m=>{f=t?encodeURIComponent(m):m,d+=`${o}=${f}&`}),d.slice(0,-1)):(f=t?encodeURIComponent(c):c,d=`${o}=${f}`),`${s}&${d}`},"").substr(1):null,pE=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),l=dE(e.headers)["content-type"]||"";if(typeof e.data=="string")r.body=e.data;else if(l.includes("application/x-www-form-urlencoded")){const o=new URLSearchParams;for(const[c,f]of Object.entries(e.data||{}))o.set(c,f);r.body=o.toString()}else if(l.includes("multipart/form-data")||e.data instanceof FormData){const o=new FormData;if(e.data instanceof FormData)e.data.forEach((f,d)=>{o.append(d,f)});else for(const f of Object.keys(e.data))o.append(f,e.data[f]);r.body=o;const c=new Headers(r.headers);c.delete("content-type"),r.headers=c}else(l.includes("application/json")||typeof e.data=="object")&&(r.body=JSON.stringify(e.data));return r};class gE extends $d{async request(t){const r=pE(t,t.webFetchExtra),s=mE(t.params,t.shouldEncodeUrlParams),l=s?`${t.url}?${s}`:t.url,o=await fetch(l,r),c=o.headers.get("content-type")||"";let{responseType:f="text"}=o.ok?t:{};c.includes("application/json")&&(f="json");let d,m;switch(f){case"arraybuffer":case"blob":m=await o.blob(),d=await hE(m);break;case"json":d=await o.json();break;case"document":case"text":default:d=await o.text()}const y={};return o.headers.forEach((g,x)=>{y[x]=g}),{data:d,headers:y,status:o.status,url:o.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}ks("CapacitorHttp",{web:()=>new gE});var F0;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(F0||(F0={}));var $0;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})($0||($0={}));class yE extends $d{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}ks("SystemBars",{web:()=>new yE});const bE="modulepreload",xE=function(e){return"/"+e},V0={},Vd=function(t,r,s){let l=Promise.resolve();if(r&&r.length>0){let c=function(m){return Promise.all(m.map(y=>Promise.resolve(y).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const f=document.querySelector("meta[property=csp-nonce]"),d=(f==null?void 0:f.nonce)||(f==null?void 0:f.getAttribute("nonce"));l=c(r.map(m=>{if(m=xE(m),m in V0)return;V0[m]=!0;const y=m.endsWith(".css"),g=y?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${g}`))return;const x=document.createElement("link");if(x.rel=y?"stylesheet":bE,y||(x.as="script"),x.crossOrigin="",x.href=m,d&&x.setAttribute("nonce",d),document.head.appendChild(x),y)return new Promise((v,S)=>{x.addEventListener("load",v),x.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${m}`)))})}))}function o(c){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=c,window.dispatchEvent(f),!f.defaultPrevented)throw c}return l.then(c=>{for(const f of c||[])f.status==="rejected"&&o(f.reason);return t().catch(o)})},gd=ks("App",{web:()=>Vd(()=>import("./web-CtUISUOo.js"),[]).then(e=>new e.AppWeb)}),vE=ks("Network",{web:()=>Vd(()=>import("./web-BKcnPEQL.js"),[]).then(e=>new e.NetworkWeb)}),Bu=In.isNativePlatform()?"https://app.palmier.me":"";async function Lx(e,t,r,s){const l=`${Bu}${t}`;console.log(`[API] ${e} ${l}`);const c=await fetch(l,{method:e,headers:{"Content-Type":"application/json"},body:r!=null?JSON.stringify(r):void 0});if(!c.ok){const f=await c.text();let d;try{const m=JSON.parse(f);d=m.error??m.message??f}catch{d=f}throw console.error(`[API] ${e} ${t} failed:`,c.status,d),new Error(d||`Request failed with status ${c.status}`)}return console.log(`[API] ${e} ${t} ->`,c.status),c.json()}function wE(e,t,r){return Lx("POST",e,t)}function SE(e,t){return Lx("GET",e,void 0)}const Y0=In.isNativePlatform(),zx=E.createContext(null),_E=2e3,Th=6e3,kE=1500,EE=6e4;function CE({children:e,activeHost:t}){const[r,s]=E.useState(null),[l,o]=E.useState(!1),c=E.useRef(null),[f,d]=E.useState(!1),[m,y]=E.useState(!1),[g,x]=E.useState(!1),[v,S]=E.useState(!1),j=E.useRef(Ru()),D=E.useRef(new Set),R=E.useRef(0),O=!!t.directUrl,F=Y0&&!O&&!!t.lanUrl&&v,ue=m||g?"disconnected":O?f?"direct":"connecting":l?F?"lan":"nats":"connecting",H=ue!=="connecting"&&ue!=="disconnected";E.useEffect(()=>{if(!Y0||O||!t.lanUrl){S(!1);return}let G=!1;const B=t.lanUrl,z=t.hostId;async function K(){console.log("[HOST/LAN] probing",B);try{const te=await fetch(`${B}/health`,{signal:AbortSignal.timeout(kE)});if(G)return;if(!te.ok){console.log("[HOST/LAN] probe got non-ok:",te.status),S(!1);return}const V=await te.json(),X=V.hostId===z;X?console.log("[HOST/LAN] reachable"):console.log("[HOST/LAN] hostId mismatch — got:",V.hostId,"expected:",z),S(X)}catch(te){G||(console.log("[HOST/LAN] probe failed:",te instanceof Error?te.message:te),S(!1))}}K();const I=window.setInterval(K,EE),oe=gd.addListener("appStateChange",te=>{te.isActive&&K()}),ee=vE.addListener("networkStatusChange",()=>K());return()=>{G=!0,clearInterval(I),oe.then(te=>te.remove()),ee.then(te=>te.remove())}},[t.hostId,t.lanUrl,O]),E.useEffect(()=>{if(O){c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),o(!1));return}let G=!1,B=1e3;const z=3e4;async function K(){for(;!G;)try{const I=await fetch(`${Bu}/api/nats-credentials/${t.hostId}`);if(G)return;if(I.status===401||I.status===403||I.status===404){console.error("[NATS] Host not found or rejected by relay:",I.status),x(!0);return}if(!I.ok)throw new Error(`credentials fetch ${I.status}`);const oe=await I.json();if(!oe.natsWsUrl){console.error("[NATS] Relay returned empty natsWsUrl — treating as terminal"),x(!0);return}if(G)return;console.log("[NATS] Connecting to",oe.natsWsUrl);const ee=await Dx({servers:oe.natsWsUrl,authenticator:Ex(oe.natsJwt,new TextEncoder().encode(oe.natsNkeySeed)),pingInterval:3e4,maxPingOut:2});if(G){ee.close().catch(()=>{});return}if(console.log("[NATS] Connected"),c.current=ee,s(ee),o(!0),B=1e3,await ee.closed(),G)return;console.log("[NATS] Connection closed, will reconnect"),c.current=null,s(null),o(!1)}catch(I){if(G)return;console.warn(`[NATS] Connect failed, retrying in ${B}ms:`,I),o(!1),await new Promise(oe=>setTimeout(oe,B)),B=Math.min(B*2,z)}}return K(),()=>{G=!0,c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),o(!1))}},[O,t]),E.useEffect(()=>{if(O)return;const G=gd.addListener("appStateChange",B=>{if(!B.isActive||!c.current)return;const z=c.current;Promise.race([z.flush(),new Promise((K,I)=>setTimeout(()=>I(new Error("ping timeout")),2e3))]).catch(()=>{console.log("[NATS] Resume probe failed — cycling conn"),z.close().catch(()=>{})})});return()=>{G.then(B=>B.remove())}},[O]),E.useEffect(()=>{if(!O){d(!1);return}const G=new AbortController;async function B(){var oe;const K=new AbortController,I=setTimeout(()=>K.abort(),_E);G.signal.addEventListener("abort",()=>K.abort());try{const ee=await fetch(`${t.directUrl}/events`,{headers:{Authorization:`Bearer ${t.clientToken}`},signal:K.signal});return clearTimeout(I),ee.ok?((oe=ee.body)==null?void 0:oe.getReader())??null:null}catch{return clearTimeout(I),null}}async function z(K){d(!0),console.log("[HOST] SSE connected to",t.directUrl),R.current=Date.now();function I(){setTimeout(()=>{G.signal.aborted||Date.now()-R.current<Th||(console.log("[HOST] Heartbeat timeout — no data for",Th/1e3,"s"),G.abort(),d(!1),console.log("[HOST] Direct host unreachable"))},Th)}I();const oe=new TextDecoder;let ee="";try{for(;;){const{done:te,value:V}=await K.read();if(te)break;ee+=oe.decode(V,{stream:!0}),R.current=Date.now(),I();const X=ee.split(`
88
88
  `);ee=X.pop()??"";for(const ge of X)if(ge.startsWith("data: ")){const we=ge.slice(6);try{const C=JSON.parse(we);if(C.task_id&&C.event_type){const L=`host-event.${t.hostId}.${C.task_id}`;for(const J of D.current)J({subject:L,data:j.current.encode(we)})}}catch{}}}}catch{}}return(async()=>{const K=await B();K&&await z(K)})(),()=>{G.abort(),d(!1)}},[t,O]);const P=E.useCallback(async(G,B,z)=>{function K(ee){ee&&typeof ee=="object"&&ee.error==="Unauthorized"&&y(!0)}async function I(ee,te){console.log(`[HOST/${te}] → ${G}`,B??"");const V=await fetch(`${ee}/rpc/${G}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.clientToken}`},body:B!=null?JSON.stringify(B):void 0,signal:z!=null&&z.timeout?AbortSignal.timeout(z.timeout):void 0});if(V.status===401)throw y(!0),new Error("Unauthorized");const X=await V.json();return K(X),console.log(`[HOST/${te}] ← ${G}`,X),X}async function oe(){if(!c.current)throw new Error("Not connected");const ee=`host.${t.hostId}.rpc.${G}`,te={...B??{},clientToken:t.clientToken},V=j.current.encode(JSON.stringify(te));console.log(`[HOST/NATS] → ${G}`,B??"");const X=await c.current.request(ee,V,{timeout:(z==null?void 0:z.timeout)??1e4}),ge=JSON.parse(j.current.decode(X.data));return K(ge),console.log(`[HOST/NATS] ← ${G}`,ge),ge}if(O)return I(t.directUrl,"HTTP");if(F&&t.lanUrl)try{return await I(t.lanUrl,"LAN")}catch(ee){if(ee instanceof Error&&ee.message==="Unauthorized")throw ee;console.log("[HOST/LAN] failed, falling back to NATS:",ee),S(!1)}return oe()},[t,O,F]),W=E.useCallback((G,B)=>{if(O)return D.current.add(B),()=>{D.current.delete(B)};if(c.current){const z=c.current.subscribe(`host-event.${G}.>`);let K=!1;return(async()=>{try{for await(const I of z){if(K)break;B({subject:I.subject,data:I.data})}}catch{}})(),()=>{K=!0,z.unsubscribe()}}return()=>{}},[t,O]);return b.jsx(zx.Provider,{value:{connected:H,mode:ue,nc:r,request:P,subscribeEvents:W,activeHost:t,unauthorized:m},children:e})}function bi(){const e=E.useContext(zx);if(!e)throw new Error("useHostConnection must be used within HostConnectionProvider");return e}const kn=In.isNativePlatform()?ks("Device"):null;function AE(e,t){const r=new Date(e),s=new Date,l={year:"numeric",month:"2-digit",day:"2-digit",timeZone:t};return r.toLocaleDateString(void 0,l)===s.toLocaleDateString(void 0,l)?new Intl.DateTimeFormat(void 0,{timeStyle:"short",timeZone:t}).format(r):new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short",timeZone:t}).format(r)}function Yd(){const{activeHost:e}=bi(),t=e.timezone;return E.useCallback(r=>AE(r,t),[t])}function jE(e){const t=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date),r=s=>{var l;return((l=t.find(o=>o.type===s))==null?void 0:l.value)??""};return{date:`${r("year")}-${r("month")}-${r("day")}`,time:`${r("hour")}:${r("minute")}`}}function NE(e){const t=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date),r=s=>{var l;return Number(((l=t.find(o=>o.type===s))==null?void 0:l.value)??"0")};return{year:r("year"),month:r("month"),day:r("day"),hour:r("hour")%24,minute:r("minute")}}function TE(e,t,r){return new Date(Date.UTC(e,t-1,r)).getUTCDay()}function OE(e,t){return new Date(Date.UTC(e,t,0)).getUTCDate()}function G0(e,t){const r=new Date(Date.UTC(e.year,e.month-1,e.day));return r.setUTCDate(r.getUTCDate()+t),{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:e.hour,minute:e.minute}}function Dl(e,t){return e.year!==t.year?e.year-t.year:e.month!==t.month?e.month-t.month:e.day!==t.day?e.day-t.day:e.hour!==t.hour?e.hour-t.hour:e.minute-t.minute}function RE(e,t){const r=Date.UTC(e.year,e.month-1,e.day,e.hour,e.minute);if(!t)return r;const s=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(r)),l=c=>{var f;return Number(((f=s.find(d=>d.type===c))==null?void 0:f.value)??"0")},o=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")%24,l("minute"),l("second"));return r-(o-r)}function ME(e,t){const r=e.split(" ");if(r.length!==5)return null;const[s,l,o,,c]=r;if(l==="*"){const y=Number(s);if(Number.isNaN(y))return null;if(y>t.minute)return{...t,minute:y};const g=new Date(Date.UTC(t.year,t.month-1,t.day,t.hour+1,y));return{year:g.getUTCFullYear(),month:g.getUTCMonth()+1,day:g.getUTCDate(),hour:g.getUTCHours(),minute:g.getUTCMinutes()}}const f=Number(s),d=Number(l);if(Number.isNaN(f)||Number.isNaN(d))return null;if(c!=="*"){const y=Number(c);if(Number.isNaN(y))return null;for(let g=0;g<8;g++){const x=G0({...t,hour:d,minute:f},g);if(TE(x.year,x.month,x.day)===y&&Dl(x,t)>0)return x}return null}if(o!=="*"){const y=Number(o);if(Number.isNaN(y))return null;let g=t.year,x=t.month;for(let v=0;v<24;v++){if(y<=OE(g,x)){const S={year:g,month:x,day:y,hour:d,minute:f};if(Dl(S,t)>0)return S}x++,x>12&&(x=1,g++)}return null}const m={...t,hour:d,minute:f};return Dl(m,t)>0?m:G0(m,1)}function DE(e){const t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(e);return t?{year:Number(t[1]),month:Number(t[2]),day:Number(t[3]),hour:Number(t[4]),minute:Number(t[5])}:null}function LE(e,t,r){if(!e||!t||t.length===0||e==="on_new_notification"||e==="on_new_sms")return null;const s=NE(r),l=[];for(const o of t)if(e==="specific_times"){const c=DE(o);c&&Dl(c,s)>0&&l.push(c)}else{const c=ME(o,s);c&&l.push(c)}return l.length===0?null:(l.sort(Dl),RE(l[0],r))}const Ux={};function zE(e){for(const t of e)Ux[t.key]=t.label}function yd(e){return Ux[e]??e}const UE=()=>window.matchMedia("(max-width: 600px)").matches;function PE({task:e,lastEvent:t,onEdit:r,onDelete:s,onViewRun:l}){var V;const{request:o,activeHost:c}=bi(),f=Yd(),d=c.timezone,[m,y]=E.useState(!1),[g,x]=E.useState(!1),[v,S]=E.useState(!1),j=E.useRef(null),D=(t==null?void 0:t.running_state)==="started",R=(((V=e.schedule_values)==null?void 0:V.length)??0)>0,O=e.schedule_type==="on_new_notification"||e.schedule_type==="on_new_sms",F=!!e.command,ue=!!e.schedule_type&&(R||O)||F,P=!!e.schedule_enabled&&ue?D?"var(--color-success)":(t==null?void 0:t.running_state)==="failed"?"var(--color-error)":"var(--color-success)":"var(--color-text-secondary)";E.useEffect(()=>{if(!g)return;function X(ge){j.current&&!j.current.contains(ge.target)&&x(!1)}return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[g]);function W(){UE()?S(!0):x(X=>!X)}function G(){x(!1),S(!1)}async function B(){if(G(),!!confirm("Abort this task?")){y(!0);try{await o("task.abort",{id:e.id})}catch(X){console.error("Abort failed:",X)}finally{y(!1)}}}async function z(){G();try{const X=await o("task.run",{id:e.id});l(e.id,X.run_id)}catch(X){console.error("Run failed:",X)}}async function K(){if(G(),!!confirm("Delete this task? Results and reports will be kept."))try{await o("task.delete",{id:e.id}),s(e.id)}catch(X){console.error("Delete failed:",X)}}const I={started:"Started",finished:"Finished",aborted:"Aborted",failed:"Failed",needs_input:"Needs input"};function oe(){if(F)return"On Command Output";if(e.schedule_type==="on_new_notification")return"On new notification";if(e.schedule_type==="on_new_sms")return"On new SMS";const X=LE(e.schedule_type,e.schedule_values,d);return X===null?"No upcoming runs":`Next: ${f(X)}`}const ee=oe(),te=b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:()=>{G(),r(e)},children:[b.jsx("span",{className:"menu-icon",children:"✎"}),"Edit"]}),b.jsxs("button",{onClick:()=>{G(),l(e.id)},children:[b.jsx("span",{className:"menu-icon",children:"📄"}),"View All Runs"]}),D?b.jsxs("button",{className:"menu-item-danger",onClick:B,disabled:m,children:[b.jsx("span",{className:"menu-icon",children:"◼"}),"Abort"]}):b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:z,children:[b.jsx("span",{className:"menu-icon",children:"▶"}),"Run Now"]}),b.jsxs("button",{className:"menu-item-danger",onClick:K,children:[b.jsx("span",{className:"menu-icon",children:"🗑"}),"Delete"]})]})]});return b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"task-card",onClick:()=>l(e.id,D?"latest":void 0),children:[b.jsxs("div",{className:"task-card-header",children:[b.jsxs("div",{className:"task-card-title-row",children:[D?b.jsx("span",{className:"status-spinner",children:b.jsx("span",{})}):b.jsx("span",{className:"status-dot",style:{backgroundColor:P}}),b.jsx("h3",{className:"task-card-name",children:e.custom_name||e.name||e.user_prompt})]}),b.jsx("div",{className:"task-card-actions",onClick:X=>X.stopPropagation(),children:b.jsxs("div",{className:"task-card-menu",ref:j,children:[b.jsx("button",{className:"task-card-menu-btn",onClick:W,"aria-label":"Task actions",children:"⋮"}),g&&b.jsx("div",{className:"task-card-menu-dropdown",children:te})]})})]}),b.jsxs("div",{className:"task-card-meta",children:[e.agent&&b.jsx("span",{className:"task-card-agent",children:yd(e.agent)}),t&&I[t.running_state]&&b.jsxs("span",{className:"task-card-last-event",children:[I[t.running_state]," ",f(t.time_stamp)]}),ue&&b.jsx("span",{className:"task-card-triggers",children:e.schedule_enabled?ee:"Schedule disabled"})]})]}),v&&mi.createPortal(b.jsx("div",{className:"bottom-sheet-overlay",onClick:()=>S(!1),children:b.jsxs("div",{className:"bottom-sheet",onClick:X=>X.stopPropagation(),children:[b.jsx("div",{className:"bottom-sheet-handle"}),b.jsx("div",{className:"bottom-sheet-title",children:e.custom_name||e.name||e.user_prompt}),b.jsx("div",{className:"bottom-sheet-actions",children:te})]})}),document.body)]})}const ua=[];function BE(){const e=ua.pop();e&&(e.pushed.current=!1,e.close())}let J0=!1;function HE(){J0||(J0=!0,window.addEventListener("popstate",BE))}function Px(e,t){const r=E.useRef(!1),s=E.useRef(t);s.current=t;const l=E.useCallback(()=>s.current(),[]),o=E.useRef({close:l,pushed:r});o.current.close=l,E.useEffect(()=>{if(e&&!r.current)HE(),history.pushState({modal:!0},""),ua.push(o.current),r.current=!0;else if(!e&&r.current){r.current=!1;const c=ua.indexOf(o.current);c!==-1&&ua.splice(c,1),history.back()}},[e,l]),E.useEffect(()=>{const c=o.current;return()=>{if(r.current){r.current=!1;const f=ua.indexOf(c);f!==-1&&ua.splice(f,1),history.back()}}},[])}const qE=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],IE=["specific_times","hourly","daily","weekly","monthly"];function pu(e){return IE.includes(e)}function FE(e){return e==="on_new_notification"||e==="on_new_sms"}function di(e="daily"){return{schedule:e,time:"00:00",dayOfWeek:"1",dayOfMonth:"1",onceDate:"",onceTime:"00:00"}}function $E(e){const t=e.split(" ");if(t.length!==5)return di();const[r,s,l,,o]=t;if(s==="*")return di("hourly");const c=`${s.padStart(2,"0")}:${r.padStart(2,"0")}`;return o!=="*"?{...di("weekly"),time:c,dayOfWeek:o}:l!=="*"?{...di("monthly"),time:c,dayOfMonth:l}:{...di("daily"),time:c}}function Bx(e,t){if(e==="specific_times"){const[r,s]=t.split("T");return{...di("specific_times"),onceDate:r??"",onceTime:(s??"09:00").slice(0,5)}}return $E(t)}function VE(e){const[t,r]=e.time.split(":").map(Number);switch(e.schedule){case"hourly":return"0 * * * *";case"daily":return`${r} ${t} * * *`;case"weekly":return`${r} ${t} * * ${e.dayOfWeek}`;case"monthly":return`${r} ${t} ${e.dayOfMonth} * *`;default:return"0 * * * *"}}function YE(e){return e.schedule==="specific_times"?e.onceDate?`${e.onceDate}T${e.onceTime}`:null:VE(e)}function Oh(e){return e==="specific_times"?"specific_times":e==="on_new_notification"?"on_new_notification":e==="on_new_sms"?"on_new_sms":"crons"}function Rh(e){var s;if(!e)return"daily";if(e.command)return"command";const t=e.schedule_type;if(t==="on_new_notification"||t==="on_new_sms")return t;if(t!=="crons"&&t!=="specific_times")return"ondemand";const r=(s=e.schedule_values)==null?void 0:s[0];return r?Bx(t,r).schedule:"ondemand"}function GE({initial:e,agents:t,hostPlatform:r,isNotificationListener:s,onSaved:l,onCancel:o}){const{request:c,activeHost:f}=bi(),{setHostLastAgent:d}=Wi(),m=()=>{var Ae;const xe=f.lastAgent,Fe=t.map(Ge=>Ge.key);return xe&&Fe.includes(xe)?xe:((Ae=t[0])==null?void 0:Ae.key)??""},[y,g]=E.useState((e==null?void 0:e.custom_name)??""),[x,v]=E.useState((e==null?void 0:e.user_prompt)??""),[S,j]=E.useState((e==null?void 0:e.agent)??m()),[D,R]=E.useState(null),[O,F]=E.useState(()=>Rh(e)),[ue,H]=E.useState(()=>{const xe=e==null?void 0:e.schedule_type,Fe=e==null?void 0:e.schedule_values;if(Fe&&(xe==="crons"||xe==="specific_times"))return Fe.map(Ge=>Bx(xe,Ge));const Ae=Rh(e);return pu(Ae)?[di(Ae)]:[]}),[P,W]=E.useState((e==null?void 0:e.requires_confirmation)??!1),[G,B]=E.useState(e!=null&&e.schedule_type||e!=null&&e.command?e.schedule_enabled??!0:!0),[z,K]=E.useState((e==null?void 0:e.foreground_mode)??!1),[I,oe]=E.useState((e==null?void 0:e.command)??""),[ee,te]=E.useState(!1),V=(e==null?void 0:e.schedule_type)==="on_new_notification"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[X,ge]=E.useState(V),[we,C]=E.useState([]),[L,J]=E.useState(!1),[N,ve]=E.useState(!1),[Ce,ke]=E.useState(""),je=E.useCallback(()=>ve(!1),[]);Px(N,je),E.useEffect(()=>{if(O!=="on_new_notification"||!s||!In.isNativePlatform()||!kn)return;let xe=!1;return J(!0),kn.getInstalledApps().then(({apps:Fe})=>{if(xe)return;const Ae="com.palmier.app",Ge=Fe.filter(gt=>gt.packageName!==Ae).sort((gt,dt)=>(gt.appName||gt.packageName).localeCompare(dt.appName||dt.packageName));C(Ge)}).catch(()=>{}).finally(()=>{xe||J(!1)}),()=>{xe=!0}},[O,s]);const Ve=(e==null?void 0:e.schedule_type)==="on_new_sms"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[ae,De]=E.useState(Ve),rt=E.useRef(null),ct=pu(O),Kt=O==="command",Dt=FE(O),tn=O==="specific_times"||O==="daily"||O==="weekly"||O==="monthly",$t=t.find(xe=>xe.key===S),nn=!!e,Ye=Rh(e),ft=nn&&y.trim()!==((e==null?void 0:e.custom_name)??""),ht=!nn||ft||x!==((e==null?void 0:e.user_prompt)??"")||S!==((e==null?void 0:e.agent)??"")||O!==Ye||P!==((e==null?void 0:e.requires_confirmation)??!1)||G!==(e!=null&&e.schedule_type||e!=null&&e.command?e.schedule_enabled??!0:!0)||z!==((e==null?void 0:e.foreground_mode)??!1)||Kt&&I!==((e==null?void 0:e.command)??"")||ct&&(JSON.stringify(Me())!==JSON.stringify((e==null?void 0:e.schedule_values)??[])||Oh(O)!==((e==null?void 0:e.schedule_type)??void 0))||Dt&&O!==(e==null?void 0:e.schedule_type)||O==="on_new_notification"&&X.trim()!==V.trim()||O==="on_new_sms"&&ae.trim()!==Ve.trim(),xt=jE(f.timezone),Yt=ct&&ue.some(xe=>xe.schedule==="specific_times"&&(!xe.onceDate||xe.onceDate<xt.date||xe.onceDate===xt.date&&(xe.onceTime??"")<=xt.time)),An=ht&&!!x.trim()&&!Yt&&(!Kt||!!I.trim())&&(!ct||ue.length>0);function lt(xe,Fe){H(Ae=>Ae.map((Ge,gt)=>gt===xe?{...Ge,...Fe}:Ge))}function $n(xe){H(Fe=>Fe.filter((Ae,Ge)=>Ge!==xe))}function ce(){pu(O)&&H(xe=>[...xe,xe.length>0?{...xe[xe.length-1]}:di(O)])}function _e(xe){F(xe),pu(xe)?H([di(xe)]):(H([]),W(!1)),xe==="command"?setTimeout(()=>{var Fe;return(Fe=rt.current)==null?void 0:Fe.focus()},0):oe(""),xe!=="on_new_notification"&&ge(V),xe!=="on_new_sms"&&De(Ve)}function Me(){return ue.flatMap(xe=>{const Fe=YE(xe);return Fe?[Fe]:[]})}async function Xe(){te(!0),R(null);try{const xe=ct?Me():O==="on_new_notification"&&X.trim()?[X.trim()]:O==="on_new_sms"&&ae.trim()?[ae.trim()]:[],Fe=ct||Dt?Oh(O):null,Ae={user_prompt:x,agent:S,schedule_type:Fe,schedule_values:xe.length>0?xe:null,schedule_enabled:O==="ondemand"?!0:G,requires_confirmation:ct?P:!1,foreground_mode:z,command:Kt?I:""};nn&&(Ae.id=e.id,ft&&(Ae.custom_name=y.trim()));const gt=await c(nn?"task.update":"task.create",Ae,{timeout:45e3});if(gt.error){R(gt.error);return}nn||d(f.hostId,S),l(gt)}catch(xe){R(xe instanceof Error?xe.message:String(xe))}finally{te(!1)}}const We=nn?"Save":(ct||Dt||Kt)&&G?"Schedule":"Save";return b.jsxs("div",{className:"task-form-overlay",children:[b.jsxs("div",{className:"task-form",children:[b.jsx("div",{className:"task-form-header",children:b.jsx("h2",{children:e?"Edit Task":"New Task"})}),D&&b.jsx("div",{className:"form-error",children:D}),nn&&b.jsxs("div",{children:[b.jsxs("label",{className:"form-label task-title-field",children:["Title",b.jsx("input",{className:"form-input",type:"text",value:y,onChange:xe=>g(xe.target.value),placeholder:e.name,maxLength:80,disabled:ee})]}),b.jsx("p",{className:"command-help-text task-title-help",children:"Leave empty to use an auto-generated title."})]}),b.jsx("textarea",{autoFocus:!e,className:"form-textarea",value:x,onChange:xe=>v(xe.target.value),placeholder:Kt?"If the input email contains an event, create a calendar entry for it.":"Research today's top AI news and write a summary.",rows:4,disabled:ee}),b.jsx("div",{className:"plan-actions",children:t.length>0&&b.jsx("div",{className:"agent-picker-section-inline",children:t.length>1?b.jsx("select",{className:"form-select form-select-sm",value:S,onChange:xe=>j(xe.target.value),disabled:ee,children:t.map(xe=>b.jsx("option",{value:xe.key,children:xe.label},xe.key))}):b.jsx("span",{className:"agent-picker-single",children:($t==null?void 0:$t.label)??t[0].label})})}),b.jsx("div",{className:"toggles-group",children:b.jsxs("div",{className:"schedule-section",children:[b.jsxs("h3",{className:"schedule-section-title",children:["Schedule ",tn&&b.jsx("span",{className:"schedule-section-hint",children:"based on host time"})]}),b.jsxs("select",{className:"form-select",value:O,onChange:xe=>_e(xe.target.value),disabled:ee,children:[b.jsx("option",{value:"ondemand",children:"On User Demand"}),b.jsx("option",{value:"specific_times",children:"Specific Times"}),b.jsx("option",{value:"hourly",children:"Hourly"}),b.jsx("option",{value:"daily",children:"Daily"}),b.jsx("option",{value:"weekly",children:"Weekly"}),b.jsx("option",{value:"monthly",children:"Monthly"}),b.jsx("option",{value:"on_new_notification",children:"On New Notification"}),b.jsx("option",{value:"on_new_sms",children:"On New SMS"}),b.jsx("option",{value:"command",children:"On Command Output"})]}),Dt&&b.jsxs("div",{className:"schedule-reactive",children:[b.jsxs("p",{className:"command-help-text",children:[O==="on_new_notification"?"Runs each time a new push notification arrives on the paired Android device.":"Runs each time a new SMS arrives on the paired Android device."," ","The triggering payload is spliced into your task prompt — reference it as “the new ",O==="on_new_notification"?"notification":"SMS","”."]}),O==="on_new_notification"&&(()=>{const xe=we.find(Ae=>Ae.packageName===X),Fe=(xe==null?void 0:xe.appName)||X;return b.jsxs(b.Fragment,{children:[s?X.trim()?b.jsxs("div",{className:"app-filter-selected",children:[b.jsx("span",{className:"app-filter-selected-name",children:Fe}),(xe==null?void 0:xe.appName)&&b.jsx("span",{className:"app-filter-selected-pkg",children:xe.packageName}),b.jsx("button",{type:"button",className:"app-filter-selected-clear",onClick:()=>ge(""),"aria-label":"Clear app filter",disabled:ee,children:"✕"})]}):b.jsx("button",{type:"button",className:"btn btn-link app-filter-trigger",onClick:()=>{ke(""),ve(!0)},disabled:ee,children:"Select app"}):b.jsx("input",{className:"form-input",type:"text",value:X,onChange:Ae=>ge(Ae.target.value),placeholder:"App (optional), e.g. com.google.android.gm",disabled:ee}),b.jsx("p",{className:"command-help-text app-filter-help",children:X.trim()?`Only notifications from ${Fe} will trigger this task.`:"Every notification from your device triggers this task."})]})})(),O==="on_new_sms"&&b.jsxs(b.Fragment,{children:[b.jsx("input",{className:"form-input",type:"text",value:ae,onChange:xe=>De(xe.target.value),placeholder:"From (optional), e.g. +1 555-1234)",disabled:ee}),b.jsx("p",{className:"command-help-text app-filter-help",children:ae.trim()?`Only SMS from ${ae.trim()} will trigger this task. Formatting (spaces, dashes, parens) is ignored.`:"Every SMS that arrives on your device triggers this task."})]})]}),Kt&&b.jsxs("div",{className:"schedule-reactive",children:[b.jsx("p",{className:"command-help-text",children:"Runs a command and invokes the task for each line of output. Use “the input” in your task description to reference each line."}),b.jsx("input",{ref:rt,className:"form-input form-input-mono",type:"text",value:I,onChange:xe=>oe(xe.target.value),placeholder:"gws gmail +watch --project my-project",disabled:ee})]}),ct&&O!=="hourly"&&b.jsxs(b.Fragment,{children:[ue.map((xe,Fe)=>b.jsxs("div",{className:"trigger-row-card",children:[b.jsxs("div",{className:"trigger-row-content",children:[O==="daily"&&b.jsx("input",{className:"form-input",type:"time",value:xe.time,onChange:Ae=>lt(Fe,{time:Ae.target.value})}),O==="weekly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:xe.dayOfWeek,onChange:Ae=>lt(Fe,{dayOfWeek:Ae.target.value}),children:qE.map((Ae,Ge)=>b.jsx("option",{value:String(Ge),children:Ae},Ge))}),b.jsx("input",{className:"form-input",type:"time",value:xe.time,onChange:Ae=>lt(Fe,{time:Ae.target.value})})]}),O==="monthly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:xe.dayOfMonth,onChange:Ae=>lt(Fe,{dayOfMonth:Ae.target.value}),children:Array.from({length:28},(Ae,Ge)=>Ge+1).map(Ae=>b.jsxs("option",{value:String(Ae),children:["Day ",Ae]},Ae))}),b.jsx("input",{className:"form-input",type:"time",value:xe.time,onChange:Ae=>lt(Fe,{time:Ae.target.value})})]}),O==="specific_times"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("input",{className:"form-input",type:"date",value:xe.onceDate,min:xt.date,onChange:Ae=>lt(Fe,{onceDate:Ae.target.value})}),b.jsx("input",{className:"form-input",type:"time",value:xe.onceTime,min:xe.onceDate===xt.date?xt.time:void 0,onChange:Ae=>lt(Fe,{onceTime:Ae.target.value})})]})]}),ue.length>1&&b.jsx("button",{className:"trigger-remove-btn",onClick:()=>$n(Fe),title:"Remove trigger",children:"×"})]},Fe)),b.jsx("button",{className:"trigger-add-btn",onClick:ce,children:"+ Add"})]}),r==="win32"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:z,onChange:xe=>K(xe.target.checked),disabled:ee}),"Run in the foreground (host must login to Windows)"]}),ct&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:P,onChange:xe=>W(xe.target.checked),disabled:ee}),"Confirm before each run"]}),O!=="ondemand"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:G,onChange:xe=>B(xe.target.checked),disabled:ee}),"Enabled"]})]})}),b.jsxs("div",{className:"form-actions",children:[b.jsxs("button",{className:"btn btn-primary",onClick:Xe,disabled:!An||ee,children:[ee&&b.jsx("span",{className:"btn-spinner"}),We]}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{ht&&x.trim()&&!confirm("You have unsaved changes. Discard?")||o()},style:{marginLeft:"auto"},children:"Cancel"})]})]}),N&&(()=>{const xe=Ce.trim().toLowerCase(),Fe=xe?we.filter(Ae=>Ae.packageName.toLowerCase().includes(xe)||Ae.appName.toLowerCase().includes(xe)):we;return b.jsx("div",{className:"app-filter-overlay",onClick:je,children:b.jsxs("div",{className:"app-filter-dialog",onClick:Ae=>Ae.stopPropagation(),children:[b.jsxs("div",{className:"app-filter-header",children:[b.jsx("h2",{children:"Select app"}),b.jsx("button",{className:"app-filter-close",onClick:je,"aria-label":"Close",children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:b.jsx("path",{d:"M4 4L12 12M12 4L4 12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]}),b.jsx("input",{className:"form-input app-filter-search",type:"text",value:Ce,onChange:Ae=>ke(Ae.target.value),onKeyDown:Ae=>{Ae.key==="Enter"&&Ce.trim()&&(ge(Ce.trim()),je())},placeholder:"Search or type a package name",autoFocus:!0}),b.jsxs("ul",{className:"app-filter-list",children:[L&&we.length===0?Array.from({length:6}).map((Ae,Ge)=>b.jsx("li",{className:"app-filter-row app-filter-skeleton",children:b.jsx("div",{className:"app-filter-skeleton-bar"})},`sk-${Ge}`)):Fe.length===0&&!Ce.trim()?b.jsx("li",{className:"app-filter-empty",children:"No apps"}):Fe.map(Ae=>b.jsx("li",{className:"app-filter-row",onClick:()=>{ge(Ae.packageName),je()},children:b.jsxs("div",{className:"app-filter-row-labels",children:[b.jsx("div",{className:"app-filter-row-name",children:Ae.appName||Ae.packageName}),Ae.appName&&b.jsx("div",{className:"app-filter-row-pkg",children:Ae.packageName})]})},Ae.packageName)),Ce.trim()&&b.jsx("li",{className:"app-filter-row",onClick:()=>{ge(Ce.trim()),je()},children:b.jsx("div",{className:"app-filter-row-labels",children:b.jsx("div",{className:"app-filter-row-name",children:Ce.trim()})})})]})]})})})()]})}function Hx({pullDistance:e,refreshing:t,threshold:r}){const s=e>0||t,l=e>=r;return b.jsx("div",{className:"pull-to-refresh",style:{transform:`translateY(${e}px)`,opacity:s?Math.min(1,e/30):0},"aria-hidden":!s,children:b.jsx("div",{className:"pull-to-refresh-badge",children:t?b.jsx("div",{className:"spinner"}):b.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.25",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:l?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"},children:[b.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),b.jsx("polyline",{points:"19 12 12 19 5 12"})]})})})}function qx({onRefresh:e,threshold:t=70,maxPull:r=110,enabled:s=!0}){const[l,o]=E.useState(0),[c,f]=E.useState(!1),d=E.useRef(null),m=E.useRef(!1),y=E.useRef(0),g=E.useRef(!1),x=E.useRef(e);return E.useEffect(()=>{x.current=e}),E.useEffect(()=>{if(!s)return;const v=D=>{if(g.current||window.scrollY>0){d.current=null;return}if(JE(D.target)){d.current=null;return}d.current=D.touches[0].clientY,m.current=!1,y.current=0},S=D=>{if(g.current||d.current==null)return;const R=D.touches[0].clientY-d.current;if(R<=0){m.current=!1,y.current=0,o(0);return}m.current=!0;const O=Math.min(r,R*.5);y.current=O,o(O),D.cancelable&&D.preventDefault()},j=()=>{if(!m.current){d.current=null,o(0);return}const D=y.current;d.current=null,m.current=!1,y.current=0,D>=t?(g.current=!0,f(!0),o(t),Promise.resolve(x.current()).catch(()=>{}).finally(()=>{g.current=!1,f(!1),o(0)})):o(0)};return window.addEventListener("touchstart",v,{passive:!0}),window.addEventListener("touchmove",S,{passive:!1}),window.addEventListener("touchend",j,{passive:!0}),window.addEventListener("touchcancel",j,{passive:!0}),()=>{window.removeEventListener("touchstart",v),window.removeEventListener("touchmove",S),window.removeEventListener("touchend",j),window.removeEventListener("touchcancel",j)}},[s,t,r]),{pullDistance:l,refreshing:c,threshold:t}}function JE(e){let t=e;for(;t&&t!==document.body&&t!==document.documentElement;){const r=window.getComputedStyle(t).overflowY;if((r==="auto"||r==="scroll")&&t.scrollHeight>t.clientHeight)return!0;t=t.parentElement}return!1}function XE(e){return JSON.stringify([e.user_prompt,e.agent??null,e.schedule_type??null,e.schedule_values??null,e.schedule_enabled,e.requires_confirmation,e.foreground_mode??!1,e.command??""])}function KE({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:o,isNotificationListener:c,onViewRun:f,hostInfoStatus:d,onRetryHostInfo:m}){const[y,g]=E.useState([]),[x,v]=E.useState(!1),[S,j]=E.useState(null),[D,R]=E.useState(new Map),[O,F]=E.useState(!1),[ue,H]=E.useState(void 0),P=E.useCallback(()=>{F(!1),H(void 0)},[]),W=E.useCallback(async()=>{if(e){v(!0),j(null);try{const oe=(await r("task.list")).tasks??[],ee=new Map;for(const te of oe)te.status&&ee.set(te.id,te.status);R(ee),g(oe)}catch(I){const oe=I instanceof Error?I.message:String(I);oe==="Not connected"||oe.includes("503")||oe.toLowerCase().includes("no responders")?j(null):j(oe),g([])}finally{v(!1)}}},[e,t,r]);E.useEffect(()=>{e?W():(g([]),v(!1))},[e,t,W]);const G=E.useRef(!1);E.useEffect(()=>{d==="error"?G.current=!0:d==="ready"&&G.current&&(G.current=!1,W())},[d,W]);const B=qx({onRefresh:W,enabled:e});E.useEffect(()=>!e||!t?void 0:s(t,async oe=>{const ee=oe.subject.split(".");if(ee.length<3)return;const te=ee.slice(2).join(".");let V={};try{V=JSON.parse(new TextDecoder().decode(oe.data))}catch{return}if(V.event_type==="running-state")try{const ge=await r("task.status",{id:te},{timeout:5e3});if(ge.error)return;R(we=>{const C=new Map(we);return C.set(te,ge),C})}catch{}}),[e,t,s,r]);function z(I){g(oe=>{const ee=oe.findIndex(te=>te.id===I.id);if(ee>=0){const te=[...oe];return te[ee]=I,te}return[I,...oe]}),F(!1),H(void 0)}function K(I){g(oe=>oe.filter(ee=>ee.id!==I)),R(oe=>{const ee=new Map(oe);return ee.delete(I),ee})}return b.jsxs(b.Fragment,{children:[b.jsx(Hx,{pullDistance:B.pullDistance,refreshing:B.refreshing,threshold:B.threshold}),S&&b.jsxs("div",{className:"form-error",children:[S,S.toLowerCase().includes("failed to fetch")&&b.jsxs(b.Fragment,{children:[" ",b.jsx("a",{href:"#",onClick:I=>{I.preventDefault(),window.location.reload()},children:"Reload"})]})]}),x&&!y.length&&d==="ready"?b.jsx("div",{className:"task-list",children:[0,1,2].map(I=>b.jsxs("div",{className:"task-card",style:{pointerEvents:"none"},children:[b.jsx("div",{className:"task-card-header",children:b.jsxs("div",{className:"task-card-title-row",children:[b.jsx("div",{className:"skeleton-line",style:{width:10,height:10,borderRadius:"50%"}}),b.jsx("div",{className:"skeleton-line",style:{width:`${60+I*12}%`}})]})}),b.jsxs("div",{className:"task-card-meta",children:[b.jsx("div",{className:"skeleton-line",style:{width:"30%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"25%"}})]})]},I))}):y.length===0?d==="loading"?b.jsx("div",{className:"empty-state",children:b.jsx("p",{className:"empty-state-text",children:"Connecting to host…"})}):d==="error"?b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"Couldn't reach host"}),b.jsxs("p",{className:"empty-state-hint",children:["The host didn't respond. Retrying automatically — if this persists, run ",b.jsx("code",{children:"palmier restart"})," on the host machine."]}),b.jsx("button",{className:"btn btn-secondary",onClick:m,children:"Retry now"})]}):b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No tasks yet"}),b.jsx("p",{className:"empty-state-hint",children:"Tap the + button to create your first task."})]}):b.jsx("div",{className:"task-list",children:y.map(I=>b.jsx(PE,{task:I,lastEvent:D.get(I.id),onEdit:oe=>{H(oe),F(!0),r("task.get",{id:oe.id}).then(ee=>{ee.error||H(ee)}).catch(()=>{})},onDelete:K,onViewRun:f},I.id))}),b.jsx("button",{className:"fab",onClick:()=>{H(void 0),F(!0)},"aria-label":"New task",title:"New task",children:b.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),b.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),O&&b.jsx(GE,{initial:ue,agents:l,hostPlatform:o,isNotificationListener:c,onSaved:z,onCancel:P},ue?XE(ue):"new")]})}let ba=null;function X0(e){ba&&(e.preventDefault(),e.returnValue="")}function Mh(e){const t=!!ba;ba=e;const r=!!ba;r&&!t?window.addEventListener("beforeunload",X0):!r&&t&&window.removeEventListener("beforeunload",X0)}function Ss(){return ba?window.confirm(ba):!0}function QE(){const e=Fr(),t=vr(),{hostId:r}=Yu(),s=t.pathname.endsWith("/tasks"),l=!s;function o(c){Ss()&&r&&e(`/hosts/${encodeURIComponent(r)}${c}`)}return b.jsxs(b.Fragment,{children:[b.jsxs("button",{className:`tab-btn ${l?"tab-btn-active":""}`,onClick:()=>o(""),children:[b.jsx("svg",{className:"tab-icon",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M2 8H4.5L6 4L8 12L10 6L11.5 8H14"})}),"Sessions"]}),b.jsxs("button",{className:`tab-btn ${s?"tab-btn-active":""}`,onClick:()=>o("/tasks"),children:[b.jsxs("svg",{className:"tab-icon",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"2"}),b.jsx("path",{d:"M5.5 8L7 9.5L10.5 6"})]}),"Tasks"]})]})}function Ix(e){const[t,r]=E.useState(()=>window.matchMedia(e).matches);return E.useEffect(()=>{const s=window.matchMedia(e),l=o=>r(o.matches);return s.addEventListener("change",l),r(s.matches),()=>s.removeEventListener("change",l)},[e]),t}const Cu=In.isNativePlatform(),ZE=["Device","Data","Messaging"],WE=[{capability:"sms-read",label:"Read SMS",group:"Messaging"},{capability:"sms-send",label:"Send SMS",group:"Messaging"},{capability:"send-email",label:"Prompt Email to Send",group:"Messaging"},{capability:"notifications",label:"Notifications from Other Apps",group:"Data"},{capability:"contacts",label:"Manage Contacts",group:"Data"},{capability:"calendar",label:"Manage Calendar",group:"Data"},{capability:"location",label:"Get Location",group:"Device"},{capability:"dnd",label:"Set Ringer Mode",group:"Device"},{capability:"alarm",label:"Trigger Alarms",group:"Device"}];async function eC(){if(!Cu||!kn)return new Set;try{const{capabilities:e}=await kn.getCapabilityStatus();return new Set(e.filter(t=>t.enabled).map(t=>t.name))}catch{return new Set}}function Fx({onChange:e,confirmDisable:t=!1}){const[r,s]=E.useState(new Map),[l,o]=E.useState(null),[c,f]=E.useState(null),d=E.useCallback(async()=>{if(!(!Cu||!kn))try{const{capabilities:S}=await kn.getCapabilityStatus(),j=new Map;for(const D of S)j.set(D.name,D);s(j),e==null||e(new Set(S.filter(D=>D.enabled).map(D=>D.name)))}catch(S){console.error("Failed to read capability status:",S)}},[e]);E.useEffect(()=>{d()},[d]),E.useEffect(()=>{if(!Cu)return;const S=gd.addListener("resume",d);return()=>{S.then(j=>j.remove())}},[d]);async function m(S,j){if(kn){o(S.capability);try{const D=await kn.setCapabilityEnabled({capability:S.capability,enabled:j});!D.enabled&&D.reason==="no-email-client"&&alert("No email app is installed on this device. Install one (e.g. Gmail) before enabling Send Email."),await d()}catch(D){console.error(`Failed to toggle ${S.capability}:`,D)}finally{o(null)}}}function y(S){const j=r.get(S.capability);if(j){if(j.enabled&&t){f(S);return}m(S,!j.enabled)}}function g(){const S=c;S&&(f(null),m(S,!1))}if(!Cu)return null;const x=ZE.map(S=>({group:S,items:WE.filter(j=>{const D=r.get(j.capability);return j.group===S&&(D==null?void 0:D.supported)})})).filter(S=>S.items.length>0);if(x.length===0)return b.jsx("div",{className:"capability-toggles-loading",children:b.jsx("span",{className:"spinner"})});const v=c&&mi.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>f(null),children:b.jsxs("div",{className:"confirm-modal",onClick:S=>S.stopPropagation(),children:[b.jsxs("h2",{className:"confirm-modal-title",children:["Disable ",c.label,"?"]}),b.jsxs("p",{className:"confirm-modal-message",children:["All hosts linked to this device will no longer be able to use ",c.label,"."]}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>f(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:g,children:"Disable"})]})]})}),document.body);return b.jsxs(b.Fragment,{children:[x.map(({group:S,items:j},D)=>b.jsx("div",{className:D>0?"drawer-toggle-group drawer-toggle-group-divided":"drawer-toggle-group",children:j.map(R=>{const O=r.get(R.capability),F=!!(O!=null&&O.enabled);return b.jsxs("label",{className:"drawer-toggle",children:[b.jsx("span",{className:"drawer-toggle-label",children:R.label}),b.jsx("button",{className:`toggle-switch ${F?"toggle-switch-on":""}`,onClick:()=>y(R),disabled:l===R.capability,role:"switch","aria-checked":F,children:b.jsx("span",{className:"toggle-switch-thumb"})})]},R.capability)})},S)),v]})}function Dh(e){return e.replace(/^https:\/\//,"")}function tC({request:e,onClose:t}){const[r,s]=E.useState(null),[l,o]=E.useState(!1),[c,f]=E.useState(null),[d,m]=E.useState(!1);E.useEffect(()=>{let x=!1;return e("passwords.list").then(v=>{x||(v.passwords?s([...v.passwords].sort((S,j)=>S.origin===j.origin?S.username.localeCompare(j.username):S.origin.localeCompare(j.origin))):o(!0))}).catch(()=>{x||o(!0)}),()=>{x=!0}},[e]);async function y(){if(!c)return;const{origin:x,username:v}=c;m(!0);try{await e("passwords.delete",{origin:x,username:v}),s(S=>(S==null?void 0:S.filter(j=>!(j.origin===x&&j.username===v)))??S),f(null)}catch(S){console.error("Failed to delete password:",S)}finally{m(!1)}}const g=c&&mi.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>{d||f(null)},children:b.jsxs("div",{className:"confirm-modal",onClick:x=>x.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Remove password?"}),b.jsxs("p",{className:"confirm-modal-message",children:["The saved password for ",b.jsx("strong",{children:c.username})," on"," ",b.jsx("strong",{children:Dh(c.origin)})," will be removed from this host."]}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>f(null),disabled:d,children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:y,disabled:d,children:d?"Removing…":"Remove"})]})]})}),document.body);return mi.createPortal(b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"confirm-modal-overlay",onClick:t,children:b.jsxs("div",{className:"confirm-modal passwords-dialog",onClick:x=>x.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Saved Passwords"}),b.jsx("div",{className:"passwords-dialog-scroll",children:l?b.jsx("p",{className:"passwords-empty",children:"Couldn't load saved passwords."}):r===null?b.jsx("p",{className:"passwords-empty",children:"Loading…"}):r.length===0?b.jsx("p",{className:"passwords-empty",children:"No saved passwords. Passwords are saved when you approve them during a task."}):b.jsx("ul",{className:"passwords-list",children:r.map(x=>b.jsxs("li",{className:"password-item",children:[b.jsxs("div",{className:"password-item-text",children:[b.jsx("span",{className:"password-item-origin",children:Dh(x.origin)}),b.jsx("span",{className:"password-item-username",children:x.username})]}),b.jsx("button",{className:"password-delete-btn",onClick:()=>f(x),"aria-label":`Remove password for ${x.username} on ${Dh(x.origin)}`,children:b.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:b.jsx("path",{d:"M4 5.5V11C4 11.2761 4.22386 11.5 4.5 11.5H9.5C9.77614 11.5 10 11.2761 10 11V5.5M3 4H11M5.5 4V3C5.5 2.72386 5.72386 2.5 6 2.5H8C8.27614 2.5 8.5 2.72386 8.5 3V4M6.5 6.5V9.5M7.5 6.5V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]},`${x.origin}
89
89
  ${x.username}`))})}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-primary",onClick:t,children:"Done"})})]})}),g]}),document.body)}const K0=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),nC=In.isNativePlatform();function Q0({daemonVersion:e,agents:t,playwrightCli:r,linkedClientToken:s,request:l,onEnabledCapabilitiesChange:o,onLinkedClientTokenChange:c}){var nn;const{pairedHosts:f,removePairedHost:d,renamePairedHost:m}=Wi(),{activeHost:y}=bi(),g=Fr(),x=vr(),S=Yu().hostId??null,j=y.clientToken||null,D=!!j&&s===j,R=Ix("(min-width: 768px)"),[O,F]=E.useState(!1),[ue,H]=E.useState(()=>Date.now());E.useEffect(()=>{const Ye=()=>H(Date.now()),ft=6e4-Date.now()%6e4,ht=setTimeout(()=>{Ye();const xt=setInterval(Ye,6e4);ht._iv=xt},ft);return()=>{const xt=ht._iv;xt&&clearInterval(xt),clearTimeout(ht)}},[]);const P=y.timezone?new Date(ue).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:y.timezone}):"";async function W(){if(!(!kn||!l||!j)){F(!0);try{const{token:Ye}=await kn.getFcmToken();if(!Ye)return;await l("device.link",{fcmToken:Ye}),c==null||c(j)}catch(Ye){console.error("Failed to make this the linked device:",Ye)}finally{F(!1)}}}async function G(Ye){const ft=Ye===S;if(ft&&l)try{await l("clients.revoke_self")}catch{}d(Ye),we(null),ft&&g("/",{replace:!0})}function B(Ye){const ht=x.pathname.endsWith("/tasks")?"/tasks":"";g(`/hosts/${encodeURIComponent(Ye)}${ht}`)}const[z,K]=E.useState(!1),[I,oe]=E.useState(!1),[ee,te]=E.useState(null),[V,X]=E.useState(""),[ge,we]=E.useState(null),[C,L]=E.useState(!1),[J,N]=E.useState(!1),ve=E.useRef(null),Ce=E.useRef(null),ke=E.useCallback(()=>{oe(!0)},[]);function je(){I&&(K(!1),oe(!1))}function Ve(){oe(!1),K(!0)}function ae(Ye,ft){te(Ye),X(ft)}function De(){ee&&V.trim()&&m(ee,V.trim()),te(null),X("")}function rt(){te(null),X("")}E.useEffect(()=>{ee&&Ce.current&&(Ce.current.focus(),Ce.current.select())},[ee]),E.useEffect(()=>{if(!z||I)return;function Ye(ft){ft.key==="Escape"&&ke()}return document.addEventListener("keydown",Ye),()=>{document.removeEventListener("keydown",Ye)}},[z,I,ke]);const ct=b.jsxs(b.Fragment,{children:[!R&&b.jsx("button",{className:"drawer-close-btn",onClick:ke,"aria-label":"Close menu",children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:b.jsx("path",{d:"M4 4L12 12M12 4L4 12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}),!K0&&f.length>0&&b.jsxs("div",{className:"drawer-section",children:[b.jsx("h3",{className:"drawer-section-label",children:"Hosts"}),b.jsx("div",{className:"host-picker-inline",children:b.jsx("div",{className:"host-picker-list",role:"listbox",children:f.map(Ye=>{const ft=Ye.hostId===S,ht=ee===Ye.hostId,xt=Ye.name||Ye.hostId.slice(0,8);return b.jsx("div",{className:"host-picker-item-wrapper",children:b.jsxs("div",{className:`host-picker-item ${ft?"host-picker-item-active":""}`,onClick:()=>{if(!ht&&!ft){if(!Ss())return;B(Ye.hostId),R||ke()}},role:"option","aria-selected":ft,children:[ht?b.jsx("input",{ref:Ce,className:"form-input host-picker-rename-input",type:"text",value:V,onChange:Yt=>X(Yt.target.value),onKeyDown:Yt=>{Yt.key==="Enter"&&De(),Yt.key==="Escape"&&rt()},onBlur:De,onClick:Yt=>Yt.stopPropagation()}):b.jsx("span",{className:"host-picker-item-name",children:xt}),b.jsxs("div",{className:"host-picker-item-actions",children:[ft&&!ht&&b.jsx("button",{className:"host-picker-edit-btn",onClick:Yt=>{Yt.stopPropagation(),ae(Ye.hostId,xt)},"aria-label":"Rename host",children:b.jsx("svg",{width:"13",height:"13",viewBox:"0 0 13 13",fill:"none",children:b.jsx("path",{d:"M9.5 1.5L11.5 3.5M1.5 11.5L2 9L9 2L11 4L4 11L1.5 11.5Z",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}),!ft&&b.jsx("button",{className:"host-picker-delete-btn",onClick:Yt=>{Yt.stopPropagation(),we(Ye.hostId)},"aria-label":`Unpair ${xt}`,children:b.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:b.jsx("path",{d:"M4 5.5V11C4 11.2761 4.22386 11.5 4.5 11.5H9.5C9.77614 11.5 10 11.2761 10 11V5.5M3 4H11M5.5 4V3C5.5 2.72386 5.72386 2.5 6 2.5H8C8.27614 2.5 8.5 2.72386 8.5 3V4M6.5 6.5V9.5M7.5 6.5V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})},Ye.hostId)})})})]}),!K0&&b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-divider"}),b.jsx("div",{className:"drawer-section",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:()=>{Ss()&&(g("/pair"),R||ke())},children:"Add New Host"})})]}),nC&&l&&b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-divider"}),b.jsxs("div",{className:"drawer-section",children:[b.jsx("h3",{className:"drawer-section-label",children:"Device Capabilities"}),D?b.jsx(Fx,{onChange:o,confirmDisable:!0}):b.jsxs(b.Fragment,{children:[b.jsx("p",{className:"drawer-section-hint",children:"This device isn't the linked device for the host, so it can't provide capabilities (SMS, contacts, location, etc.)."}),b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>{s&&s!==j?L(!0):W()},disabled:O,children:O?"Linking…":"Link the host to this device"})]})]})]}),l&&b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-divider"}),b.jsxs("div",{className:"drawer-section",children:[b.jsx("h3",{className:"drawer-section-label",children:"Passwords"}),b.jsx("button",{className:"btn btn-link",onClick:()=>N(!0),children:"Manage saved passwords"})]})]}),b.jsxs("div",{className:"drawer-footer",children:[t&&t.length>0&&(()=>{const Ye=t.filter(ht=>ht.version),ft=t.filter(ht=>!ht.version);return b.jsxs("div",{className:"drawer-agents",children:[Ye.length>0&&b.jsxs("div",{className:"drawer-agents-section",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Agents"}),Ye.map(ht=>b.jsxs("div",{className:"drawer-agents-row",children:[b.jsx("span",{children:ht.label}),b.jsxs("span",{className:"drawer-agents-version",children:["v",ht.version]})]},ht.key))]}),ft.length>0&&b.jsxs("div",{className:"drawer-agents-section",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Version not managed by Palmier"}),ft.map(ht=>b.jsx("div",{className:"drawer-agents-row",children:b.jsx("span",{children:ht.label})},ht.key))]})]})})(),r&&b.jsx("div",{className:"drawer-agents",children:b.jsxs("div",{className:"drawer-agents-section",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Browser Automation"}),b.jsxs("div",{className:"drawer-agents-row",children:[b.jsx("span",{children:r.label}),b.jsxs("span",{className:"drawer-agents-version",children:["v",r.version]})]})]})}),(y.timezone||e)&&b.jsxs("div",{className:"drawer-host-info",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Host"}),y.timezone&&b.jsxs("div",{className:"drawer-host-time",children:[P," · ",y.timezone]}),e&&b.jsxs("div",{className:"drawer-version",children:["Version: v",e]})]}),b.jsxs("div",{className:"drawer-legal",children:[b.jsx("a",{href:"https://www.palmier.me/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms"}),b.jsx("span",{className:"drawer-legal-sep",children:"·"}),b.jsx("a",{href:"https://www.palmier.me/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy"})]})]})]}),Kt=!!ge&&ge===S&&D,Dt=ge&&mi.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>we(null),children:b.jsxs("div",{className:"confirm-modal",onClick:Ye=>Ye.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Remove host?"}),b.jsxs("p",{className:"confirm-modal-message",children:['"',((nn=f.find(Ye=>Ye.hostId===ge))==null?void 0:nn.name)||ge.slice(0,8),'" will be ',Kt?"removed and unlinked":"removed",".",Kt&&b.jsx(b.Fragment,{children:" This device is currently linked to the host — unlinking will revoke its access to all device capabilities (SMS, contacts, location, etc.) until another device is linked."})]}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>we(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:()=>G(ge),children:"Remove"})]})]})}),document.body),tn=C&&mi.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>L(!1),children:b.jsxs("div",{className:"confirm-modal",onClick:Ye=>Ye.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Link the host to this device?"}),b.jsx("p",{className:"confirm-modal-message",children:"Another device is already linked to this host. Only one device can be linked to the host — switching will disable those capabilities on the currently linked device."}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>L(!1),children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:()=>{L(!1),W()},children:"Link"})]})]})}),document.body),$t=J&&l&&b.jsx(tC,{request:l,onClose:()=>N(!1)});return R?b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-panel drawer-panel-desktop",ref:ve,children:ct}),Dt,tn,$t]}):b.jsxs(b.Fragment,{children:[b.jsx("button",{className:"hamburger-btn",onClick:Ve,"aria-label":"Open menu",children:b.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:b.jsx("path",{d:"M3 5H17M3 10H17M3 15H17",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}),z&&mi.createPortal(b.jsx("div",{className:`drawer-overlay ${I?"drawer-overlay-closing":""}`,onClick:ke,onAnimationEnd:je,children:b.jsx("div",{className:`drawer-panel ${I?"drawer-panel-closing":""}`,ref:ve,onClick:Ye=>Ye.stopPropagation(),children:ct})}),document.body),Dt,tn,$t]})}const rC=In.isNativePlatform(),Gd={width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function iC(){return b.jsxs("svg",{...Gd,"aria-hidden":"true",children:[b.jsx("path",{d:"M3 11 L12 3 L21 11"}),b.jsx("path",{d:"M5 9.5 V21 H19 V9.5"})]})}function Z0(){return b.jsxs("svg",{...Gd,"aria-hidden":"true",children:[b.jsx("circle",{cx:"12",cy:"12",r:"10"}),b.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),b.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}function sC(){return b.jsxs("svg",{...Gd,"aria-hidden":"true",children:[b.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),b.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),b.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function aC(){const{mode:e}=bi(),[t,r]=E.useState(!1),s=E.useRef(null);if(E.useEffect(()=>{if(!t)return;function f(m){var y;(y=s.current)!=null&&y.contains(m.target)||r(!1)}document.addEventListener("pointerdown",f);const d=window.setTimeout(()=>r(!1),3e3);return()=>{document.removeEventListener("pointerdown",f),clearTimeout(d)}},[t]),e==="direct")return null;let l,o,c;switch(e){case"lan":l=b.jsx(iC,{}),o="Connected via LAN",c="lan";break;case"nats":l=b.jsx(Z0,{}),o=rC?"Connected via relay":"Connected",c="relay";break;case"disconnected":l=b.jsx(sC,{}),o="Disconnected",c="disconnected";break;case"connecting":default:l=b.jsx(Z0,{}),o="Connecting…",c="connecting";break}return b.jsxs("div",{ref:s,className:`conn-status conn-status--${c}`,children:[b.jsx("button",{type:"button",className:"conn-status-btn","aria-label":o,onClick:()=>r(f=>!f),children:l}),b.jsx("div",{className:`conn-status-popover ${t?"conn-status-popover--open":""}`,role:"tooltip",children:o})]})}function W0(e,t){var s;const r=e.map(l=>l.key);return t&&r.includes(t)?t:((s=e[0])==null?void 0:s.key)??""}function lC({agents:e,hostPlatform:t,onStarted:r}){const{request:s,activeHost:l}=bi(),{setHostLastAgent:o}=Wi(),[c,f]=E.useState(""),[d,m]=E.useState(()=>W0(e,l.lastAgent)),[y,g]=E.useState(!1),[x,v]=E.useState(null);E.useEffect(()=>{e.length&&(e.find(O=>O.key===d)||m(W0(e,l.lastAgent)))},[e,d,l.lastAgent]),E.useEffect(()=>{const O=c.trim().length>0;return Mh(O?"Your session draft will be lost. Continue?":null),()=>Mh(null)},[c]);const S=e.find(O=>O.key===d),j=!!c.trim()&&!!d&&!y;async function D(){if(j){g(!0),v(null);try{const O=await s("task.run_oneoff",{user_prompt:c,agent:d,...t==="win32"?{foreground_mode:!0}:{}});if(O.error){v(O.error);return}o(l.hostId,d),f(""),Mh(null),O.task_id&&r(O.task_id,O.run_id)}catch(O){v(O instanceof Error?O.message:String(O))}finally{g(!1)}}}function R(O){O.key==="Enter"&&(O.metaKey||O.ctrlKey)&&(O.preventDefault(),D())}return b.jsxs("div",{className:"session-composer",children:[x&&b.jsx("div",{className:"form-error",children:x}),b.jsx("textarea",{className:"session-composer-textarea",value:c,onChange:O=>f(O.target.value),onKeyDown:R,placeholder:"What can I do for you?",rows:3,disabled:y}),b.jsxs("div",{className:"session-composer-controls",children:[e.length>0&&b.jsx("div",{className:"agent-picker-section-inline",children:e.length>1?b.jsx("select",{className:"form-select form-select-sm",value:d,onChange:O=>m(O.target.value),disabled:y,children:e.map(O=>b.jsx("option",{value:O.key,children:O.label},O.key))}):b.jsx("span",{className:"agent-picker-single",children:(S==null?void 0:S.label)??e[0].label})}),b.jsx("button",{className:"btn btn-primary chat-send-btn",onClick:D,disabled:!j,"aria-label":"Run session",title:"Run session",children:y?b.jsx("span",{className:"btn-spinner"}):b.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),b.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]})}const xs=72,eb=6;function oC({id:e,revealedId:t,setRevealedId:r,onDelete:s,onClick:l,children:o,actionLabel:c="Delete",confirmMessage:f="Delete this item? This can't be undone.",disabled:d=!1}){const m=t===e,[y,g]=E.useState(0),[x,v]=E.useState(!1),S=E.useRef(0),j=E.useRef(0),D=E.useRef(null),R=E.useRef(0),O=E.useRef(!1),F=E.useRef(null);E.useEffect(()=>{m||g(0)},[m]),E.useEffect(()=>{if(!m)return;function B(z){var K;(K=F.current)!=null&&K.contains(z.target)||r(null)}return document.addEventListener("pointerdown",B),()=>document.removeEventListener("pointerdown",B)},[m,r]);function ue(B){B.button!==void 0&&B.button!==0||(S.current=B.clientX,j.current=B.clientY,D.current=null,R.current=m?-xs:0,O.current=!1)}function H(B){if(d||B.pointerType==="mouse"&&B.buttons===0)return;const z=B.clientX-S.current,K=B.clientY-j.current;if(D.current===null){if(Math.abs(z)<eb&&Math.abs(K)<eb)return;if(D.current=Math.abs(z)>Math.abs(K)?"x":"y",D.current==="x")try{B.currentTarget.setPointerCapture(B.pointerId)}catch{}}if(D.current!=="x")return;O.current=!0,x||v(!0);let I=R.current+z;I>0&&(I=I/4),I<-xs&&(I=-xs+(I+xs)/4),g(I)}function P(){if(D.current!=="x"){v(!1);return}D.current=null,v(!1),y<=-36?(g(-xs),r(e)):(g(0),m&&r(null))}function W(B){if(O.current){O.current=!1,B.stopPropagation(),B.preventDefault();return}m&&(B.stopPropagation(),B.preventDefault(),r(null))}const G=y!==0?y:m?-xs:0;return b.jsxs("div",{ref:F,className:"swipe-row",children:[!d&&b.jsxs("button",{type:"button",className:`swipe-row-action${G<0?"":" swipe-row-action--hidden"}`,style:{width:xs},onClick:B=>{B.stopPropagation(),window.confirm(f)&&s()},tabIndex:m?0:-1,"aria-hidden":!m,"aria-label":c,children:[b.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[b.jsx("polyline",{points:"3 6 5 6 21 6"}),b.jsx("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),b.jsx("path",{d:"M10 11v6M14 11v6"}),b.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"})]}),b.jsx("span",{className:"swipe-row-action-label",children:c})]}),b.jsx("div",{className:`swipe-row-content ${x?"swipe-row-content-dragging":""}`,style:{transform:`translateX(${G}px)`},onPointerDown:ue,onPointerMove:H,onPointerUp:P,onPointerCancel:P,onClickCapture:W,onClick:l,children:o})]})}function $x({starred:e,onToggle:t,className:r}){return b.jsx("button",{type:"button",className:`star-button${e?" star-button--on":""}${r?` ${r}`:""}`,onClick:s=>{s.stopPropagation(),t()},"aria-pressed":e,"aria-label":e?"Unstar session":"Star session",title:e?"Unstar":"Star",children:b.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:b.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})}const uC=10;function cC({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:o,filterTaskId:c,onClearFilter:f,hostInfoStatus:d,onRetryHostInfo:m}){const y=Yd(),[g,x]=E.useState([]),[v,S]=E.useState(0),[j,D]=E.useState(!1),[R,O]=E.useState(!1),[F,ue]=E.useState(null),H=Fr();async function P(C){const L=`${C.task_id}:${C.run_id}`;x(J=>J.filter(N=>`${N.task_id}:${N.run_id}`!==L)),S(J=>Math.max(0,J-1)),ue(null);try{await r("taskrun.delete",{task_id:C.task_id,run_id:C.run_id})}catch(J){console.error("Failed to delete run:",J),x(N=>[C,...N]),S(N=>N+1)}}async function W(C){const L=`${C.task_id}:${C.run_id}`,J=!C.starred,N=ve=>x(Ce=>Ce.map(ke=>`${ke.task_id}:${ke.run_id}`===L?{...ke,starred:ve}:ke));N(J);try{const ve=await r("taskrun.star",{task_id:C.task_id,run_id:C.run_id,starred:J});if(ve.error)throw new Error(ve.error)}catch(ve){console.error("Failed to update star:",ve),N(!J)}}const G=E.useRef(null),B=E.useCallback(C=>{const L={offset:C,limit:uC};return c&&(L.task_id=c),L},[c]),z=E.useCallback(async(C,L)=>{if(e){L?O(!0):D(!0);try{const J=await r("taskrun.list",B(C)),N=J.entries??[];S(J.total??0),x(L?ve=>{const Ce=new Set(ve.map(je=>`${je.task_id}:${je.run_id}`)),ke=N.filter(je=>!Ce.has(`${je.task_id}:${je.run_id}`));return[...ve,...ke]}:N)}catch(J){J instanceof Error&&J.message==="Not connected"||console.error("Failed to load runs:",J)}finally{D(!1),O(!1)}}},[e,r,B]);E.useEffect(()=>{e?(x([]),S(0),z(0,!1)):(x([]),S(0))},[e,t,z,c]);const K=E.useRef(!1);E.useEffect(()=>{d==="error"?K.current=!0:d==="ready"&&K.current&&(K.current=!1,z(0,!1))},[d,z]);const I=qx({onRefresh:()=>z(0,!1),enabled:e});E.useEffect(()=>!e||!t?void 0:s(t,async L=>{try{const J=JSON.parse(new TextDecoder().decode(L.data));if(J.event_type==="running-state"&&J.running_state&&["started","finished","failed","aborted","needs_input"].includes(J.running_state)){const N=await r("taskrun.list",B(0)),ve=N.entries??[];S(N.total??0),x(Ce=>{const ke=new Map(ve.map(De=>[`${De.task_id}:${De.run_id}`,De])),je=Ce.map(De=>{const rt=`${De.task_id}:${De.run_id}`;return ke.get(rt)??De}),Ve=new Set(je.map(De=>`${De.task_id}:${De.run_id}`));return[...ve.filter(De=>!Ve.has(`${De.task_id}:${De.run_id}`)),...je]})}}catch{}}),[e,t,s,r]),E.useEffect(()=>{const C=G.current;if(!C)return;const L=new IntersectionObserver(J=>{J[0].isIntersecting&&!R&&g.length<v&&z(g.length,!0)},{threshold:.1});return L.observe(C),()=>L.disconnect()},[g.length,v,R,z]);function oe(C,L){if(!C||!L)return"";const J=Math.round((L-C)/1e3);if(J<60)return`${J}s`;const N=Math.floor(J/60),ve=J%60;return`${N}m ${ve}s`}const ee={started:"Running",finished:"Finished",failed:"Failed",aborted:"Aborted",needs_input:"Needs input"};function te(C,L){Ss()&&t&&H(`/hosts/${encodeURIComponent(t)}/runs/${encodeURIComponent(C)}/${encodeURIComponent(L)}`)}const V=!c&&d==="ready"&&b.jsx(lC,{agents:l,hostPlatform:o,onStarted:(C,L)=>{if(!t)return;const J=`/hosts/${encodeURIComponent(t)}/runs/${encodeURIComponent(C)}`;H(L?`${J}/${encodeURIComponent(L)}`:J)}}),X=b.jsx(Hx,{pullDistance:I.pullDistance,refreshing:I.refreshing,threshold:I.threshold}),ge=c&&f&&b.jsx("div",{style:{marginBottom:"var(--space-sm)"},children:b.jsxs("span",{className:"sessions-filter-chip",children:["Filtered by task",b.jsx("button",{onClick:f,"aria-label":"Clear filter",children:"×"})]})});function we(C){if(C==="failed")return"var(--color-error)";if(C==="aborted"||C==="needs_input")return"var(--color-warning, #d97706)"}return j&&g.length===0&&e&&d==="ready"?b.jsxs(b.Fragment,{children:[X,V,b.jsx("div",{className:"task-list",children:[0,1,2].map(C=>b.jsxs("div",{className:"task-card",style:{pointerEvents:"none"},children:[b.jsx("div",{className:"task-card-header",children:b.jsx("div",{className:"task-card-title-row",children:b.jsx("div",{className:"skeleton-line",style:{width:`${70+C*10}%`}})})}),b.jsx("div",{className:"task-card-meta",children:b.jsx("div",{className:"skeleton-line",style:{width:"45%"}})})]},C))})]}):g.length===0?b.jsxs(b.Fragment,{children:[X,V,ge,b.jsx("div",{className:"sessions-view",children:d==="loading"?b.jsx("div",{className:"empty-state",children:b.jsx("p",{className:"empty-state-text",children:"Connecting to host…"})}):d==="error"?b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"Couldn't reach host"}),b.jsxs("p",{className:"empty-state-hint",children:["The host didn't respond. Retrying automatically — if this persists, run ",b.jsx("code",{children:"palmier restart"})," on the host machine."]}),b.jsx("button",{className:"btn btn-secondary",onClick:m,children:"Retry now"})]}):b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No sessions yet"}),b.jsx("p",{className:"empty-state-hint",children:c?"This task hasn't been executed yet. Run it from the task menu or wait for its next trigger.":"Your sessions will appear here."})]})})]}):b.jsxs(b.Fragment,{children:[X,V,ge,b.jsxs("div",{className:"task-list",children:[g.map((C,L)=>{const J=`${C.task_id}:${C.run_id}`;return b.jsx(oC,{id:J,revealedId:F,setRevealedId:ue,onDelete:()=>P(C),disabled:C.starred,confirmMessage:"Delete this session? Its run history will be removed from the host.",onClick:()=>!C.error&&te(C.task_id,C.run_id),children:b.jsxs("div",{className:"sessions-card",children:[b.jsxs("div",{className:"sessions-card-body",children:[b.jsx("h3",{className:"sessions-card-name",children:C.task_name||C.task_id}),b.jsxs("div",{className:"sessions-card-meta",children:[C.running_state==="started"?b.jsx("span",{className:"status-spinner","aria-label":"Running",children:b.jsx("span",{})}):b.jsx("span",{style:{color:we(C.running_state)},children:ee[C.running_state??""]??C.running_state}),C.end_time&&b.jsx("span",{children:y(C.end_time)}),C.start_time&&C.end_time&&b.jsx("span",{style:{color:"var(--color-muted)"},children:oe(C.start_time,C.end_time)}),C.error&&b.jsx("span",{style:{color:"var(--color-muted)"},children:C.error})]})]}),!C.error&&b.jsx($x,{starred:!!C.starred,onToggle:()=>W(C)}),b.jsx("span",{className:"sessions-card-chevron",children:"›"})]})},`${J}-${L}`)}),b.jsx("div",{ref:G,style:{height:1}}),R&&b.jsx("div",{className:"loading-state",style:{padding:"var(--space-md)"},children:b.jsx("div",{className:"spinner"})})]})]})}function fC(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const hC=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,dC=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,mC={};function tb(e,t){return(mC.jsx?dC:hC).test(e)}const pC=/[ \t\n\f\r]/g;function gC(e){return typeof e=="object"?e.type==="text"?nb(e.value):!1:nb(e)}function nb(e){return e.replace(pC,"")===""}class Kl{constructor(t,r,s){this.normal=r,this.property=t,s&&(this.space=s)}}Kl.prototype.normal={};Kl.prototype.property={};Kl.prototype.space=void 0;function Vx(e,t){const r={},s={};for(const l of e)Object.assign(r,l.property),Object.assign(s,l.normal);return new Kl(r,s,t)}function bd(e){return e.toLowerCase()}class Fn{constructor(t,r){this.attribute=r,this.property=t}}Fn.prototype.attribute="";Fn.prototype.booleanish=!1;Fn.prototype.boolean=!1;Fn.prototype.commaOrSpaceSeparated=!1;Fn.prototype.commaSeparated=!1;Fn.prototype.defined=!1;Fn.prototype.mustUseProperty=!1;Fn.prototype.number=!1;Fn.prototype.overloadedBoolean=!1;Fn.prototype.property="";Fn.prototype.spaceSeparated=!1;Fn.prototype.space=void 0;let yC=0;const tt=Es(),un=Es(),xd=Es(),Se=Es(),Mt=Es(),xa=Es(),Zn=Es();function Es(){return 2**++yC}const vd=Object.freeze(Object.defineProperty({__proto__:null,boolean:tt,booleanish:un,commaOrSpaceSeparated:Zn,commaSeparated:xa,number:Se,overloadedBoolean:xd,spaceSeparated:Mt},Symbol.toStringTag,{value:"Module"})),Lh=Object.keys(vd);class Jd extends Fn{constructor(t,r,s,l){let o=-1;if(super(t,r),rb(this,"space",l),typeof s=="number")for(;++o<Lh.length;){const c=Lh[o];rb(this,Lh[o],(s&vd[c])===vd[c])}}}Jd.prototype.defined=!0;function rb(e,t,r){r&&(e[t]=r)}function Na(e){const t={},r={};for(const[s,l]of Object.entries(e.properties)){const o=new Jd(s,e.transform(e.attributes||{},s),l,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(o.mustUseProperty=!0),t[s]=o,r[bd(s)]=s,r[bd(o.attribute)]=s}return new Kl(t,r,e.space)}const Yx=Na({properties:{ariaActiveDescendant:null,ariaAtomic:un,ariaAutoComplete:null,ariaBusy:un,ariaChecked:un,ariaColCount:Se,ariaColIndex:Se,ariaColSpan:Se,ariaControls:Mt,ariaCurrent:null,ariaDescribedBy:Mt,ariaDetails:null,ariaDisabled:un,ariaDropEffect:Mt,ariaErrorMessage:null,ariaExpanded:un,ariaFlowTo:Mt,ariaGrabbed:un,ariaHasPopup:null,ariaHidden:un,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Mt,ariaLevel:Se,ariaLive:null,ariaModal:un,ariaMultiLine:un,ariaMultiSelectable:un,ariaOrientation:null,ariaOwns:Mt,ariaPlaceholder:null,ariaPosInSet:Se,ariaPressed:un,ariaReadOnly:un,ariaRelevant:null,ariaRequired:un,ariaRoleDescription:Mt,ariaRowCount:Se,ariaRowIndex:Se,ariaRowSpan:Se,ariaSelected:un,ariaSetSize:Se,ariaSort:null,ariaValueMax:Se,ariaValueMin:Se,ariaValueNow:Se,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Gx(e,t){return t in e?e[t]:t}function Jx(e,t){return Gx(e,t.toLowerCase())}const bC=Na({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:xa,acceptCharset:Mt,accessKey:Mt,action:null,allow:null,allowFullScreen:tt,allowPaymentRequest:tt,allowUserMedia:tt,alt:null,as:null,async:tt,autoCapitalize:null,autoComplete:Mt,autoFocus:tt,autoPlay:tt,blocking:Mt,capture:null,charSet:null,checked:tt,cite:null,className:Mt,cols:Se,colSpan:null,content:null,contentEditable:un,controls:tt,controlsList:Mt,coords:Se|xa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:tt,defer:tt,dir:null,dirName:null,disabled:tt,download:xd,draggable:un,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:tt,formTarget:null,headers:Mt,height:Se,hidden:xd,high:Se,href:null,hrefLang:null,htmlFor:Mt,httpEquiv:Mt,id:null,imageSizes:null,imageSrcSet:null,inert:tt,inputMode:null,integrity:null,is:null,isMap:tt,itemId:null,itemProp:Mt,itemRef:Mt,itemScope:tt,itemType:Mt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:tt,low:Se,manifest:null,max:null,maxLength:Se,media:null,method:null,min:null,minLength:Se,multiple:tt,muted:tt,name:null,nonce:null,noModule:tt,noValidate:tt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:tt,optimum:Se,pattern:null,ping:Mt,placeholder:null,playsInline:tt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:tt,referrerPolicy:null,rel:Mt,required:tt,reversed:tt,rows:Se,rowSpan:Se,sandbox:Mt,scope:null,scoped:tt,seamless:tt,selected:tt,shadowRootClonable:tt,shadowRootDelegatesFocus:tt,shadowRootMode:null,shape:null,size:Se,sizes:null,slot:null,span:Se,spellCheck:un,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Se,step:null,style:null,tabIndex:Se,target:null,title:null,translate:null,type:null,typeMustMatch:tt,useMap:null,value:un,width:Se,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Mt,axis:null,background:null,bgColor:null,border:Se,borderColor:null,bottomMargin:Se,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:tt,declare:tt,event:null,face:null,frame:null,frameBorder:null,hSpace:Se,leftMargin:Se,link:null,longDesc:null,lowSrc:null,marginHeight:Se,marginWidth:Se,noResize:tt,noHref:tt,noShade:tt,noWrap:tt,object:null,profile:null,prompt:null,rev:null,rightMargin:Se,rules:null,scheme:null,scrolling:un,standby:null,summary:null,text:null,topMargin:Se,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Se,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:tt,disableRemotePlayback:tt,prefix:null,property:null,results:Se,security:null,unselectable:null},space:"html",transform:Jx}),xC=Na({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Zn,accentHeight:Se,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Se,amplitude:Se,arabicForm:null,ascent:Se,attributeName:null,attributeType:null,azimuth:Se,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Se,by:null,calcMode:null,capHeight:Se,className:Mt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Se,diffuseConstant:Se,direction:null,display:null,dur:null,divisor:Se,dominantBaseline:null,download:tt,dx:null,dy:null,edgeMode:null,editable:null,elevation:Se,enableBackground:null,end:null,event:null,exponent:Se,externalResourcesRequired:null,fill:null,fillOpacity:Se,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:xa,g2:xa,glyphName:xa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Se,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Se,horizOriginX:Se,horizOriginY:Se,id:null,ideographic:Se,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Se,k:Se,k1:Se,k2:Se,k3:Se,k4:Se,kernelMatrix:Zn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Se,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Se,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Se,overlineThickness:Se,paintOrder:null,panose1:null,path:null,pathLength:Se,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Mt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Se,pointsAtY:Se,pointsAtZ:Se,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Zn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Zn,rev:Zn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Zn,requiredFeatures:Zn,requiredFonts:Zn,requiredFormats:Zn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Se,specularExponent:Se,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Se,strikethroughThickness:Se,string:null,stroke:null,strokeDashArray:Zn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Se,strokeOpacity:Se,strokeWidth:null,style:null,surfaceScale:Se,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Zn,tabIndex:Se,tableValues:null,target:null,targetX:Se,targetY:Se,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Zn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Se,underlineThickness:Se,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Se,values:null,vAlphabetic:Se,vMathematical:Se,vectorEffect:null,vHanging:Se,vIdeographic:Se,version:null,vertAdvY:Se,vertOriginX:Se,vertOriginY:Se,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Se,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Gx}),Xx=Na({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Kx=Na({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Jx}),Qx=Na({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),vC={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},wC=/[A-Z]/g,ib=/-[a-z]/g,SC=/^data[-\w.:]+$/i;function _C(e,t){const r=bd(t);let s=t,l=Fn;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&SC.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(ib,EC);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!ib.test(o)){let c=o.replace(wC,kC);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}l=Jd}return new l(s,t)}function kC(e){return"-"+e.toLowerCase()}function EC(e){return e.charAt(1).toUpperCase()}const CC=Vx([Yx,bC,Xx,Kx,Qx],"html"),Xd=Vx([Yx,xC,Xx,Kx,Qx],"svg");function AC(e){return e.join(" ").trim()}var la={},zh,sb;function jC(){if(sb)return zh;sb=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,l=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,f=/^\s+|\s+$/g,d=`
90
90
  `,m="/",y="*",g="",x="comment",v="declaration";function S(D,R){if(typeof D!="string")throw new TypeError("First argument must be a string");if(!D)return[];R=R||{};var O=1,F=1;function ue(ee){var te=ee.match(t);te&&(O+=te.length);var V=ee.lastIndexOf(d);F=~V?ee.length-V:F+ee.length}function H(){var ee={line:O,column:F};return function(te){return te.position=new P(ee),B(),te}}function P(ee){this.start=ee,this.end={line:O,column:F},this.source=R.source}P.prototype.content=D;function W(ee){var te=new Error(R.source+":"+O+":"+F+": "+ee);if(te.reason=ee,te.filename=R.source,te.line=O,te.column=F,te.source=D,!R.silent)throw te}function G(ee){var te=ee.exec(D);if(te){var V=te[0];return ue(V),D=D.slice(V.length),te}}function B(){G(r)}function z(ee){var te;for(ee=ee||[];te=K();)te!==!1&&ee.push(te);return ee}function K(){var ee=H();if(!(m!=D.charAt(0)||y!=D.charAt(1))){for(var te=2;g!=D.charAt(te)&&(y!=D.charAt(te)||m!=D.charAt(te+1));)++te;if(te+=2,g===D.charAt(te-1))return W("End of comment missing");var V=D.slice(2,te-2);return F+=2,ue(V),D=D.slice(te),F+=2,ee({type:x,comment:V})}}function I(){var ee=H(),te=G(s);if(te){if(K(),!G(l))return W("property missing ':'");var V=G(o),X=ee({type:v,property:j(te[0].replace(e,g)),value:V?j(V[0].replace(e,g)):g});return G(c),X}}function oe(){var ee=[];z(ee);for(var te;te=I();)te!==!1&&(ee.push(te),z(ee));return ee}return B(),oe()}function j(D){return D?D.replace(f,g):g}return zh=S,zh}var ab;function NC(){if(ab)return la;ab=1;var e=la&&la.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(la,"__esModule",{value:!0}),la.default=r;const t=e(jC());function r(s,l){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),f=typeof l=="function";return c.forEach(d=>{if(d.type!=="declaration")return;const{property:m,value:y}=d;f?l(m,y,d):y&&(o=o||{},o[m]=y)}),o}return la}var _l={},lb;function TC(){if(lb)return _l;lb=1,Object.defineProperty(_l,"__esModule",{value:!0}),_l.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,l=/^-(ms)-/,o=function(m){return!m||r.test(m)||e.test(m)},c=function(m,y){return y.toUpperCase()},f=function(m,y){return"".concat(y,"-")},d=function(m,y){return y===void 0&&(y={}),o(m)?m:(m=m.toLowerCase(),y.reactCompat?m=m.replace(l,f):m=m.replace(s,f),m.replace(t,c))};return _l.camelCase=d,_l}var kl,ob;function OC(){if(ob)return kl;ob=1;var e=kl&&kl.__importDefault||function(l){return l&&l.__esModule?l:{default:l}},t=e(NC()),r=TC();function s(l,o){var c={};return!l||typeof l!="string"||(0,t.default)(l,function(f,d){f&&d&&(c[(0,r.camelCase)(f,o)]=d)}),c}return s.default=s,kl=s,kl}var RC=OC();const MC=Vb(RC),Zx=Wx("end"),Kd=Wx("start");function Wx(e){return t;function t(r){const s=r&&r.position&&r.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function DC(e){const t=Kd(e),r=Zx(e);if(t&&r)return{start:t,end:r}}function Ll(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?ub(e.position):"start"in e||"end"in e?ub(e):"line"in e||"column"in e?wd(e):""}function wd(e){return cb(e&&e.line)+":"+cb(e&&e.column)}function ub(e){return wd(e&&e.start)+"-"+wd(e&&e.end)}function cb(e){return e&&typeof e=="number"?e:1}class Cn extends Error{constructor(t,r,s){super(),typeof r=="string"&&(s=r,r=void 0);let l="",o={},c=!1;if(r&&("line"in r&&"column"in r?o={place:r}:"start"in r&&"end"in r?o={place:r}:"type"in r?o={ancestors:[r],place:r.position}:o={...r}),typeof t=="string"?l=t:!o.cause&&t&&(c=!0,l=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const d=s.indexOf(":");d===-1?o.ruleId=s:(o.source=s.slice(0,d),o.ruleId=s.slice(d+1))}if(!o.place&&o.ancestors&&o.ancestors){const d=o.ancestors[o.ancestors.length-1];d&&(o.place=d.position)}const f=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=f?f.column:void 0,this.fatal=void 0,this.file="",this.message=l,this.line=f?f.line:void 0,this.name=Ll(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Cn.prototype.file="";Cn.prototype.name="";Cn.prototype.reason="";Cn.prototype.message="";Cn.prototype.stack="";Cn.prototype.column=void 0;Cn.prototype.line=void 0;Cn.prototype.ancestors=void 0;Cn.prototype.cause=void 0;Cn.prototype.fatal=void 0;Cn.prototype.place=void 0;Cn.prototype.ruleId=void 0;Cn.prototype.source=void 0;const Qd={}.hasOwnProperty,LC=new Map,zC=/[A-Z]/g,UC=new Set(["table","tbody","thead","tfoot","tr"]),PC=new Set(["td","th"]),e1="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function BC(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=GC(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=YC(r,t.jsx,t.jsxs)}const l={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Xd:CC,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=t1(l,e,void 0);return o&&typeof o!="string"?o:l.create(e,l.Fragment,{children:o||void 0},void 0)}function t1(e,t,r){if(t.type==="element")return HC(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return qC(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return FC(e,t,r);if(t.type==="mdxjsEsm")return IC(e,t);if(t.type==="root")return $C(e,t,r);if(t.type==="text")return VC(e,t)}function HC(e,t,r){const s=e.schema;let l=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(l=Xd,e.schema=l),e.ancestors.push(t);const o=r1(e,t.tagName,!1),c=JC(e,t);let f=Wd(e,t);return UC.has(t.tagName)&&(f=f.filter(function(d){return typeof d=="string"?!gC(d):!0})),n1(e,c,o,t),Zd(c,f),e.ancestors.pop(),e.schema=s,e.create(t,o,c,r)}function qC(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}$l(e,t.position)}function IC(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);$l(e,t.position)}function FC(e,t,r){const s=e.schema;let l=s;t.name==="svg"&&s.space==="html"&&(l=Xd,e.schema=l),e.ancestors.push(t);const o=t.name===null?e.Fragment:r1(e,t.name,!0),c=XC(e,t),f=Wd(e,t);return n1(e,c,o,t),Zd(c,f),e.ancestors.pop(),e.schema=s,e.create(t,o,c,r)}function $C(e,t,r){const s={};return Zd(s,Wd(e,t)),e.create(t,e.Fragment,s,r)}function VC(e,t){return t.value}function n1(e,t,r,s){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=s)}function Zd(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function YC(e,t,r){return s;function s(l,o,c,f){const m=Array.isArray(c.children)?r:t;return f?m(o,c,f):m(o,c)}}function GC(e,t){return r;function r(s,l,o,c){const f=Array.isArray(o.children),d=Kd(s);return t(l,o,c,f,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function JC(e,t){const r={};let s,l;for(l in t.properties)if(l!=="children"&&Qd.call(t.properties,l)){const o=KC(e,l,t.properties[l]);if(o){const[c,f]=o;e.tableCellAlignToStyle&&c==="align"&&typeof f=="string"&&PC.has(t.tagName)?s=f:r[c]=f}}if(s){const o=r.style||(r.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return r}function XC(e,t){const r={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const f=c.properties[0];f.type,Object.assign(r,e.evaluater.evaluateExpression(f.argument))}else $l(e,t.position);else{const l=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const f=s.value.data.estree.body[0];f.type,o=e.evaluater.evaluateExpression(f.expression)}else $l(e,t.position);else o=s.value===null?!0:s.value;r[l]=o}return r}function Wd(e,t){const r=[];let s=-1;const l=e.passKeys?new Map:LC;for(;++s<t.children.length;){const o=t.children[s];let c;if(e.passKeys){const d=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(d){const m=l.get(d)||0;c=d+"-"+m,l.set(d,m+1)}}const f=t1(e,o,c);f!==void 0&&r.push(f)}return r}function KC(e,t,r){const s=_C(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=s.commaSeparated?fC(r):AC(r)),s.property==="style"){let l=typeof r=="object"?r:QC(e,String(r));return e.stylePropertyNameCase==="css"&&(l=ZC(l)),["style",l]}return[e.elementAttributeNameCase==="react"&&s.space?vC[s.property]||s.property:s.attribute,r]}}function QC(e,t){try{return MC(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const s=r,l=new Cn("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:s,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw l.file=e.filePath||void 0,l.url=e1+"#cannot-parse-style-attribute",l}}function r1(e,t,r){let s;if(!r)s={type:"Literal",value:t};else if(t.includes(".")){const l=t.split(".");let o=-1,c;for(;++o<l.length;){const f=tb(l[o])?{type:"Identifier",name:l[o]}:{type:"Literal",value:l[o]};c=c?{type:"MemberExpression",object:c,property:f,computed:!!(o&&f.type==="Literal"),optional:!1}:f}s=c}else s=tb(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const l=s.value;return Qd.call(e.components,l)?e.components[l]:l}if(e.evaluater)return e.evaluater.evaluateExpression(s);$l(e)}function $l(e,t){const r=new Cn("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=e1+"#cannot-handle-mdx-estrees-without-createevaluater",r}function ZC(e){const t={};let r;for(r in e)Qd.call(e,r)&&(t[WC(r)]=e[r]);return t}function WC(e){let t=e.replace(zC,eA);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function eA(e){return"-"+e.toLowerCase()}const Uh={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},tA={};function em(e,t){const r=tA,s=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,l=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return i1(e,s,l)}function i1(e,t,r){if(nA(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return fb(e.children,t,r)}return Array.isArray(e)?fb(e,t,r):""}function fb(e,t,r){const s=[];let l=-1;for(;++l<e.length;)s[l]=i1(e[l],t,r);return s.join("")}function nA(e){return!!(e&&typeof e=="object")}const hb=document.createElement("i");function tm(e){const t="&"+e+";";hb.innerHTML=t;const r=hb.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function rr(e,t,r,s){const l=e.length;let o=0,c;if(t<0?t=-t>l?0:l+t:t=t>l?l:t,r=r>0?r:0,s.length<1e4)c=Array.from(s),c.unshift(t,r),e.splice(...c);else for(r&&e.splice(t,r);o<s.length;)c=s.slice(o,o+1e4),c.unshift(t,0),e.splice(...c),o+=1e4,t+=1e4}function xr(e,t){return e.length>0?(rr(e,e.length,0,t),e):t}const db={}.hasOwnProperty;function s1(e){const t={};let r=-1;for(;++r<e.length;)rA(t,e[r]);return t}function rA(e,t){let r;for(r in t){const l=(db.call(e,r)?e[r]:void 0)||(e[r]={}),o=t[r];let c;if(o)for(c in o){db.call(l,c)||(l[c]=[]);const f=o[c];iA(l[c],Array.isArray(f)?f:f?[f]:[])}}}function iA(e,t){let r=-1;const s=[];for(;++r<t.length;)(t[r].add==="after"?e:s).push(t[r]);rr(e,0,0,s)}function a1(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function Tr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Mn=ts(/[A-Za-z]/),En=ts(/[\dA-Za-z]/),sA=ts(/[#-'*+\--9=?A-Z^-~]/);function Hu(e){return e!==null&&(e<32||e===127)}const Sd=ts(/\d/),aA=ts(/[\dA-Fa-f]/),lA=ts(/[!-/:-@[-`{-~]/);function Ie(e){return e!==null&&e<-2}function Rt(e){return e!==null&&(e<0||e===32)}function at(e){return e===-2||e===-1||e===32}const Wu=ts(new RegExp("\\p{P}|\\p{S}","u")),_s=ts(/\s/);function ts(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Ta(e){const t=[];let r=-1,s=0,l=0;for(;++r<e.length;){const o=e.charCodeAt(r);let c="";if(o===37&&En(e.charCodeAt(r+1))&&En(e.charCodeAt(r+2)))l=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(c=String.fromCharCode(o));else if(o>55295&&o<57344){const f=e.charCodeAt(r+1);o<56320&&f>56319&&f<57344?(c=String.fromCharCode(o,f),l=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,r),encodeURIComponent(c)),s=r+l+1,c=""),l&&(r+=l,l=0)}return t.join("")+e.slice(s)}function pt(e,t,r,s){const l=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(d){return at(d)?(e.enter(r),f(d)):t(d)}function f(d){return at(d)&&o++<l?(e.consume(d),f):(e.exit(r),t(d))}}const oA={tokenize:uA};function uA(e){const t=e.attempt(this.parser.constructs.contentInitial,s,l);let r;return t;function s(f){if(f===null){e.consume(f);return}return e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),pt(e,t,"linePrefix")}function l(f){return e.enter("paragraph"),o(f)}function o(f){const d=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=d),r=d,c(f)}function c(f){if(f===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(f);return}return Ie(f)?(e.consume(f),e.exit("chunkText"),o):(e.consume(f),c)}}const cA={tokenize:fA},mb={tokenize:hA};function fA(e){const t=this,r=[];let s=0,l,o,c;return f;function f(F){if(s<r.length){const ue=r[s];return t.containerState=ue[1],e.attempt(ue[0].continuation,d,m)(F)}return m(F)}function d(F){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,l&&O();const ue=t.events.length;let H=ue,P;for(;H--;)if(t.events[H][0]==="exit"&&t.events[H][1].type==="chunkFlow"){P=t.events[H][1].end;break}R(s);let W=ue;for(;W<t.events.length;)t.events[W][1].end={...P},W++;return rr(t.events,H+1,0,t.events.slice(ue)),t.events.length=W,m(F)}return f(F)}function m(F){if(s===r.length){if(!l)return x(F);if(l.currentConstruct&&l.currentConstruct.concrete)return S(F);t.interrupt=!!(l.currentConstruct&&!l._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(mb,y,g)(F)}function y(F){return l&&O(),R(s),x(F)}function g(F){return t.parser.lazy[t.now().line]=s!==r.length,c=t.now().offset,S(F)}function x(F){return t.containerState={},e.attempt(mb,v,S)(F)}function v(F){return s++,r.push([t.currentConstruct,t.containerState]),x(F)}function S(F){if(F===null){l&&O(),R(0),e.consume(F);return}return l=l||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:l,contentType:"flow",previous:o}),j(F)}function j(F){if(F===null){D(e.exit("chunkFlow"),!0),R(0),e.consume(F);return}return Ie(F)?(e.consume(F),D(e.exit("chunkFlow")),s=0,t.interrupt=void 0,f):(e.consume(F),j)}function D(F,ue){const H=t.sliceStream(F);if(ue&&H.push(null),F.previous=o,o&&(o.next=F),o=F,l.defineSkip(F.start),l.write(H),t.parser.lazy[F.start.line]){let P=l.events.length;for(;P--;)if(l.events[P][1].start.offset<c&&(!l.events[P][1].end||l.events[P][1].end.offset>c))return;const W=t.events.length;let G=W,B,z;for(;G--;)if(t.events[G][0]==="exit"&&t.events[G][1].type==="chunkFlow"){if(B){z=t.events[G][1].end;break}B=!0}for(R(s),P=W;P<t.events.length;)t.events[P][1].end={...z},P++;rr(t.events,G+1,0,t.events.slice(W)),t.events.length=P}}function R(F){let ue=r.length;for(;ue-- >F;){const H=r[ue];t.containerState=H[1],H[0].exit.call(t,e)}r.length=F}function O(){l.write([null]),o=void 0,l=void 0,t.containerState._closeFlow=void 0}}function hA(e,t,r){return pt(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ka(e){if(e===null||Rt(e)||_s(e))return 1;if(Wu(e))return 2}function ec(e,t,r){const s=[];let l=-1;for(;++l<e.length;){const o=e[l].resolveAll;o&&!s.includes(o)&&(t=o(t,r),s.push(o))}return t}const _d={name:"attention",resolveAll:dA,tokenize:mA};function dA(e,t){let r=-1,s,l,o,c,f,d,m,y;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(s=r;s--;)if(e[s][0]==="exit"&&e[s][1].type==="attentionSequence"&&e[s][1]._open&&t.sliceSerialize(e[s][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[s][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[s][1].end.offset-e[s][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;d=e[s][1].end.offset-e[s][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const g={...e[s][1].end},x={...e[r][1].start};pb(g,-d),pb(x,d),c={type:d>1?"strongSequence":"emphasisSequence",start:g,end:{...e[s][1].end}},f={type:d>1?"strongSequence":"emphasisSequence",start:{...e[r][1].start},end:x},o={type:d>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[r][1].start}},l={type:d>1?"strong":"emphasis",start:{...c.start},end:{...f.end}},e[s][1].end={...c.start},e[r][1].start={...f.end},m=[],e[s][1].end.offset-e[s][1].start.offset&&(m=xr(m,[["enter",e[s][1],t],["exit",e[s][1],t]])),m=xr(m,[["enter",l,t],["enter",c,t],["exit",c,t],["enter",o,t]]),m=xr(m,ec(t.parser.constructs.insideSpan.null,e.slice(s+1,r),t)),m=xr(m,[["exit",o,t],["enter",f,t],["exit",f,t],["exit",l,t]]),e[r][1].end.offset-e[r][1].start.offset?(y=2,m=xr(m,[["enter",e[r][1],t],["exit",e[r][1],t]])):y=0,rr(e,s-1,r-s+3,m),r=s+m.length-y-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function mA(e,t){const r=this.parser.constructs.attentionMarkers.null,s=this.previous,l=ka(s);let o;return c;function c(d){return o=d,e.enter("attentionSequence"),f(d)}function f(d){if(d===o)return e.consume(d),f;const m=e.exit("attentionSequence"),y=ka(d),g=!y||y===2&&l||r.includes(d),x=!l||l===2&&y||r.includes(s);return m._open=!!(o===42?g:g&&(l||!x)),m._close=!!(o===42?x:x&&(y||!g)),t(d)}}function pb(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const pA={name:"autolink",tokenize:gA};function gA(e,t,r){let s=0;return l;function l(v){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(v),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(v){return Mn(v)?(e.consume(v),c):v===64?r(v):m(v)}function c(v){return v===43||v===45||v===46||En(v)?(s=1,f(v)):m(v)}function f(v){return v===58?(e.consume(v),s=0,d):(v===43||v===45||v===46||En(v))&&s++<32?(e.consume(v),f):(s=0,m(v))}function d(v){return v===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(v),e.exit("autolinkMarker"),e.exit("autolink"),t):v===null||v===32||v===60||Hu(v)?r(v):(e.consume(v),d)}function m(v){return v===64?(e.consume(v),y):sA(v)?(e.consume(v),m):r(v)}function y(v){return En(v)?g(v):r(v)}function g(v){return v===46?(e.consume(v),s=0,y):v===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(v),e.exit("autolinkMarker"),e.exit("autolink"),t):x(v)}function x(v){if((v===45||En(v))&&s++<63){const S=v===45?x:g;return e.consume(v),S}return r(v)}}const Ql={partial:!0,tokenize:yA};function yA(e,t,r){return s;function s(o){return at(o)?pt(e,l,"linePrefix")(o):l(o)}function l(o){return o===null||Ie(o)?t(o):r(o)}}const l1={continuation:{tokenize:xA},exit:vA,name:"blockQuote",tokenize:bA};function bA(e,t,r){const s=this;return l;function l(c){if(c===62){const f=s.containerState;return f.open||(e.enter("blockQuote",{_container:!0}),f.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(c),e.exit("blockQuoteMarker"),o}return r(c)}function o(c){return at(c)?(e.enter("blockQuotePrefixWhitespace"),e.consume(c),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(c))}}function xA(e,t,r){const s=this;return l;function l(c){return at(c)?pt(e,o,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c):o(c)}function o(c){return e.attempt(l1,t,r)(c)}}function vA(e){e.exit("blockQuote")}const o1={name:"characterEscape",tokenize:wA};function wA(e,t,r){return s;function s(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),l}function l(o){return lA(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(o)}}const u1={name:"characterReference",tokenize:SA};function SA(e,t,r){const s=this;let l=0,o,c;return f;function f(g){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(g),e.exit("characterReferenceMarker"),d}function d(g){return g===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(g),e.exit("characterReferenceMarkerNumeric"),m):(e.enter("characterReferenceValue"),o=31,c=En,y(g))}function m(g){return g===88||g===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(g),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,c=aA,y):(e.enter("characterReferenceValue"),o=7,c=Sd,y(g))}function y(g){if(g===59&&l){const x=e.exit("characterReferenceValue");return c===En&&!tm(s.sliceSerialize(x))?r(g):(e.enter("characterReferenceMarker"),e.consume(g),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return c(g)&&l++<o?(e.consume(g),y):r(g)}}const gb={partial:!0,tokenize:kA},yb={concrete:!0,name:"codeFenced",tokenize:_A};function _A(e,t,r){const s=this,l={partial:!0,tokenize:H};let o=0,c=0,f;return d;function d(P){return m(P)}function m(P){const W=s.events[s.events.length-1];return o=W&&W[1].type==="linePrefix"?W[2].sliceSerialize(W[1],!0).length:0,f=P,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),y(P)}function y(P){return P===f?(c++,e.consume(P),y):c<3?r(P):(e.exit("codeFencedFenceSequence"),at(P)?pt(e,g,"whitespace")(P):g(P))}function g(P){return P===null||Ie(P)?(e.exit("codeFencedFence"),s.interrupt?t(P):e.check(gb,j,ue)(P)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),x(P))}function x(P){return P===null||Ie(P)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),g(P)):at(P)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),pt(e,v,"whitespace")(P)):P===96&&P===f?r(P):(e.consume(P),x)}function v(P){return P===null||Ie(P)?g(P):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),S(P))}function S(P){return P===null||Ie(P)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),g(P)):P===96&&P===f?r(P):(e.consume(P),S)}function j(P){return e.attempt(l,ue,D)(P)}function D(P){return e.enter("lineEnding"),e.consume(P),e.exit("lineEnding"),R}function R(P){return o>0&&at(P)?pt(e,O,"linePrefix",o+1)(P):O(P)}function O(P){return P===null||Ie(P)?e.check(gb,j,ue)(P):(e.enter("codeFlowValue"),F(P))}function F(P){return P===null||Ie(P)?(e.exit("codeFlowValue"),O(P)):(e.consume(P),F)}function ue(P){return e.exit("codeFenced"),t(P)}function H(P,W,G){let B=0;return z;function z(te){return P.enter("lineEnding"),P.consume(te),P.exit("lineEnding"),K}function K(te){return P.enter("codeFencedFence"),at(te)?pt(P,I,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(te):I(te)}function I(te){return te===f?(P.enter("codeFencedFenceSequence"),oe(te)):G(te)}function oe(te){return te===f?(B++,P.consume(te),oe):B>=c?(P.exit("codeFencedFenceSequence"),at(te)?pt(P,ee,"whitespace")(te):ee(te)):G(te)}function ee(te){return te===null||Ie(te)?(P.exit("codeFencedFence"),W(te)):G(te)}}}function kA(e,t,r){const s=this;return l;function l(c){return c===null?r(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?r(c):t(c)}}const Ph={name:"codeIndented",tokenize:CA},EA={partial:!0,tokenize:AA};function CA(e,t,r){const s=this;return l;function l(m){return e.enter("codeIndented"),pt(e,o,"linePrefix",5)(m)}function o(m){const y=s.events[s.events.length-1];return y&&y[1].type==="linePrefix"&&y[2].sliceSerialize(y[1],!0).length>=4?c(m):r(m)}function c(m){return m===null?d(m):Ie(m)?e.attempt(EA,c,d)(m):(e.enter("codeFlowValue"),f(m))}function f(m){return m===null||Ie(m)?(e.exit("codeFlowValue"),c(m)):(e.consume(m),f)}function d(m){return e.exit("codeIndented"),t(m)}}function AA(e,t,r){const s=this;return l;function l(c){return s.parser.lazy[s.now().line]?r(c):Ie(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):pt(e,o,"linePrefix",5)(c)}function o(c){const f=s.events[s.events.length-1];return f&&f[1].type==="linePrefix"&&f[2].sliceSerialize(f[1],!0).length>=4?t(c):Ie(c)?l(c):r(c)}}const jA={name:"codeText",previous:TA,resolve:NA,tokenize:OA};function NA(e){let t=e.length-4,r=3,s,l;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=r;++s<t;)if(e[s][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(s=r-1,t++;++s<=t;)l===void 0?s!==t&&e[s][1].type!=="lineEnding"&&(l=s):(s===t||e[s][1].type==="lineEnding")&&(e[l][1].type="codeTextData",s!==l+2&&(e[l][1].end=e[s-1][1].end,e.splice(l+2,s-l-2),t-=s-l-2,s=l+2),l=void 0);return e}function TA(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function OA(e,t,r){let s=0,l,o;return c;function c(g){return e.enter("codeText"),e.enter("codeTextSequence"),f(g)}function f(g){return g===96?(e.consume(g),s++,f):(e.exit("codeTextSequence"),d(g))}function d(g){return g===null?r(g):g===32?(e.enter("space"),e.consume(g),e.exit("space"),d):g===96?(o=e.enter("codeTextSequence"),l=0,y(g)):Ie(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),d):(e.enter("codeTextData"),m(g))}function m(g){return g===null||g===32||g===96||Ie(g)?(e.exit("codeTextData"),d(g)):(e.consume(g),m)}function y(g){return g===96?(e.consume(g),l++,y):l===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(g)):(o.type="codeTextData",m(g))}}class RA{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const s=r??Number.POSITIVE_INFINITY;return s<this.left.length?this.left.slice(t,s):t>this.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,r,s){const l=r||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-l,Number.POSITIVE_INFINITY);return s&&El(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),El(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),El(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);El(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);El(this.left,r.reverse())}}}function El(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function c1(e){const t={};let r=-1,s,l,o,c,f,d,m;const y=new RA(e);for(;++r<y.length;){for(;r in t;)r=t[r];if(s=y.get(r),r&&s[1].type==="chunkFlow"&&y.get(r-1)[1].type==="listItemPrefix"&&(d=s[1]._tokenizer.events,o=0,o<d.length&&d[o][1].type==="lineEndingBlank"&&(o+=2),o<d.length&&d[o][1].type==="content"))for(;++o<d.length&&d[o][1].type!=="content";)d[o][1].type==="chunkText"&&(d[o][1]._isInFirstContentOfListItem=!0,o++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,MA(y,r)),r=t[r],m=!0);else if(s[1]._container){for(o=r,l=void 0;o--;)if(c=y.get(o),c[1].type==="lineEnding"||c[1].type==="lineEndingBlank")c[0]==="enter"&&(l&&(y.get(l)[1].type="lineEndingBlank"),c[1].type="lineEnding",l=o);else if(!(c[1].type==="linePrefix"||c[1].type==="listItemIndent"))break;l&&(s[1].end={...y.get(l)[1].start},f=y.slice(l,r),f.unshift(s),y.splice(l,r-l+1,f))}}return rr(e,0,Number.POSITIVE_INFINITY,y.slice(0)),!m}function MA(e,t){const r=e.get(t)[1],s=e.get(t)[2];let l=t-1;const o=[];let c=r._tokenizer;c||(c=s.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(c._contentTypeTextTrailing=!0));const f=c.events,d=[],m={};let y,g,x=-1,v=r,S=0,j=0;const D=[j];for(;v;){for(;e.get(++l)[1]!==v;);o.push(l),v._tokenizer||(y=s.sliceStream(v),v.next||y.push(null),g&&c.defineSkip(v.start),v._isInFirstContentOfListItem&&(c._gfmTasklistFirstContentOfListItem=!0),c.write(y),v._isInFirstContentOfListItem&&(c._gfmTasklistFirstContentOfListItem=void 0)),g=v,v=v.next}for(v=r;++x<f.length;)f[x][0]==="exit"&&f[x-1][0]==="enter"&&f[x][1].type===f[x-1][1].type&&f[x][1].start.line!==f[x][1].end.line&&(j=x+1,D.push(j),v._tokenizer=void 0,v.previous=void 0,v=v.next);for(c.events=[],v?(v._tokenizer=void 0,v.previous=void 0):D.pop(),x=D.length;x--;){const R=f.slice(D[x],D[x+1]),O=o.pop();d.push([O,O+R.length-1]),e.splice(O,2,R)}for(d.reverse(),x=-1;++x<d.length;)m[S+d[x][0]]=S+d[x][1],S+=d[x][1]-d[x][0]-1;return m}const DA={resolve:zA,tokenize:UA},LA={partial:!0,tokenize:PA};function zA(e){return c1(e),e}function UA(e,t){let r;return s;function s(f){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),l(f)}function l(f){return f===null?o(f):Ie(f)?e.check(LA,c,o)(f):(e.consume(f),l)}function o(f){return e.exit("chunkContent"),e.exit("content"),t(f)}function c(f){return e.consume(f),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,l}}function PA(e,t,r){const s=this;return l;function l(c){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),pt(e,o,"linePrefix")}function o(c){if(c===null||Ie(c))return r(c);const f=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&f&&f[1].type==="linePrefix"&&f[2].sliceSerialize(f[1],!0).length>=4?t(c):e.interrupt(s.parser.constructs.flow,r,t)(c)}}function f1(e,t,r,s,l,o,c,f,d){const m=d||Number.POSITIVE_INFINITY;let y=0;return g;function g(R){return R===60?(e.enter(s),e.enter(l),e.enter(o),e.consume(R),e.exit(o),x):R===null||R===32||R===41||Hu(R)?r(R):(e.enter(s),e.enter(c),e.enter(f),e.enter("chunkString",{contentType:"string"}),j(R))}function x(R){return R===62?(e.enter(o),e.consume(R),e.exit(o),e.exit(l),e.exit(s),t):(e.enter(f),e.enter("chunkString",{contentType:"string"}),v(R))}function v(R){return R===62?(e.exit("chunkString"),e.exit(f),x(R)):R===null||R===60||Ie(R)?r(R):(e.consume(R),R===92?S:v)}function S(R){return R===60||R===62||R===92?(e.consume(R),v):v(R)}function j(R){return!y&&(R===null||R===41||Rt(R))?(e.exit("chunkString"),e.exit(f),e.exit(c),e.exit(s),t(R)):y<m&&R===40?(e.consume(R),y++,j):R===41?(e.consume(R),y--,j):R===null||R===32||R===40||Hu(R)?r(R):(e.consume(R),R===92?D:j)}function D(R){return R===40||R===41||R===92?(e.consume(R),j):j(R)}}function h1(e,t,r,s,l,o){const c=this;let f=0,d;return m;function m(v){return e.enter(s),e.enter(l),e.consume(v),e.exit(l),e.enter(o),y}function y(v){return f>999||v===null||v===91||v===93&&!d||v===94&&!f&&"_hiddenFootnoteSupport"in c.parser.constructs?r(v):v===93?(e.exit(o),e.enter(l),e.consume(v),e.exit(l),e.exit(s),t):Ie(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),y):(e.enter("chunkString",{contentType:"string"}),g(v))}function g(v){return v===null||v===91||v===93||Ie(v)||f++>999?(e.exit("chunkString"),y(v)):(e.consume(v),d||(d=!at(v)),v===92?x:g)}function x(v){return v===91||v===92||v===93?(e.consume(v),f++,g):g(v)}}function d1(e,t,r,s,l,o){let c;return f;function f(x){return x===34||x===39||x===40?(e.enter(s),e.enter(l),e.consume(x),e.exit(l),c=x===40?41:x,d):r(x)}function d(x){return x===c?(e.enter(l),e.consume(x),e.exit(l),e.exit(s),t):(e.enter(o),m(x))}function m(x){return x===c?(e.exit(o),d(c)):x===null?r(x):Ie(x)?(e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),pt(e,m,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),y(x))}function y(x){return x===c||x===null||Ie(x)?(e.exit("chunkString"),m(x)):(e.consume(x),x===92?g:y)}function g(x){return x===c||x===92?(e.consume(x),y):y(x)}}function zl(e,t){let r;return s;function s(l){return Ie(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r=!0,s):at(l)?pt(e,s,r?"linePrefix":"lineSuffix")(l):t(l)}}const BA={name:"definition",tokenize:qA},HA={partial:!0,tokenize:IA};function qA(e,t,r){const s=this;let l;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return h1.call(s,e,f,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function f(v){return l=Tr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),d):r(v)}function d(v){return Rt(v)?zl(e,m)(v):m(v)}function m(v){return f1(e,y,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function y(v){return e.attempt(HA,g,g)(v)}function g(v){return at(v)?pt(e,x,"whitespace")(v):x(v)}function x(v){return v===null||Ie(v)?(e.exit("definition"),s.parser.defined.push(l),t(v)):r(v)}}function IA(e,t,r){return s;function s(f){return Rt(f)?zl(e,l)(f):r(f)}function l(f){return d1(e,o,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(f)}function o(f){return at(f)?pt(e,c,"whitespace")(f):c(f)}function c(f){return f===null||Ie(f)?t(f):r(f)}}const FA={name:"hardBreakEscape",tokenize:$A};function $A(e,t,r){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),l}function l(o){return Ie(o)?(e.exit("hardBreakEscape"),t(o)):r(o)}}const VA={name:"headingAtx",resolve:YA,tokenize:GA};function YA(e,t){let r=e.length-2,s=3,l,o;return e[s][1].type==="whitespace"&&(s+=2),r-2>s&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(s===r-1||r-4>s&&e[r-2][1].type==="whitespace")&&(r-=s+1===r?2:4),r>s&&(l={type:"atxHeadingText",start:e[s][1].start,end:e[r][1].end},o={type:"chunkText",start:e[s][1].start,end:e[r][1].end,contentType:"text"},rr(e,s,r-s+1,[["enter",l,t],["enter",o,t],["exit",o,t],["exit",l,t]])),e}function GA(e,t,r){let s=0;return l;function l(y){return e.enter("atxHeading"),o(y)}function o(y){return e.enter("atxHeadingSequence"),c(y)}function c(y){return y===35&&s++<6?(e.consume(y),c):y===null||Rt(y)?(e.exit("atxHeadingSequence"),f(y)):r(y)}function f(y){return y===35?(e.enter("atxHeadingSequence"),d(y)):y===null||Ie(y)?(e.exit("atxHeading"),t(y)):at(y)?pt(e,f,"whitespace")(y):(e.enter("atxHeadingText"),m(y))}function d(y){return y===35?(e.consume(y),d):(e.exit("atxHeadingSequence"),f(y))}function m(y){return y===null||y===35||Rt(y)?(e.exit("atxHeadingText"),f(y)):(e.consume(y),m)}}const JA=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],bb=["pre","script","style","textarea"],XA={concrete:!0,name:"htmlFlow",resolveTo:ZA,tokenize:WA},KA={partial:!0,tokenize:tj},QA={partial:!0,tokenize:ej};function ZA(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function WA(e,t,r){const s=this;let l,o,c,f,d;return m;function m(N){return y(N)}function y(N){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(N),g}function g(N){return N===33?(e.consume(N),x):N===47?(e.consume(N),o=!0,j):N===63?(e.consume(N),l=3,s.interrupt?t:C):Mn(N)?(e.consume(N),c=String.fromCharCode(N),D):r(N)}function x(N){return N===45?(e.consume(N),l=2,v):N===91?(e.consume(N),l=5,f=0,S):Mn(N)?(e.consume(N),l=4,s.interrupt?t:C):r(N)}function v(N){return N===45?(e.consume(N),s.interrupt?t:C):r(N)}function S(N){const ve="CDATA[";return N===ve.charCodeAt(f++)?(e.consume(N),f===ve.length?s.interrupt?t:I:S):r(N)}function j(N){return Mn(N)?(e.consume(N),c=String.fromCharCode(N),D):r(N)}function D(N){if(N===null||N===47||N===62||Rt(N)){const ve=N===47,Ce=c.toLowerCase();return!ve&&!o&&bb.includes(Ce)?(l=1,s.interrupt?t(N):I(N)):JA.includes(c.toLowerCase())?(l=6,ve?(e.consume(N),R):s.interrupt?t(N):I(N)):(l=7,s.interrupt&&!s.parser.lazy[s.now().line]?r(N):o?O(N):F(N))}return N===45||En(N)?(e.consume(N),c+=String.fromCharCode(N),D):r(N)}function R(N){return N===62?(e.consume(N),s.interrupt?t:I):r(N)}function O(N){return at(N)?(e.consume(N),O):z(N)}function F(N){return N===47?(e.consume(N),z):N===58||N===95||Mn(N)?(e.consume(N),ue):at(N)?(e.consume(N),F):z(N)}function ue(N){return N===45||N===46||N===58||N===95||En(N)?(e.consume(N),ue):H(N)}function H(N){return N===61?(e.consume(N),P):at(N)?(e.consume(N),H):F(N)}function P(N){return N===null||N===60||N===61||N===62||N===96?r(N):N===34||N===39?(e.consume(N),d=N,W):at(N)?(e.consume(N),P):G(N)}function W(N){return N===d?(e.consume(N),d=null,B):N===null||Ie(N)?r(N):(e.consume(N),W)}function G(N){return N===null||N===34||N===39||N===47||N===60||N===61||N===62||N===96||Rt(N)?H(N):(e.consume(N),G)}function B(N){return N===47||N===62||at(N)?F(N):r(N)}function z(N){return N===62?(e.consume(N),K):r(N)}function K(N){return N===null||Ie(N)?I(N):at(N)?(e.consume(N),K):r(N)}function I(N){return N===45&&l===2?(e.consume(N),V):N===60&&l===1?(e.consume(N),X):N===62&&l===4?(e.consume(N),L):N===63&&l===3?(e.consume(N),C):N===93&&l===5?(e.consume(N),we):Ie(N)&&(l===6||l===7)?(e.exit("htmlFlowData"),e.check(KA,J,oe)(N)):N===null||Ie(N)?(e.exit("htmlFlowData"),oe(N)):(e.consume(N),I)}function oe(N){return e.check(QA,ee,J)(N)}function ee(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),te}function te(N){return N===null||Ie(N)?oe(N):(e.enter("htmlFlowData"),I(N))}function V(N){return N===45?(e.consume(N),C):I(N)}function X(N){return N===47?(e.consume(N),c="",ge):I(N)}function ge(N){if(N===62){const ve=c.toLowerCase();return bb.includes(ve)?(e.consume(N),L):I(N)}return Mn(N)&&c.length<8?(e.consume(N),c+=String.fromCharCode(N),ge):I(N)}function we(N){return N===93?(e.consume(N),C):I(N)}function C(N){return N===62?(e.consume(N),L):N===45&&l===2?(e.consume(N),C):I(N)}function L(N){return N===null||Ie(N)?(e.exit("htmlFlowData"),J(N)):(e.consume(N),L)}function J(N){return e.exit("htmlFlow"),t(N)}}function ej(e,t,r){const s=this;return l;function l(c){return Ie(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o):r(c)}function o(c){return s.parser.lazy[s.now().line]?r(c):t(c)}}function tj(e,t,r){return s;function s(l){return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),e.attempt(Ql,t,r)}}const nj={name:"htmlText",tokenize:rj};function rj(e,t,r){const s=this;let l,o,c;return f;function f(C){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(C),d}function d(C){return C===33?(e.consume(C),m):C===47?(e.consume(C),H):C===63?(e.consume(C),F):Mn(C)?(e.consume(C),G):r(C)}function m(C){return C===45?(e.consume(C),y):C===91?(e.consume(C),o=0,S):Mn(C)?(e.consume(C),O):r(C)}function y(C){return C===45?(e.consume(C),v):r(C)}function g(C){return C===null?r(C):C===45?(e.consume(C),x):Ie(C)?(c=g,X(C)):(e.consume(C),g)}function x(C){return C===45?(e.consume(C),v):g(C)}function v(C){return C===62?V(C):C===45?x(C):g(C)}function S(C){const L="CDATA[";return C===L.charCodeAt(o++)?(e.consume(C),o===L.length?j:S):r(C)}function j(C){return C===null?r(C):C===93?(e.consume(C),D):Ie(C)?(c=j,X(C)):(e.consume(C),j)}function D(C){return C===93?(e.consume(C),R):j(C)}function R(C){return C===62?V(C):C===93?(e.consume(C),R):j(C)}function O(C){return C===null||C===62?V(C):Ie(C)?(c=O,X(C)):(e.consume(C),O)}function F(C){return C===null?r(C):C===63?(e.consume(C),ue):Ie(C)?(c=F,X(C)):(e.consume(C),F)}function ue(C){return C===62?V(C):F(C)}function H(C){return Mn(C)?(e.consume(C),P):r(C)}function P(C){return C===45||En(C)?(e.consume(C),P):W(C)}function W(C){return Ie(C)?(c=W,X(C)):at(C)?(e.consume(C),W):V(C)}function G(C){return C===45||En(C)?(e.consume(C),G):C===47||C===62||Rt(C)?B(C):r(C)}function B(C){return C===47?(e.consume(C),V):C===58||C===95||Mn(C)?(e.consume(C),z):Ie(C)?(c=B,X(C)):at(C)?(e.consume(C),B):V(C)}function z(C){return C===45||C===46||C===58||C===95||En(C)?(e.consume(C),z):K(C)}function K(C){return C===61?(e.consume(C),I):Ie(C)?(c=K,X(C)):at(C)?(e.consume(C),K):B(C)}function I(C){return C===null||C===60||C===61||C===62||C===96?r(C):C===34||C===39?(e.consume(C),l=C,oe):Ie(C)?(c=I,X(C)):at(C)?(e.consume(C),I):(e.consume(C),ee)}function oe(C){return C===l?(e.consume(C),l=void 0,te):C===null?r(C):Ie(C)?(c=oe,X(C)):(e.consume(C),oe)}function ee(C){return C===null||C===34||C===39||C===60||C===61||C===96?r(C):C===47||C===62||Rt(C)?B(C):(e.consume(C),ee)}function te(C){return C===47||C===62||Rt(C)?B(C):r(C)}function V(C){return C===62?(e.consume(C),e.exit("htmlTextData"),e.exit("htmlText"),t):r(C)}function X(C){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),ge}function ge(C){return at(C)?pt(e,we,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):we(C)}function we(C){return e.enter("htmlTextData"),c(C)}}const nm={name:"labelEnd",resolveAll:lj,resolveTo:oj,tokenize:uj},ij={tokenize:cj},sj={tokenize:fj},aj={tokenize:hj};function lj(e){let t=-1;const r=[];for(;++t<e.length;){const s=e[t][1];if(r.push(e[t]),s.type==="labelImage"||s.type==="labelLink"||s.type==="labelEnd"){const l=s.type==="labelImage"?4:2;s.type="data",t+=l}}return e.length!==r.length&&rr(e,0,e.length,r),e}function oj(e,t){let r=e.length,s=0,l,o,c,f;for(;r--;)if(l=e[r][1],o){if(l.type==="link"||l.type==="labelLink"&&l._inactive)break;e[r][0]==="enter"&&l.type==="labelLink"&&(l._inactive=!0)}else if(c){if(e[r][0]==="enter"&&(l.type==="labelImage"||l.type==="labelLink")&&!l._balanced&&(o=r,l.type!=="labelLink")){s=2;break}}else l.type==="labelEnd"&&(c=r);const d={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},m={type:"label",start:{...e[o][1].start},end:{...e[c][1].end}},y={type:"labelText",start:{...e[o+s+2][1].end},end:{...e[c-2][1].start}};return f=[["enter",d,t],["enter",m,t]],f=xr(f,e.slice(o+1,o+s+3)),f=xr(f,[["enter",y,t]]),f=xr(f,ec(t.parser.constructs.insideSpan.null,e.slice(o+s+4,c-3),t)),f=xr(f,[["exit",y,t],e[c-2],e[c-1],["exit",m,t]]),f=xr(f,e.slice(c+1)),f=xr(f,[["exit",d,t]]),rr(e,o,e.length,f),e}function uj(e,t,r){const s=this;let l=s.events.length,o,c;for(;l--;)if((s.events[l][1].type==="labelImage"||s.events[l][1].type==="labelLink")&&!s.events[l][1]._balanced){o=s.events[l][1];break}return f;function f(x){return o?o._inactive?g(x):(c=s.parser.defined.includes(Tr(s.sliceSerialize({start:o.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(x),e.exit("labelMarker"),e.exit("labelEnd"),d):r(x)}function d(x){return x===40?e.attempt(ij,y,c?y:g)(x):x===91?e.attempt(sj,y,c?m:g)(x):c?y(x):g(x)}function m(x){return e.attempt(aj,y,g)(x)}function y(x){return t(x)}function g(x){return o._balanced=!0,r(x)}}function cj(e,t,r){return s;function s(g){return e.enter("resource"),e.enter("resourceMarker"),e.consume(g),e.exit("resourceMarker"),l}function l(g){return Rt(g)?zl(e,o)(g):o(g)}function o(g){return g===41?y(g):f1(e,c,f,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(g)}function c(g){return Rt(g)?zl(e,d)(g):y(g)}function f(g){return r(g)}function d(g){return g===34||g===39||g===40?d1(e,m,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(g):y(g)}function m(g){return Rt(g)?zl(e,y)(g):y(g)}function y(g){return g===41?(e.enter("resourceMarker"),e.consume(g),e.exit("resourceMarker"),e.exit("resource"),t):r(g)}}function fj(e,t,r){const s=this;return l;function l(f){return h1.call(s,e,o,c,"reference","referenceMarker","referenceString")(f)}function o(f){return s.parser.defined.includes(Tr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(f):r(f)}function c(f){return r(f)}}function hj(e,t,r){return s;function s(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),l}function l(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),t):r(o)}}const dj={name:"labelStartImage",resolveAll:nm.resolveAll,tokenize:mj};function mj(e,t,r){const s=this;return l;function l(f){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(f),e.exit("labelImageMarker"),o}function o(f){return f===91?(e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelImage"),c):r(f)}function c(f){return f===94&&"_hiddenFootnoteSupport"in s.parser.constructs?r(f):t(f)}}const pj={name:"labelStartLink",resolveAll:nm.resolveAll,tokenize:gj};function gj(e,t,r){const s=this;return l;function l(c){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelLink"),o}function o(c){return c===94&&"_hiddenFootnoteSupport"in s.parser.constructs?r(c):t(c)}}const Bh={name:"lineEnding",tokenize:yj};function yj(e,t){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),pt(e,t,"linePrefix")}}const Au={name:"thematicBreak",tokenize:bj};function bj(e,t,r){let s=0,l;return o;function o(m){return e.enter("thematicBreak"),c(m)}function c(m){return l=m,f(m)}function f(m){return m===l?(e.enter("thematicBreakSequence"),d(m)):s>=3&&(m===null||Ie(m))?(e.exit("thematicBreak"),t(m)):r(m)}function d(m){return m===l?(e.consume(m),s++,d):(e.exit("thematicBreakSequence"),at(m)?pt(e,f,"whitespace")(m):f(m))}}const qn={continuation:{tokenize:Sj},exit:kj,name:"list",tokenize:wj},xj={partial:!0,tokenize:Ej},vj={partial:!0,tokenize:_j};function wj(e,t,r){const s=this,l=s.events[s.events.length-1];let o=l&&l[1].type==="linePrefix"?l[2].sliceSerialize(l[1],!0).length:0,c=0;return f;function f(v){const S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Sd(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(Au,r,m)(v):m(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(v)}return r(v)}function d(v){return Sd(v)&&++c<10?(e.consume(v),d):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),m(v)):r(v)}function m(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Ql,s.interrupt?r:y,e.attempt(xj,x,g))}function y(v){return s.containerState.initialBlankLine=!0,o++,x(v)}function g(v){return at(v)?(e.enter("listItemPrefixWhitespace"),e.consume(v),e.exit("listItemPrefixWhitespace"),x):r(v)}function x(v){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(v)}}function Sj(e,t,r){const s=this;return s.containerState._closeFlow=void 0,e.check(Ql,l,o);function l(f){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,pt(e,t,"listItemIndent",s.containerState.size+1)(f)}function o(f){return s.containerState.furtherBlankLines||!at(f)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(f)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(vj,t,c)(f))}function c(f){return s.containerState._closeFlow=!0,s.interrupt=void 0,pt(e,e.attempt(qn,t,r),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(f)}}function _j(e,t,r){const s=this;return pt(e,l,"listItemIndent",s.containerState.size+1);function l(o){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(o):r(o)}}function kj(e){e.exit(this.containerState.type)}function Ej(e,t,r){const s=this;return pt(e,l,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function l(o){const c=s.events[s.events.length-1];return!at(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):r(o)}}const xb={name:"setextUnderline",resolveTo:Cj,tokenize:Aj};function Cj(e,t){let r=e.length,s,l,o;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){s=r;break}e[r][1].type==="paragraph"&&(l=r)}else e[r][1].type==="content"&&e.splice(r,1),!o&&e[r][1].type==="definition"&&(o=r);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[l][1].type="setextHeadingText",o?(e.splice(l,0,["enter",c,t]),e.splice(o+1,0,["exit",e[s][1],t]),e[s][1].end={...e[o][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function Aj(e,t,r){const s=this;let l;return o;function o(m){let y=s.events.length,g;for(;y--;)if(s.events[y][1].type!=="lineEnding"&&s.events[y][1].type!=="linePrefix"&&s.events[y][1].type!=="content"){g=s.events[y][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||g)?(e.enter("setextHeadingLine"),l=m,c(m)):r(m)}function c(m){return e.enter("setextHeadingLineSequence"),f(m)}function f(m){return m===l?(e.consume(m),f):(e.exit("setextHeadingLineSequence"),at(m)?pt(e,d,"lineSuffix")(m):d(m))}function d(m){return m===null||Ie(m)?(e.exit("setextHeadingLine"),t(m)):r(m)}}const jj={tokenize:Nj};function Nj(e){const t=this,r=e.attempt(Ql,s,e.attempt(this.parser.constructs.flowInitial,l,pt(e,e.attempt(this.parser.constructs.flow,l,e.attempt(DA,l)),"linePrefix")));return r;function s(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function l(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const Tj={resolveAll:p1()},Oj=m1("string"),Rj=m1("text");function m1(e){return{resolveAll:p1(e==="text"?Mj:void 0),tokenize:t};function t(r){const s=this,l=this.parser.constructs[e],o=r.attempt(l,c,f);return c;function c(y){return m(y)?o(y):f(y)}function f(y){if(y===null){r.consume(y);return}return r.enter("data"),r.consume(y),d}function d(y){return m(y)?(r.exit("data"),o(y)):(r.consume(y),d)}function m(y){if(y===null)return!0;const g=l[y];let x=-1;if(g)for(;++x<g.length;){const v=g[x];if(!v.previous||v.previous.call(s,s.previous))return!0}return!1}}}function p1(e){return t;function t(r,s){let l=-1,o;for(;++l<=r.length;)o===void 0?r[l]&&r[l][1].type==="data"&&(o=l,l++):(!r[l]||r[l][1].type!=="data")&&(l!==o+2&&(r[o][1].end=r[l-1][1].end,r.splice(o+2,l-o-2),l=o+2),o=void 0);return e?e(r,s):r}}function Mj(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const s=e[r-1][1],l=t.sliceStream(s);let o=l.length,c=-1,f=0,d;for(;o--;){const m=l[o];if(typeof m=="string"){for(c=m.length;m.charCodeAt(c-1)===32;)f++,c--;if(c)break;c=-1}else if(m===-2)d=!0,f++;else if(m!==-1){o++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(f=0),f){const m={type:r===e.length||d||f<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?c:s.start._bufferIndex+c,_index:s.start._index+o,line:s.end.line,column:s.end.column-f,offset:s.end.offset-f},end:{...s.end}};s.end={...m.start},s.start.offset===s.end.offset?Object.assign(s,m):(e.splice(r,0,["enter",m,t],["exit",m,t]),r+=2)}r++}return e}const Dj={42:qn,43:qn,45:qn,48:qn,49:qn,50:qn,51:qn,52:qn,53:qn,54:qn,55:qn,56:qn,57:qn,62:l1},Lj={91:BA},zj={[-2]:Ph,[-1]:Ph,32:Ph},Uj={35:VA,42:Au,45:[xb,Au],60:XA,61:xb,95:Au,96:yb,126:yb},Pj={38:u1,92:o1},Bj={[-5]:Bh,[-4]:Bh,[-3]:Bh,33:dj,38:u1,42:_d,60:[pA,nj],91:pj,92:[FA,o1],93:nm,95:_d,96:jA},Hj={null:[_d,Tj]},qj={null:[42,95]},Ij={null:[]},Fj=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:qj,contentInitial:Lj,disable:Ij,document:Dj,flow:Uj,flowInitial:zj,insideSpan:Hj,string:Pj,text:Bj},Symbol.toStringTag,{value:"Module"}));function $j(e,t,r){let s={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const l={},o=[];let c=[],f=[];const d={attempt:W(H),check:W(P),consume:O,enter:F,exit:ue,interrupt:W(P,{interrupt:!0})},m={code:null,containerState:{},defineSkip:j,events:[],now:S,parser:e,previous:null,sliceSerialize:x,sliceStream:v,write:g};let y=t.tokenize.call(m,d);return t.resolveAll&&o.push(t),m;function g(K){return c=xr(c,K),D(),c[c.length-1]!==null?[]:(G(t,0),m.events=ec(o,m.events,m),m.events)}function x(K,I){return Yj(v(K),I)}function v(K){return Vj(c,K)}function S(){const{_bufferIndex:K,_index:I,line:oe,column:ee,offset:te}=s;return{_bufferIndex:K,_index:I,line:oe,column:ee,offset:te}}function j(K){l[K.line]=K.column,z()}function D(){let K;for(;s._index<c.length;){const I=c[s._index];if(typeof I=="string")for(K=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===K&&s._bufferIndex<I.length;)R(I.charCodeAt(s._bufferIndex));else R(I)}}function R(K){y=y(K)}function O(K){Ie(K)?(s.line++,s.column=1,s.offset+=K===-3?2:1,z()):K!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===c[s._index].length&&(s._bufferIndex=-1,s._index++)),m.previous=K}function F(K,I){const oe=I||{};return oe.type=K,oe.start=S(),m.events.push(["enter",oe,m]),f.push(oe),oe}function ue(K){const I=f.pop();return I.end=S(),m.events.push(["exit",I,m]),I}function H(K,I){G(K,I.from)}function P(K,I){I.restore()}function W(K,I){return oe;function oe(ee,te,V){let X,ge,we,C;return Array.isArray(ee)?J(ee):"tokenize"in ee?J([ee]):L(ee);function L(ke){return je;function je(Ve){const ae=Ve!==null&&ke[Ve],De=Ve!==null&&ke.null,rt=[...Array.isArray(ae)?ae:ae?[ae]:[],...Array.isArray(De)?De:De?[De]:[]];return J(rt)(Ve)}}function J(ke){return X=ke,ge=0,ke.length===0?V:N(ke[ge])}function N(ke){return je;function je(Ve){return C=B(),we=ke,ke.partial||(m.currentConstruct=ke),ke.name&&m.parser.constructs.disable.null.includes(ke.name)?Ce():ke.tokenize.call(I?Object.assign(Object.create(m),I):m,d,ve,Ce)(Ve)}}function ve(ke){return K(we,C),te}function Ce(ke){return C.restore(),++ge<X.length?N(X[ge]):V}}}function G(K,I){K.resolveAll&&!o.includes(K)&&o.push(K),K.resolve&&rr(m.events,I,m.events.length-I,K.resolve(m.events.slice(I),m)),K.resolveTo&&(m.events=K.resolveTo(m.events,m))}function B(){const K=S(),I=m.previous,oe=m.currentConstruct,ee=m.events.length,te=Array.from(f);return{from:ee,restore:V};function V(){s=K,m.previous=I,m.currentConstruct=oe,m.events.length=ee,f=te,z()}}function z(){s.line in l&&s.column<2&&(s.column=l[s.line],s.offset+=l[s.line]-1)}}function Vj(e,t){const r=t.start._index,s=t.start._bufferIndex,l=t.end._index,o=t.end._bufferIndex;let c;if(r===l)c=[e[r].slice(s,o)];else{if(c=e.slice(r,l),s>-1){const f=c[0];typeof f=="string"?c[0]=f.slice(s):c.shift()}o>0&&c.push(e[l].slice(0,o))}return c}function Yj(e,t){let r=-1;const s=[];let l;for(;++r<e.length;){const o=e[r];let c;if(typeof o=="string")c=o;else switch(o){case-5:{c="\r";break}case-4:{c=`
@@ -114,4 +114,4 @@ ${x.username}`))})}),b.jsx("div",{className:"confirm-modal-actions",children:b.j
114
114
  `))+1))}const c="#".repeat(l),f=r.enter("headingAtx"),d=r.enter("phrasing");o.move(c+" ");let m=r.containerPhrasing(e,{before:"# ",after:`
115
115
  `,...o.current()});return/^[\t ]/.test(m)&&(m=Vl(m.charCodeAt(0))+m.slice(1)),m=m?c+" "+m:c,r.options.closeAtx&&(m+=" "+c),d(),f(),m}D1.peek=O3;function D1(e){return e.value||""}function O3(){return"<"}L1.peek=R3;function L1(e,t,r,s){const l=um(r),o=l==='"'?"Quote":"Apostrophe",c=r.enter("image");let f=r.enter("label");const d=r.createTracker(s);let m=d.move("![");return m+=d.move(r.safe(e.alt,{before:m,after:"]",...d.current()})),m+=d.move("]("),f(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(f=r.enter("destinationLiteral"),m+=d.move("<"),m+=d.move(r.safe(e.url,{before:m,after:">",...d.current()})),m+=d.move(">")):(f=r.enter("destinationRaw"),m+=d.move(r.safe(e.url,{before:m,after:e.title?" ":")",...d.current()}))),f(),e.title&&(f=r.enter(`title${o}`),m+=d.move(" "+l),m+=d.move(r.safe(e.title,{before:m,after:l,...d.current()})),m+=d.move(l),f()),m+=d.move(")"),c(),m}function R3(){return"!"}z1.peek=M3;function z1(e,t,r,s){const l=e.referenceType,o=r.enter("imageReference");let c=r.enter("label");const f=r.createTracker(s);let d=f.move("![");const m=r.safe(e.alt,{before:d,after:"]",...f.current()});d+=f.move(m+"]["),c();const y=r.stack;r.stack=[],c=r.enter("reference");const g=r.safe(r.associationId(e),{before:d,after:"]",...f.current()});return c(),r.stack=y,o(),l==="full"||!m||m!==g?d+=f.move(g+"]"):l==="shortcut"?d=d.slice(0,-1):d+=f.move("]"),d}function M3(){return"!"}U1.peek=D3;function U1(e,t,r){let s=e.value||"",l="`",o=-1;for(;new RegExp("(^|[^`])"+l+"([^`]|$)").test(s);)l+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o<r.unsafe.length;){const c=r.unsafe[o],f=r.compilePattern(c);let d;if(c.atBreak)for(;d=f.exec(s);){let m=d.index;s.charCodeAt(m)===10&&s.charCodeAt(m-1)===13&&m--,s=s.slice(0,m)+" "+s.slice(d.index+1)}}return l+s+l}function D3(){return"`"}function P1(e,t){const r=em(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}B1.peek=L3;function B1(e,t,r,s){const l=um(r),o=l==='"'?"Quote":"Apostrophe",c=r.createTracker(s);let f,d;if(P1(e,r)){const y=r.stack;r.stack=[],f=r.enter("autolink");let g=c.move("<");return g+=c.move(r.containerPhrasing(e,{before:g,after:">",...c.current()})),g+=c.move(">"),f(),r.stack=y,g}f=r.enter("link"),d=r.enter("label");let m=c.move("[");return m+=c.move(r.containerPhrasing(e,{before:m,after:"](",...c.current()})),m+=c.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=r.enter("destinationLiteral"),m+=c.move("<"),m+=c.move(r.safe(e.url,{before:m,after:">",...c.current()})),m+=c.move(">")):(d=r.enter("destinationRaw"),m+=c.move(r.safe(e.url,{before:m,after:e.title?" ":")",...c.current()}))),d(),e.title&&(d=r.enter(`title${o}`),m+=c.move(" "+l),m+=c.move(r.safe(e.title,{before:m,after:l,...c.current()})),m+=c.move(l),d()),m+=c.move(")"),f(),m}function L3(e,t,r){return P1(e,r)?"<":"["}H1.peek=z3;function H1(e,t,r,s){const l=e.referenceType,o=r.enter("linkReference");let c=r.enter("label");const f=r.createTracker(s);let d=f.move("[");const m=r.containerPhrasing(e,{before:d,after:"]",...f.current()});d+=f.move(m+"]["),c();const y=r.stack;r.stack=[],c=r.enter("reference");const g=r.safe(r.associationId(e),{before:d,after:"]",...f.current()});return c(),r.stack=y,o(),l==="full"||!m||m!==g?d+=f.move(g+"]"):l==="shortcut"?d=d.slice(0,-1):d+=f.move("]"),d}function z3(){return"["}function cm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function U3(e){const t=cm(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function P3(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function q1(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function B3(e,t,r,s){const l=r.enter("list"),o=r.bulletCurrent;let c=e.ordered?P3(r):cm(r);const f=e.ordered?c==="."?")":".":U3(r);let d=t&&r.bulletLastUsed?c===r.bulletLastUsed:!1;if(!e.ordered){const y=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&y&&(!y.children||!y.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(d=!0),q1(r)===c&&y){let g=-1;for(;++g<e.children.length;){const x=e.children[g];if(x&&x.type==="listItem"&&x.children&&x.children[0]&&x.children[0].type==="thematicBreak"){d=!0;break}}}}d&&(c=f),r.bulletCurrent=c;const m=r.containerFlow(e,s);return r.bulletLastUsed=c,r.bulletCurrent=o,l(),m}function H3(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function q3(e,t,r,s){const l=H3(r);let o=r.bulletCurrent||cm(r);t&&t.type==="list"&&t.ordered&&(o=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(l==="tab"||l==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const f=r.createTracker(s);f.move(o+" ".repeat(c-o.length)),f.shift(c);const d=r.enter("listItem"),m=r.indentLines(r.containerFlow(e,f.current()),y);return d(),m;function y(g,x,v){return x?(v?"":" ".repeat(c))+g:(v?o:o+" ".repeat(c-o.length))+g}}function I3(e,t,r,s){const l=r.enter("paragraph"),o=r.enter("phrasing"),c=r.containerPhrasing(e,s);return o(),l(),c}const F3=nc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function $3(e,t,r,s){return(e.children.some(function(c){return F3(c)})?r.containerPhrasing:r.containerFlow).call(r,e,s)}function V3(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}I1.peek=Y3;function I1(e,t,r,s){const l=V3(r),o=r.enter("strong"),c=r.createTracker(s),f=c.move(l+l);let d=c.move(r.containerPhrasing(e,{after:l,before:f,...c.current()}));const m=d.charCodeAt(0),y=Fu(s.before.charCodeAt(s.before.length-1),m,l);y.inside&&(d=Vl(m)+d.slice(1));const g=d.charCodeAt(d.length-1),x=Fu(s.after.charCodeAt(0),g,l);x.inside&&(d=d.slice(0,-1)+Vl(g));const v=c.move(l+l);return o(),r.attentionEncodeSurroundingInfo={after:x.outside,before:y.outside},f+d+v}function Y3(e,t,r){return r.options.strong||"*"}function G3(e,t,r,s){return r.safe(e.value,s)}function J3(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function X3(e,t,r){const s=(q1(r)+(r.options.ruleSpaces?" ":"")).repeat(J3(r));return r.options.ruleSpaces?s.slice(0,-1):s}const F1={blockquote:b3,break:Hb,code:k3,definition:C3,emphasis:M1,hardBreak:Hb,heading:T3,html:D1,image:L1,imageReference:z1,inlineCode:U1,link:B1,linkReference:H1,list:B3,listItem:q3,paragraph:I3,root:$3,strong:I1,text:G3,thematicBreak:X3};function K3(){return{enter:{table:Q3,tableData:qb,tableHeader:qb,tableRow:W3},exit:{codeText:eO,table:Z3,tableData:Qh,tableHeader:Qh,tableRow:Qh}}}function Q3(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function Z3(e){this.exit(e),this.data.inTable=void 0}function W3(e){this.enter({type:"tableRow",children:[]},e)}function Qh(e){this.exit(e)}function qb(e){this.enter({type:"tableCell",children:[]},e)}function eO(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,tO));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function tO(e,t){return t==="|"?t:e}function nO(e){const t=e||{},r=t.tableCellPadding,s=t.tablePipeAlign,l=t.stringLength,o=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
116
116
  `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:x,table:c,tableCell:d,tableRow:f}};function c(v,S,j,D){return m(y(v,j,D),v.align)}function f(v,S,j,D){const R=g(v,j,D),O=m([R]);return O.slice(0,O.indexOf(`
117
- `))}function d(v,S,j,D){const R=j.enter("tableCell"),O=j.enter("phrasing"),F=j.containerPhrasing(v,{...D,before:o,after:o});return O(),R(),F}function m(v,S){return g3(v,{align:S,alignDelimiters:s,padding:r,stringLength:l})}function y(v,S,j){const D=v.children;let R=-1;const O=[],F=S.enter("table");for(;++R<D.length;)O[R]=g(D[R],S,j);return F(),O}function g(v,S,j){const D=v.children;let R=-1;const O=[],F=S.enter("tableRow");for(;++R<D.length;)O[R]=d(D[R],v,S,j);return F(),O}function x(v,S,j){let D=F1.inlineCode(v,S,j);return j.stack.includes("tableCell")&&(D=D.replace(/\|/g,"\\$&")),D}}function rO(){return{exit:{taskListCheckValueChecked:Ib,taskListCheckValueUnchecked:Ib,paragraph:sO}}}function iO(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:aO}}}function Ib(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function sO(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const l=t.children;let o=-1,c;for(;++o<l.length;){const f=l[o];if(f.type==="paragraph"){c=f;break}}c===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function aO(e,t,r,s){const l=e.children[0],o=typeof e.checked=="boolean"&&l&&l.type==="paragraph",c="["+(e.checked?"x":" ")+"] ",f=r.createTracker(s);o&&f.move(c);let d=F1.listItem(e,t,r,{...s,...f.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),d;function m(y){return y+c}}function lO(){return[BT(),a3(),c3(),K3(),rO()]}function oO(e){return{extensions:[HT(),l3(e),f3(),nO(e),iO()]}}const uO={tokenize:pO,partial:!0},$1={tokenize:gO,partial:!0},V1={tokenize:yO,partial:!0},Y1={tokenize:bO,partial:!0},cO={tokenize:xO,partial:!0},G1={name:"wwwAutolink",tokenize:dO,previous:X1},J1={name:"protocolAutolink",tokenize:mO,previous:K1},xi={name:"emailAutolink",tokenize:hO,previous:Q1},$r={};function fO(){return{text:$r}}let vs=48;for(;vs<123;)$r[vs]=xi,vs++,vs===58?vs=65:vs===91&&(vs=97);$r[43]=xi;$r[45]=xi;$r[46]=xi;$r[95]=xi;$r[72]=[xi,J1];$r[104]=[xi,J1];$r[87]=[xi,G1];$r[119]=[xi,G1];function hO(e,t,r){const s=this;let l,o;return c;function c(g){return!jd(g)||!Q1.call(s,s.previous)||fm(s.events)?r(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return jd(g)?(e.consume(g),f):g===64?(e.consume(g),d):r(g)}function d(g){return g===46?e.check(cO,y,m)(g):g===45||g===95||En(g)?(o=!0,e.consume(g),d):y(g)}function m(g){return e.consume(g),l=!0,d}function y(g){return o&&l&&Mn(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):r(g)}}function dO(e,t,r){const s=this;return l;function l(c){return c!==87&&c!==119||!X1.call(s,s.previous)||fm(s.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(uO,e.attempt($1,e.attempt(V1,o),r),r)(c))}function o(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function mO(e,t,r){const s=this;let l="",o=!1;return c;function c(g){return(g===72||g===104)&&K1.call(s,s.previous)&&!fm(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),l+=String.fromCodePoint(g),e.consume(g),f):r(g)}function f(g){if(Mn(g)&&l.length<5)return l+=String.fromCodePoint(g),e.consume(g),f;if(g===58){const x=l.toLowerCase();if(x==="http"||x==="https")return e.consume(g),d}return r(g)}function d(g){return g===47?(e.consume(g),o?m:(o=!0,d)):r(g)}function m(g){return g===null||Hu(g)||Rt(g)||_s(g)||Wu(g)?r(g):e.attempt($1,e.attempt(V1,y),r)(g)}function y(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function pO(e,t,r){let s=0;return l;function l(c){return(c===87||c===119)&&s<3?(s++,e.consume(c),l):c===46&&s===3?(e.consume(c),o):r(c)}function o(c){return c===null?r(c):t(c)}}function gO(e,t,r){let s,l,o;return c;function c(m){return m===46||m===95?e.check(Y1,d,f)(m):m===null||Rt(m)||_s(m)||m!==45&&Wu(m)?d(m):(o=!0,e.consume(m),c)}function f(m){return m===95?s=!0:(l=s,s=void 0),e.consume(m),c}function d(m){return l||s||!o?r(m):t(m)}}function yO(e,t){let r=0,s=0;return l;function l(c){return c===40?(r++,e.consume(c),l):c===41&&s<r?o(c):c===33||c===34||c===38||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===60||c===63||c===93||c===95||c===126?e.check(Y1,t,o)(c):c===null||Rt(c)||_s(c)?t(c):(e.consume(c),l)}function o(c){return c===41&&s++,e.consume(c),l}}function bO(e,t,r){return s;function s(f){return f===33||f===34||f===39||f===41||f===42||f===44||f===46||f===58||f===59||f===63||f===95||f===126?(e.consume(f),s):f===38?(e.consume(f),o):f===93?(e.consume(f),l):f===60||f===null||Rt(f)||_s(f)?t(f):r(f)}function l(f){return f===null||f===40||f===91||Rt(f)||_s(f)?t(f):s(f)}function o(f){return Mn(f)?c(f):r(f)}function c(f){return f===59?(e.consume(f),s):Mn(f)?(e.consume(f),c):r(f)}}function xO(e,t,r){return s;function s(o){return e.consume(o),l}function l(o){return En(o)?r(o):t(o)}}function X1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Rt(e)}function K1(e){return!Mn(e)}function Q1(e){return!(e===47||jd(e))}function jd(e){return e===43||e===45||e===46||e===95||En(e)}function fm(e){let t=e.length,r=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const vO={tokenize:jO,partial:!0};function wO(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:EO,continuation:{tokenize:CO},exit:AO}},text:{91:{name:"gfmFootnoteCall",tokenize:kO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:SO,resolveTo:_O}}}}function SO(e,t,r){const s=this;let l=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;l--;){const d=s.events[l][1];if(d.type==="labelImage"){c=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return f;function f(d){if(!c||!c._balanced)return r(d);const m=Tr(s.sliceSerialize({start:c.end,end:s.now()}));return m.codePointAt(0)!==94||!o.includes(m.slice(1))?r(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),t(d))}}function _O(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},l={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};l.end.column++,l.end.offset++,l.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},l.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},f=[e[r+1],e[r+2],["enter",s,t],e[r+3],e[r+4],["enter",l,t],["exit",l,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(r,e.length-r+1,...f),e}function kO(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return f;function f(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),d}function d(g){return g!==94?r(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",m)}function m(g){if(o>999||g===93&&!c||g===null||g===91||Rt(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return l.includes(Tr(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(g)}return Rt(g)||(c=!0),o++,e.consume(g),g===92?y:m}function y(g){return g===91||g===92||g===93?(e.consume(g),o++,m):m(g)}}function EO(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,f;return d;function d(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),m}function m(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",y):r(S)}function y(S){if(c>999||S===93&&!f||S===null||S===91||Rt(S))return r(S);if(S===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return o=Tr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return Rt(S)||(f=!0),c++,e.consume(S),S===92?g:y}function g(S){return S===91||S===92||S===93?(e.consume(S),c++,y):y(S)}function x(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),l.includes(o)||l.push(o),pt(e,v,"gfmFootnoteDefinitionWhitespace")):r(S)}function v(S){return t(S)}}function CO(e,t,r){return e.check(Ql,t,e.attempt(vO,t,r))}function AO(e){e.exit("gfmFootnoteDefinition")}function jO(e,t,r){const s=this;return pt(e,l,"gfmFootnoteDefinitionIndent",5);function l(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):r(o)}}function NO(e){let r=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:l};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function l(c,f){let d=-1;for(;++d<c.length;)if(c[d][0]==="enter"&&c[d][1].type==="strikethroughSequenceTemporary"&&c[d][1]._close){let m=d;for(;m--;)if(c[m][0]==="exit"&&c[m][1].type==="strikethroughSequenceTemporary"&&c[m][1]._open&&c[d][1].end.offset-c[d][1].start.offset===c[m][1].end.offset-c[m][1].start.offset){c[d][1].type="strikethroughSequence",c[m][1].type="strikethroughSequence";const y={type:"strikethrough",start:Object.assign({},c[m][1].start),end:Object.assign({},c[d][1].end)},g={type:"strikethroughText",start:Object.assign({},c[m][1].end),end:Object.assign({},c[d][1].start)},x=[["enter",y,f],["enter",c[m][1],f],["exit",c[m][1],f],["enter",g,f]],v=f.parser.constructs.insideSpan.null;v&&rr(x,x.length,0,ec(v,c.slice(m+1,d),f)),rr(x,x.length,0,[["exit",g,f],["enter",c[d][1],f],["exit",c[d][1],f],["exit",y,f]]),rr(c,m-1,d-m+3,x),d=m+x.length-2;break}}for(d=-1;++d<c.length;)c[d][1].type==="strikethroughSequenceTemporary"&&(c[d][1].type="data");return c}function o(c,f,d){const m=this.previous,y=this.events;let g=0;return x;function x(S){return m===126&&y[y.length-1][1].type!=="characterEscape"?d(S):(c.enter("strikethroughSequenceTemporary"),v(S))}function v(S){const j=ka(m);if(S===126)return g>1?d(S):(c.consume(S),g++,v);if(g<2&&!r)return d(S);const D=c.exit("strikethroughSequenceTemporary"),R=ka(S);return D._open=!R||R===2&&!!j,D._close=!j||j===2&&!!R,f(S)}}}class TO{constructor(){this.map=[]}add(t,r,s){OO(this,t,r,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];s.push(t.slice()),t.length=0;let l=s.pop();for(;l;){for(const o of l)t.push(o);l=s.pop()}this.map.length=0}}function OO(e,t,r,s){let l=0;if(!(r===0&&s.length===0)){for(;l<e.map.length;){if(e.map[l][0]===t){e.map[l][1]+=r,e.map[l][2].push(...s);return}l+=1}e.map.push([t,r,s])}}function RO(e,t){let r=!1;const s=[];for(;t<e.length;){const l=e[t];if(r){if(l[0]==="enter")l[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(l[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const o=s.length-1;s[o]=s[o]==="left"?"center":"right"}}else if(l[1].type==="tableDelimiterRow")break}else l[0]==="enter"&&l[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return s}function MO(){return{flow:{null:{name:"table",tokenize:DO,resolveAll:LO}}}}function DO(e,t,r){const s=this;let l=0,o=0,c;return f;function f(z){let K=s.events.length-1;for(;K>-1;){const ee=s.events[K][1].type;if(ee==="lineEnding"||ee==="linePrefix")K--;else break}const I=K>-1?s.events[K][1].type:null,oe=I==="tableHead"||I==="tableRow"?P:d;return oe===P&&s.parser.lazy[s.now().line]?r(z):oe(z)}function d(z){return e.enter("tableHead"),e.enter("tableRow"),m(z)}function m(z){return z===124||(c=!0,o+=1),y(z)}function y(z){return z===null?r(z):Ie(z)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(z),e.exit("lineEnding"),v):r(z):at(z)?pt(e,y,"whitespace")(z):(o+=1,c&&(c=!1,l+=1),z===124?(e.enter("tableCellDivider"),e.consume(z),e.exit("tableCellDivider"),c=!0,y):(e.enter("data"),g(z)))}function g(z){return z===null||z===124||Rt(z)?(e.exit("data"),y(z)):(e.consume(z),z===92?x:g)}function x(z){return z===92||z===124?(e.consume(z),g):g(z)}function v(z){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(z):(e.enter("tableDelimiterRow"),c=!1,at(z)?pt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(z):S(z))}function S(z){return z===45||z===58?D(z):z===124?(c=!0,e.enter("tableCellDivider"),e.consume(z),e.exit("tableCellDivider"),j):H(z)}function j(z){return at(z)?pt(e,D,"whitespace")(z):D(z)}function D(z){return z===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(z),e.exit("tableDelimiterMarker"),R):z===45?(o+=1,R(z)):z===null||Ie(z)?ue(z):H(z)}function R(z){return z===45?(e.enter("tableDelimiterFiller"),O(z)):H(z)}function O(z){return z===45?(e.consume(z),O):z===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(z),e.exit("tableDelimiterMarker"),F):(e.exit("tableDelimiterFiller"),F(z))}function F(z){return at(z)?pt(e,ue,"whitespace")(z):ue(z)}function ue(z){return z===124?S(z):z===null||Ie(z)?!c||l!==o?H(z):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(z)):H(z)}function H(z){return r(z)}function P(z){return e.enter("tableRow"),W(z)}function W(z){return z===124?(e.enter("tableCellDivider"),e.consume(z),e.exit("tableCellDivider"),W):z===null||Ie(z)?(e.exit("tableRow"),t(z)):at(z)?pt(e,W,"whitespace")(z):(e.enter("data"),G(z))}function G(z){return z===null||z===124||Rt(z)?(e.exit("data"),W(z)):(e.consume(z),z===92?B:G)}function B(z){return z===92||z===124?(e.consume(z),G):G(z)}}function LO(e,t){let r=-1,s=!0,l=0,o=[0,0,0,0],c=[0,0,0,0],f=!1,d=0,m,y,g;const x=new TO;for(;++r<e.length;){const v=e[r],S=v[1];v[0]==="enter"?S.type==="tableHead"?(f=!1,d!==0&&(Fb(x,t,d,m,y),y=void 0,d=0),m={type:"table",start:Object.assign({},S.start),end:Object.assign({},S.end)},x.add(r,0,[["enter",m,t]])):S.type==="tableRow"||S.type==="tableDelimiterRow"?(s=!0,g=void 0,o=[0,0,0,0],c=[0,r+1,0,0],f&&(f=!1,y={type:"tableBody",start:Object.assign({},S.start),end:Object.assign({},S.end)},x.add(r,0,[["enter",y,t]])),l=S.type==="tableDelimiterRow"?2:y?3:1):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")?(s=!1,c[2]===0&&(o[1]!==0&&(c[0]=c[1],g=xu(x,t,o,l,void 0,g),o=[0,0,0,0]),c[2]=r)):S.type==="tableCellDivider"&&(s?s=!1:(o[1]!==0&&(c[0]=c[1],g=xu(x,t,o,l,void 0,g)),o=c,c=[o[1],r,0,0])):S.type==="tableHead"?(f=!0,d=r):S.type==="tableRow"||S.type==="tableDelimiterRow"?(d=r,o[1]!==0?(c[0]=c[1],g=xu(x,t,o,l,r,g)):c[1]!==0&&(g=xu(x,t,c,l,r,g)),l=0):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")&&(c[3]=r)}for(d!==0&&Fb(x,t,d,m,y),x.consume(t.events),r=-1;++r<t.events.length;){const v=t.events[r];v[0]==="enter"&&v[1].type==="table"&&(v[1]._align=RO(t.events,r))}return e}function xu(e,t,r,s,l,o){const c=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";r[0]!==0&&(o.end=Object.assign({},ca(t.events,r[0])),e.add(r[0],0,[["exit",o,t]]));const d=ca(t.events,r[1]);if(o={type:c,start:Object.assign({},d),end:Object.assign({},d)},e.add(r[1],0,[["enter",o,t]]),r[2]!==0){const m=ca(t.events,r[2]),y=ca(t.events,r[3]),g={type:f,start:Object.assign({},m),end:Object.assign({},y)};if(e.add(r[2],0,[["enter",g,t]]),s!==2){const x=t.events[r[2]],v=t.events[r[3]];if(x[1].end=Object.assign({},v[1].end),x[1].type="chunkText",x[1].contentType="text",r[3]>r[2]+1){const S=r[2]+1,j=r[3]-r[2]-1;e.add(S,j,[])}}e.add(r[3]+1,0,[["exit",g,t]])}return l!==void 0&&(o.end=Object.assign({},ca(t.events,l)),e.add(l,0,[["exit",o,t]]),o=void 0),o}function Fb(e,t,r,s,l){const o=[],c=ca(t.events,r);l&&(l.end=Object.assign({},c),o.push(["exit",l,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(r+1,0,o)}function ca(e,t){const r=e[t],s=r[0]==="enter"?"start":"end";return r[1][s]}const zO={name:"tasklistCheck",tokenize:PO};function UO(){return{text:{91:zO}}}function PO(e,t,r){const s=this;return l;function l(d){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),o)}function o(d){return Rt(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),c):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),c):r(d)}function c(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),f):r(d)}function f(d){return Ie(d)?t(d):at(d)?e.check({tokenize:BO},t,r)(d):r(d)}}function BO(e,t,r){return pt(e,s,"whitespace");function s(l){return l===null?r(l):t(l)}}function HO(e){return s1([fO(),wO(),NO(e),MO(),UO()])}const qO={};function IO(e){const t=this,r=e||qO,s=t.data(),l=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);l.push(HO(r)),o.push(lO()),c.push(oO(r))}function FO(e){j1(e,[/\r?\n|\r/g,$O])}function $O(){return{type:"break"}}function VO(){return function(e){FO(e)}}const hm=E.createContext(null);function Z1(e,t){const r=A1(t);return e&&r!==null?jT(r,e.baseFile):null}function YO({node:e,href:t,...r}){const s=E.useContext(hm),l=Z1(s,t);return!s||l===null?b.jsx("a",{...r,href:t,target:"_blank",rel:"noopener noreferrer"}):b.jsx("a",{...r,href:t,className:"md-file-link",onClick:o=>{o.preventDefault(),s.openFile(l)}})}function GO({node:e,src:t,alt:r,...s}){const l=E.useContext(hm),o=Z1(l,typeof t=="string"?t:void 0),[c,f]=E.useState(),[d,m]=E.useState(!1),y=l==null?void 0:l.loadFile;return E.useEffect(()=>{if(o===null||!y)return;let g=!1,x;return m(!1),y(o).then(v=>{g||(x=URL.createObjectURL(v),f(x))}).catch(()=>{g||m(!0)}),()=>{g=!0,x&&URL.revokeObjectURL(x)}},[o,y]),!l||o===null?b.jsx("img",{...s,src:t,alt:r}):d?b.jsx("span",{className:"md-image-missing",children:r||o}):c?b.jsx("img",{...s,src:c,alt:r,className:"md-file-image",onClick:()=>l.openFile(o)}):b.jsx("span",{className:"md-image-loading skeleton-line"})}const JO={a:YO,img:GO};function W1({content:e,files:t,baseFile:r}){const s=E.useMemo(()=>({openFile:t.openFile,loadFile:t.loadFile,baseFile:r}),[t.openFile,t.loadFile,r]);return b.jsx(hm.Provider,{value:s,children:b.jsx(wT,{remarkPlugins:[IO,VO],urlTransform:CT,components:JO,children:e})})}function XO({filePath:e,files:t,onClose:r}){const[s,l]=E.useState(null),[o,c]=E.useState(null),{loadFile:f}=t;E.useEffect(()=>{let y=!1,g;return l(null),c(null),(async()=>{try{const x=await f(e),v=MT(x.type),S={kind:v,size:x.size};if(v==="markdown"||v==="text"||v==="html"?S.text=await x.text():(g=URL.createObjectURL(x),S.objectUrl=g),y){g&&URL.revokeObjectURL(g);return}l(S)}catch(x){y||c(x instanceof Error?x.message:"Failed to load file.")}})(),()=>{y=!0,g&&URL.revokeObjectURL(g)}},[e,f]);const d=NT(e);function m(){if(o)return b.jsx("p",{className:"file-viewer-message",children:o});if(!s)return b.jsxs("div",{className:"file-viewer-loading",children:[b.jsx("div",{className:"skeleton-line",style:{width:"40%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"100%",height:"8rem"}})]});switch(s.kind){case"markdown":return b.jsx(W1,{content:s.text??"",files:t,baseFile:e});case"text":return b.jsx("pre",{className:"file-viewer-text",children:s.text});case"html":return b.jsx("iframe",{className:"file-viewer-frame",sandbox:"",srcDoc:s.text,title:d});case"image":return b.jsx("img",{src:s.objectUrl,alt:d,style:{maxWidth:"100%",height:"auto"}});case"binary":return In.isNativePlatform()?b.jsx("p",{className:"file-viewer-message",children:"Downloading this file type isn't supported in the app yet."}):b.jsxs("div",{className:"file-viewer-download",children:[b.jsxs("p",{className:"file-viewer-message",children:["This file can't be previewed (",DT(s.size),")."]}),b.jsx("a",{className:"btn btn-primary",href:s.objectUrl,download:d,children:"Download"})]})}}return b.jsx("div",{className:"report-dialog-overlay",onClick:r,children:b.jsxs("div",{className:"report-dialog",onClick:y=>y.stopPropagation(),children:[b.jsxs("div",{className:"report-dialog-header",children:[b.jsx("span",{className:"report-dialog-title",children:d}),b.jsx("button",{className:"report-dialog-close",onClick:r,"aria-label":"Close",children:b.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),b.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),b.jsx("div",{className:`report-dialog-body${(s==null?void 0:s.kind)==="html"?" report-dialog-body--frame":""}`,children:m()})]})})}function KO({connected:e,hostId:t,request:r,subscribeEvents:s,taskId:l,runId:o}){const c=Fr(),f=Yd(),[d,m]=E.useState(!0),[y,g]=E.useState([]),[x,v]=E.useState(),[S,j]=E.useState(),[D,R]=E.useState(),[O,F]=E.useState(!1),ue=x==="started",H=x==="followup",P=x==="started"||x==="followup",W=x==="needs_input",[G,B]=E.useState(null);Px(G!==null,()=>B(null));const[z,K]=E.useState(!1),[I,oe]=E.useState(""),[ee,te]=E.useState(!1),V=E.useRef(null),X=E.useRef(null),ge=E.useRef(null),[we,C]=E.useState(o==="latest"?void 0:o),L=o==="latest"&&we===null;E.useEffect(()=>{if(o!=="latest"){C(o);return}e&&(C(void 0),r("taskrun.list",{task_id:l,limit:1}).then(ae=>{var De,rt;return C(((rt=(De=ae.entries)==null?void 0:De[0])==null?void 0:rt.run_id)??null)}).catch(()=>C(null)))},[o,l,e,r]);async function J(){if(we)try{const ae=await r("task.result",{id:l,run_id:we});if(ae.error){console.error("No result:",ae.error),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0});return}g(ae.messages??[]),v(ae.running_state),j(ae.agent),R(ae.agent_version),F(!!ae.starred)}catch(ae){console.error("Failed to load result:",ae),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0})}finally{m(!1)}}async function N(){if(!we)return;const ae=!O;F(ae);try{const De=await r("taskrun.star",{task_id:l,run_id:we,starred:ae});if(De.error)throw new Error(De.error)}catch(De){console.error("Failed to update star:",De),F(!ae)}}const ve=E.useCallback(ae=>we?OT(r,l,we,ae):Promise.reject(new Error("Run not loaded.")),[r,l,we]),Ce=E.useMemo(()=>({openFile:B,loadFile:ve}),[ve]);E.useEffect(()=>{!e||!we||(m(!0),J())},[e,l,we]),E.useEffect(()=>!e||!t||!we?void 0:s(t,async De=>{try{const rt=JSON.parse(new TextDecoder().decode(De.data));if(rt.event_type!=="running-state"&&rt.event_type!=="result-updated"||De.subject.split(".").pop()!==l||rt.event_type==="result-updated"&&rt.run_id&&rt.run_id!==we)return;J()}catch{}}),[e,t,l,we,s,r]),E.useEffect(()=>{V.current&&(V.current.scrollTop=V.current.scrollHeight)},[y]),E.useEffect(()=>{d||L||!we||ge.current!==we&&(ge.current=we,requestAnimationFrame(()=>{V.current&&(V.current.scrollTop=V.current.scrollHeight),window.scrollTo({top:document.documentElement.scrollHeight,behavior:"auto"})}))},[d,L,we]);function ke(ae){if(ae==="input")return"User Input";if(ae==="confirmation")return"Confirmation"}function je(ae){return ae==="started"?"Task started":ae==="finished"?"Task finished":ae==="failed"?"Task failed":ae==="error"?"Command failed":ae==="aborted"?"Task aborted":ae==="confirmation"?"Task confirmed":ae==="stopped"?"Follow-up stopped":ae==="needs_input"?"Waiting for your reply":ae??""}const Ve=b.jsx("button",{type:"button",className:"btn btn-secondary chat-stop-btn",disabled:z,"aria-label":"Abort task",onClick:async()=>{if(confirm("Abort this task?")){K(!0);try{await r("task.abort",{id:l})}catch(ae){console.error("Abort failed:",ae)}finally{K(!1)}}},children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:b.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})});return b.jsxs("div",{className:"run-detail",children:[b.jsxs("div",{className:"run-detail-header",children:[b.jsxs("button",{className:"run-detail-back",onClick:()=>c(-1),children:[b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M15 18l-6-6 6-6"})}),"Back"]}),!d&&!L&&b.jsx($x,{starred:O,onToggle:N})]}),L?b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No runs yet"}),b.jsx("p",{className:"empty-state-hint",children:"This task hasn't been executed yet. Run it from the task menu or wait for its next trigger."})]}):d?b.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)",padding:"var(--space-sm) 0"},children:[b.jsx("div",{className:"skeleton-line",style:{width:"40%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"55%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"100%",height:"8rem",marginTop:"var(--space-sm)"}})]}):b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"chat-thread",ref:V,children:[y.map((ae,De)=>{const rt=P&&ae.role==="assistant"&&!y.slice(De+1).some(ct=>ct.role==="assistant"||ct.role==="user");return ae.role==="status"?b.jsxs("div",{className:`chat-status${ae.type==="error"?" chat-status--error":""}`,children:[b.jsxs("div",{children:[je(ae.type),ae.time>0&&b.jsx("span",{className:"chat-status-time",children:f(ae.time)})]}),ae.content&&b.jsx("pre",{className:"chat-status-detail",children:ae.content})]},De):b.jsxs("div",{className:`chat-message chat-message--${ae.role}${ae.role==="assistant"&&ae.stream==="stderr"?" chat-message--stderr":""}`,children:[ae.role==="assistant"&&S&&b.jsxs("div",{className:"chat-message-agent",children:[yd(S),D&&b.jsxs("span",{className:"chat-message-agent-version",children:[" v",D]})]}),b.jsxs("div",{className:"chat-message-content",children:[b.jsx(W1,{content:ae.content,files:Ce}),rt&&b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),ae.attachments&&ae.attachments.length>0&&b.jsx("div",{className:"chat-message-attachments",children:ae.attachments.map(ct=>b.jsx("button",{className:"chat-attachment-chip",onClick:()=>B(ct),children:ct},ct))}),b.jsxs("div",{className:"chat-message-meta",children:[ke(ae.type)&&b.jsx("span",{className:"chat-message-type",children:ke(ae.type)}),ae.model&&b.jsxs("span",{children:[ae.model," ·"]}),ae.time>0&&b.jsx("span",{children:f(ae.time)})]})]},De)}),P&&(()=>{const ae=y.filter(De=>De.role!=="status");return ae.length===0||ae[ae.length-1].role!=="assistant"})()&&b.jsxs("div",{className:"chat-message chat-message--assistant",children:[S&&b.jsxs("div",{className:"chat-message-agent",children:[yd(S),D&&b.jsxs("span",{className:"chat-message-agent-version",children:[" v",D]})]}),b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]})]}),ue||H?b.jsx("div",{className:"chat-input-bar",children:Ve}):b.jsxs("form",{className:"chat-input-bar",onSubmit:async ae=>{ae.preventDefault();const De=I.trim();if(!(!De||ee)){te(!0);try{await r("task.followup",{id:l,run_id:we,message:De}),oe("")}catch(rt){console.error("Follow-up failed:",rt)}finally{te(!1)}}},children:[W&&Ve,b.jsx("input",{ref:X,className:"chat-input",type:"text",placeholder:W?"Reply to the agent":"Follow-up message",value:I,onChange:ae=>oe(ae.target.value),disabled:ee}),b.jsx("button",{className:"btn btn-primary chat-send-btn",type:"submit",disabled:!I.trim()||ee,children:b.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),b.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),b.jsxs("button",{className:"run-detail-back run-detail-back--footer",onClick:()=>c(-1),children:[b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M15 18l-6-6 6-6"})}),"Back"]})]}),G&&b.jsx(XO,{filePath:G,files:Ce,onClose:()=>B(null)})]})}function Zh({title:e,message:t,onUpdate:r,onDismiss:s}){return b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:e}),b.jsx("p",{className:"confirm-modal-message",children:t}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:r,children:"Update Now"}),s&&b.jsx("button",{className:"btn btn-secondary",onClick:s,children:"Dismiss"})]})]})})}function QO(){const{activeHost:e}=bi(),t=E.useRef(null);E.useEffect(()=>{if(In.isNativePlatform()||e.directUrl||t.current===e.hostId)return;async function r(){var s;try{if(!("serviceWorker"in navigator)||!("PushManager"in window)){console.warn("[Push] Push notifications not supported");return}const l=await navigator.serviceWorker.ready;(s=l.active)==null||s.postMessage({type:"set-host-id",hostId:e.hostId});let o=await l.pushManager.getSubscription();if(!o){const{publicKey:f}=await SE("/api/push/vapid-key");if(!f){console.warn("[Push] No VAPID public key configured on server");return}if(await Notification.requestPermission()!=="granted"){console.log("[Push] Permission denied");return}o=await l.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:f})}const c=o.toJSON();await wE("/api/push/subscribe",{hostId:e.hostId,endpoint:c.endpoint,keys:{p256dh:c.keys.p256dh,auth:c.keys.auth}}),t.current=e.hostId}catch(l){console.error("[Push] Subscription failed:",l)}}r()},[e])}const ZO="1.1.23",Wh=13e4;function vu(e,t){if(e.includes("-"))return!1;const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let l=0;l<3;l++){if((r[l]??0)<(s[l]??0))return!0;if((r[l]??0)>(s[l]??0))return!1}return!1}function wu(){const{removePairedHost:e,setHostLanUrl:t,setHostTimezone:r}=Wi(),{connected:s,request:l,subscribeEvents:o,unauthorized:c,activeHost:f}=bi(),d=f.hostId,m=f.clientToken||null,y=Fr(),g=vr(),x=Yu(),v=Ix("(min-width: 768px)"),S=g.pathname.endsWith("/tasks"),j=x.runId?void 0:x.taskId,D=!!(x.taskId&&x.runId),[R,O]=E.useState(!1),[F,ue]=E.useState(!1),[H,P]=E.useState(null),[W,G]=E.useState(null),[B,z]=E.useState(null),[K,I]=E.useState(null),[oe,ee]=E.useState({}),[te,V]=E.useState({}),[X,ge]=E.useState(null),[we,C]=E.useState(null),[L,J]=E.useState(null),[N,ve]=E.useState(null),[Ce,ke]=E.useState(new Set),[je,Ve]=E.useState([]),[ae,De]=E.useState(),[rt,ct]=E.useState("loading"),[Kt,Dt]=E.useState(0),tn=E.useRef(0),$t=E.useCallback(()=>{tn.current=0,ct("loading"),Dt(ye=>ye+1)},[]),nn=!!m&&N===m,[Ye,ft]=E.useState(new Map),[ht,xt]=E.useState(new Map),[Yt,An]=E.useState(new Map),[lt,$n]=E.useState(new Map),[ce,_e]=E.useState(new Map),[Me,Xe]=E.useState(new Map),[We,xe]=E.useState(new Map);QO(),E.useEffect(()=>{window.scrollTo(0,0)},[d]),E.useEffect(()=>{let ye=!1;return eC().then(Oe=>{ye||ke(Oe)}),()=>{ye=!0}},[]),E.useEffect(()=>{if(!s){tn.current=0,ct("loading");return}ct(Re=>Re==="error"?Re:"loading");let ye=!1,Oe;return l("host.info",void 0,{timeout:15e3}).then(Re=>{var cn,rn,Vt,yt,zt,wn,Dr,Si;if(ye)return;Ve(Re.agents??[]),ge(Re.playwright_cli??null),De(Re.host_platform),ve(Re.linked_client_token??null),zE(Re.agents??[]);const Je=Re.version??null;G(Je),O(!!Je&&vu(Je,ZO)),t(d,Re.lan_url??void 0),r(d,Re.host_timezone);const Pe=new Map,He=new Map,Ke=new Map,Lt=new Map;for(const Gt of Re.pending_prompts??[])if(Gt.type==="confirmation")Pe.set(Gt.key,{description:((cn=Gt.meta)==null?void 0:cn.description)??"",sessionName:(rn=Gt.meta)==null?void 0:rn.session_name});else if(Gt.type==="choice")He.set(Gt.key,{question:((Vt=Gt.meta)==null?void 0:Vt.description)??"",options:Gt.params??[],sessionName:(yt=Gt.meta)==null?void 0:yt.session_name});else if(Gt.type==="input"){const ns=Gt.params??((zt=Gt.meta)==null?void 0:zt.input_questions)??[];Ke.set(Gt.key,{questions:ns,description:(wn=Gt.meta)==null?void 0:wn.description,sessionName:(Dr=Gt.meta)==null?void 0:Dr.session_name,secret:(Si=Gt.meta)==null?void 0:Si.secret}),Lt.set(Gt.key,new Array(ns.length).fill(""))}ft(Pe),xt(He),An(Ke),$n(Lt),tn.current=0,ct("ready")}).catch(()=>{if(ye)return;ct("error");const Re=Math.min(2e3*2**tn.current,3e4);tn.current++,Oe=window.setTimeout(()=>Dt(Je=>Je+1),Re)}),()=>{ye=!0,clearTimeout(Oe)}},[s,d,l,t,r,Kt]),E.useEffect(()=>{if(rt!=="error")return;function ye(){document.visibilityState==="visible"&&$t()}return document.addEventListener("visibilitychange",ye),()=>document.removeEventListener("visibilitychange",ye)},[rt,$t]),E.useEffect(()=>s?o(d,Oe=>{let Re={};try{Re=JSON.parse(new TextDecoder().decode(Oe.data))}catch{return}const Je=Re.event_type,Pe=Re.session_id;if(Je==="input-request"&&Pe){const He=Re.input_questions,Ke=Re.session_name,Lt=Re.description,cn=Re.secret;He!=null&&He.length&&(An(rn=>{if(rn.has(Pe))return rn;const Vt=new Map(rn);return Vt.set(Pe,{questions:He,description:Lt,sessionName:Ke,secret:cn}),Vt}),$n(rn=>{if(rn.has(Pe))return rn;const Vt=new Map(rn);return Vt.set(Pe,new Array(He.length).fill("")),Vt}));return}if(Je==="input-resolved"&&Pe){An(He=>{if(!He.has(Pe))return He;const Ke=new Map(He);return Ke.delete(Pe),Ke}),$n(He=>{const Ke=new Map(He);return Ke.delete(Pe),Ke}),_e(He=>{if(!He.has(Pe))return He;const Ke=new Map(He);return Ke.delete(Pe),Ke});return}if(Je==="confirm-request"&&Pe){const He=Re.description,Ke=Re.session_name;He&&ft(Lt=>{if(Lt.has(Pe))return Lt;const cn=new Map(Lt);return cn.set(Pe,{description:He,sessionName:Ke}),cn});return}if(Je==="confirm-resolved"&&Pe){ft(He=>{if(!He.has(Pe))return He;const Ke=new Map(He);return Ke.delete(Pe),Ke});return}if(Je==="choice-request"&&Pe){const He=Re.description,Ke=Re.options,Lt=Re.session_name;He&&(Ke!=null&&Ke.length)&&xt(cn=>{if(cn.has(Pe))return cn;const rn=new Map(cn);return rn.set(Pe,{question:He,options:Ke,sessionName:Lt}),rn});return}if(Je==="choice-resolved"&&Pe){xt(He=>{if(!He.has(Pe))return He;const Ke=new Map(He);return Ke.delete(Pe),Ke});return}}):void 0,[s,d,o]);async function Fe(ye,Oe,Re,Je){if(!Me.has(ye)){Xe(Pe=>new Map(Pe).set(ye,Oe)),xe(Pe=>{const He=new Map(Pe);return He.delete(ye),He});try{await l("task.user_input",{id:ye,value:Re},{timeout:3e4}),Je()}catch(Pe){console.error("[Dashboard] Failed to send user input:",Pe),xe(He=>new Map(He).set(ye,"Couldn't reach the host. Try again."))}finally{Xe(Pe=>{const He=new Map(Pe);return He.delete(ye),He})}}}function Ae(ye,Oe){Fe(ye,Oe,[Oe],()=>{ft(Re=>{const Je=new Map(Re);return Je.delete(ye),Je})})}function Ge(ye,Oe){Fe(ye,Oe,[Oe],()=>{xt(Re=>{const Je=new Map(Re);return Je.delete(ye),Je})})}function gt(ye,Oe,Re){Fe(ye,Oe,Re,()=>{An(Je=>{const Pe=new Map(Je);return Pe.delete(ye),Pe}),$n(Je=>{const Pe=new Map(Je);return Pe.delete(ye),Pe}),_e(Je=>{const Pe=new Map(Je);return Pe.delete(ye),Pe})})}function dt(ye,Oe){if(!Ss())return;const Re=`/hosts/${encodeURIComponent(d)}/runs/${encodeURIComponent(ye)}`;y(Oe?`${Re}/${encodeURIComponent(Oe)}`:Re)}E.useEffect(()=>{if(!W)return;let ye=!1;return fetch("https://registry.npmjs.org/palmier/latest").then(Oe=>Oe.ok?Oe.json():null).then(Oe=>{!ye&&(Oe!=null&&Oe.version)&&z(Oe.version)}).catch(()=>{}),()=>{ye=!0}},[W]),E.useEffect(()=>{let ye=!1;for(const Oe of je)!Oe.version||!Oe.npmPackage||fetch(`https://registry.npmjs.org/${Oe.npmPackage}/latest`).then(Re=>Re.ok?Re.json():null).then(Re=>{ye||!(Re!=null&&Re.version)||ee(Je=>Je[Oe.key]===Re.version?Je:{...Je,[Oe.key]:Re.version})}).catch(()=>{});return()=>{ye=!0}},[je]);const Qt=je.find(ye=>{if(!ye.version)return!1;const Oe=oe[ye.key];return!Oe||!vu(ye.version,Oe)?!1:te[ye.key]!==Oe});function gn(ye,Oe){V(Re=>({...Re,[ye]:Oe}))}async function vi(ye){ue("agent"),P(null);try{const Oe=await l("host.updateAgent",{key:ye},{timeout:Wh});if(Oe.error){P(Oe.error),ue(!1);return}const Re=await l("host.info");Re.agents&&Ve(Re.agents)}catch(Oe){P(Oe instanceof Error?Oe.message:String(Oe))}finally{ue(!1)}}E.useEffect(()=>{if(!(X!=null&&X.npmPackage))return;let ye=!1;return fetch(`https://registry.npmjs.org/${X.npmPackage}/latest`).then(Oe=>Oe.ok?Oe.json():null).then(Oe=>{!ye&&(Oe!=null&&Oe.version)&&C(Oe.version)}).catch(()=>{}),()=>{ye=!0}},[X==null?void 0:X.npmPackage,X==null?void 0:X.version]);const ar=X&&we&&vu(X.version,we)&&L!==we?X:null;function wr(ye){J(ye)}async function Mr(){ue("playwright"),P(null);try{const ye=await l("host.updatePlaywrightCli",void 0,{timeout:Wh});if(ye.error){P(ye.error),ue(!1);return}const Oe=await l("host.info");ge(Oe.playwright_cli??null)}catch(ye){P(ye instanceof Error?ye.message:String(ye))}finally{ue(!1)}}const jn=!R&&!!W&&!!B&&vu(W,B)&&K!==B;function Vr(){B&&I(B)}async function Yr(){ue("daemon"),P(null);try{const ye=await l("host.update",void 0,{timeout:Wh});if(ye.error){P(ye.error),ue(!1);return}}catch{}setTimeout(()=>window.location.reload(),3e4)}const Gr=Ye.size>0||ht.size>0||Yt.size>0,wi=s&&!c;return b.jsxs("div",{className:"dashboard",children:[v&&b.jsx(Q0,{daemonVersion:W,agents:je,playwrightCli:X,linkedClientToken:N,request:l,onEnabledCapabilitiesChange:ke,onLinkedClientTokenChange:ve}),b.jsxs("div",{className:"dashboard-content",children:[b.jsxs("header",{className:"app-header",children:[b.jsxs("div",{className:"app-title-bar",children:[!v&&b.jsx(Q0,{daemonVersion:W,agents:je,playwrightCli:X,linkedClientToken:N,request:l,onEnabledCapabilitiesChange:ke,onLinkedClientTokenChange:ve}),b.jsx("h1",{className:"app-title",children:"Palmier"}),b.jsx(aC,{})]}),b.jsx("div",{className:"tab-bar",children:b.jsx(QE,{})})]}),b.jsx("main",{className:"dashboard-main",children:c?b.jsxs("div",{className:"revoked-state",children:[b.jsx("div",{className:"revoked-icon",children:b.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),b.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}),b.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"18"})]})}),b.jsx("h2",{className:"revoked-title",children:"Client Revoked"}),b.jsx("p",{className:"revoked-description",children:"This client was revoked by the host. To reconnect, generate a new pairing code on the host machine."}),b.jsx("div",{className:"revoked-command",children:b.jsx("code",{children:"palmier pair"})}),b.jsxs("div",{className:"revoked-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>{Ss()&&y("/pair")},children:"Re-pair Device"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{e(d),y("/",{replace:!0})},children:"Remove Host"})]})]}):wi?b.jsxs(b.Fragment,{children:[S&&!D&&b.jsx(KE,{connected:s,hostId:d,request:l,subscribeEvents:o,agents:je,hostPlatform:ae,isNotificationListener:nn&&Ce.has("notifications"),onViewRun:dt,hostInfoStatus:rt,onRetryHostInfo:$t}),D?b.jsx(KO,{connected:s,hostId:d,request:l,subscribeEvents:o,taskId:x.taskId,runId:decodeURIComponent(x.runId)}):S?null:b.jsx(cC,{connected:s,hostId:d,request:l,subscribeEvents:o,agents:je,hostPlatform:ae,filterTaskId:j,onClearFilter:()=>{Ss()&&y(`/hosts/${encodeURIComponent(d)}`)},hostInfoStatus:rt,onRetryHostInfo:$t})]}):b.jsx("div",{className:"empty-state",children:b.jsx("p",{className:"empty-state-text",children:"Connecting to host…"})})}),(R||jn)&&!F&&!H&&!Gr&&b.jsx(Zh,{title:R?"Update Required":"Update Available",message:R?`Your Palmier host${W?` (v${W})`:""} is too old for this version of the app. Please update to continue.`:`A new version of Palmier (v${B}) is available. You're running v${W}.`,onUpdate:Yr,onDismiss:R?void 0:Vr}),!R&&!jn&&Qt&&!F&&!H&&!Gr&&b.jsx(Zh,{title:"Agent Update Available",message:`A new version of ${Qt.label} (v${oe[Qt.key]}) is available. You're running v${Qt.version}.`,onUpdate:()=>vi(Qt.key),onDismiss:()=>gn(Qt.key,oe[Qt.key])}),!R&&!jn&&!Qt&&ar&&we&&!F&&!H&&!Gr&&b.jsx(Zh,{title:"Browser Automation Update Available",message:`A new version of ${ar.label} (v${we}) is available. You're running v${ar.version}.`,onUpdate:Mr,onDismiss:()=>wr(we)}),F&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Updating..."}),b.jsx("p",{className:"confirm-modal-message",children:F==="daemon"?"Installing update and restarting daemon. Please wait...":"Installing update. Please wait..."})]})}),H&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Update Failed"}),b.jsx("p",{className:"confirm-modal-message",style:{whiteSpace:"pre-line"},children:H}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>{P(null)},children:"Retry"})})]})})]}),mi.createPortal(b.jsxs(b.Fragment,{children:[[...Ye.entries()].map(([ye,{description:Oe,sessionName:Re}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Confirmation Required"}),Re&&b.jsx("p",{className:"confirm-modal-subtitle",children:Re}),b.jsx("p",{className:"confirm-modal-message",children:Oe}),We.has(ye)&&b.jsx("p",{className:"form-error",children:We.get(ye)}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsxs("button",{className:"btn btn-primary",disabled:Me.has(ye),onClick:()=>Ae(ye,"confirmed"),children:[Me.get(ye)==="confirmed"&&b.jsx("span",{className:"btn-spinner"}),"Confirm"]}),b.jsxs("button",{className:"btn btn-secondary",disabled:Me.has(ye),onClick:()=>Ae(ye,"aborted"),children:[Me.get(ye)==="aborted"&&b.jsx("span",{className:"btn-spinner btn-spinner-current"}),"Abort"]})]})]})},ye)),[...ht.entries()].map(([ye,{question:Oe,options:Re,sessionName:Je}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Question"}),Je&&b.jsx("p",{className:"confirm-modal-subtitle",children:Je}),b.jsx("p",{className:"confirm-modal-message",children:Oe}),We.has(ye)&&b.jsx("p",{className:"form-error",children:We.get(ye)}),b.jsx("div",{className:`confirm-modal-actions${Re.length===2&&Re.every(Pe=>Pe.length<=16)?"":" choice-options-stacked"}`,children:Re.map((Pe,He)=>b.jsxs("button",{className:"btn btn-secondary",disabled:Me.has(ye),onClick:()=>Ge(ye,String(He)),children:[Me.get(ye)===String(He)&&b.jsx("span",{className:"btn-spinner btn-spinner-current"}),Pe]},He))}),b.jsxs("button",{className:"prompt-abort-link",disabled:Me.has(ye),onClick:()=>Ge(ye,"aborted"),children:[Me.get(ye)==="aborted"&&b.jsx("span",{className:"btn-spinner btn-spinner-current"}),"Abort Task"]})]})},ye)),[...Yt.entries()].map(([ye,{questions:Oe,description:Re,sessionName:Je,secret:Pe}])=>{const He=lt.get(ye)??new Array(Oe.length).fill("");return b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal input-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:Pe?"Password Required":"Input Required"}),Je&&b.jsx("p",{className:"confirm-modal-subtitle",children:Je}),Re&&b.jsx("p",{className:"confirm-modal-message",children:Re}),b.jsx("div",{className:"input-list",children:Oe.map((Ke,Lt)=>b.jsxs("div",{className:"input-item",children:[b.jsx("label",{className:"input-label",children:Ke}),b.jsx("input",{type:Pe?"password":"text",autoComplete:Pe?"off":void 0,className:"input-field",value:He[Lt]??"",onChange:cn=>{$n(rn=>{const Vt=new Map(rn),yt=[...Vt.get(ye)??[]];return yt[Lt]=cn.target.value,Vt.set(ye,yt),Vt})},disabled:Me.has(ye),autoFocus:Lt===0})]},Lt))}),Pe&&b.jsxs("label",{className:"toggle-label input-save-toggle",children:[b.jsx("input",{type:"checkbox",checked:ce.get(ye)??!0,disabled:Me.has(ye),onChange:Ke=>_e(Lt=>new Map(Lt).set(ye,Ke.target.checked))}),"Save this password"]}),We.has(ye)&&b.jsx("p",{className:"form-error",children:We.get(ye)}),b.jsx("div",{className:"input-actions",children:b.jsxs("button",{className:"btn btn-primary",disabled:Me.has(ye)||He.some(Ke=>!Ke.trim()),onClick:()=>{const Ke=Pe?[...He,ce.get(ye)??!0?"save":"nosave"]:He;gt(ye,"submit",Ke)},children:[Me.get(ye)==="submit"&&b.jsx("span",{className:"btn-spinner"}),"Submit"]})}),b.jsxs("button",{className:"prompt-abort-link",disabled:Me.has(ye),onClick:()=>gt(ye,"aborted",["aborted"]),children:[Me.get(ye)==="aborted"&&b.jsx("span",{className:"btn-spinner btn-spinner-current"}),"Abort"]})]})},ye)})]}),document.body)]})}const WO=ks("Preferences",{web:()=>Vd(()=>import("./web-YFetWCPM.js"),[]).then(e=>new e.PreferencesWeb)}),Al=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),$b=In.isNativePlatform();function e4(){const[e,t]=E.useState(""),[r,s]=E.useState(!0),[l,o]=E.useState(!1),[c,f]=E.useState(null),{addPairedHost:d,pairedHosts:m}=Wi(),y=Fr();async function g(){const x=e.trim().toUpperCase();if(!x){f("Enter a pairing code.");return}o(!0),f(null);try{let v;if(Al){const D=await fetch("/pair",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:x,label:navigator.userAgent})});if(!D.ok){const R=await D.json().catch(()=>({error:"Connection failed"}));throw new Error(R.error||`HTTP ${D.status}`)}v=await D.json()}else{const D=await fetch(`${Bu}/api/config`);if(!D.ok)throw new Error("Failed to fetch server config");const R=await D.json();if(!R.natsWsUrl)throw new Error("Server has no NATS WebSocket URL configured");const O=await Dx({servers:R.natsWsUrl,authenticator:Ex(R.natsJwt,new TextEncoder().encode(R.natsNkeySeed))}),F=Ru(),ue=`pair.${x}`,H=await O.request(ue,F.encode(JSON.stringify({label:navigator.userAgent})),{timeout:1e4});v=JSON.parse(F.decode(H.data)),await O.close()}const S={hostId:v.hostId,clientToken:v.clientToken,directUrl:Al?window.location.origin:void 0,...v.hostName?{name:v.hostName}:{}};if(d(S),In.isNativePlatform()&&kn){await WO.set({key:"hostId",value:v.hostId});try{const{token:D}=await kn.getFcmToken();await fetch(`${Bu}/api/fcm/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostId:v.hostId,fcmToken:D})})}catch(D){console.warn("FCM token registration failed:",D)}}const j=`/hosts/${encodeURIComponent(v.hostId)}`;y($b&&r?`${j}/pair/setup`:j)}catch(v){const S=v instanceof Error?v.message:String(v);S.includes("timeout")||S.includes("TIMEOUT")||S.includes("503")||S.toLowerCase().includes("no responders")?f("Code not found or expired. Check the code and try again."):f(S)}finally{o(!1)}}return b.jsx("div",{className:"pair-page",children:b.jsxs("div",{className:"pair-card",children:[b.jsxs("div",{className:"pair-header",children:[b.jsx("h1",{className:"pair-title",children:Al?"Pair":"Pair with Host"}),b.jsx("p",{className:"pair-subtitle",children:Al?"Enter the pairing code shown in your terminal.":"Connect this device to a Palmier host"})]}),!Al&&b.jsxs("div",{className:"pair-instructions",children:[b.jsxs("div",{className:"pair-instruction-block",children:[b.jsx("h3",{className:"pair-instruction-heading",children:"Setting up a new host?"}),b.jsxs("ol",{className:"pair-steps",children:[b.jsxs("li",{children:["Install Palmier on your host machine.",b.jsx("span",{className:"pair-platform-label",children:"Linux / macOS:"}),b.jsx("code",{className:"pair-command",children:"curl -fsSL https://palmier.me/install.sh | bash"}),b.jsx("span",{className:"pair-platform-label",children:"Windows (PowerShell):"}),b.jsx("code",{className:"pair-command",children:"irm https://palmier.me/install.ps1 | iex"})]}),b.jsxs("li",{children:["Run the setup wizard:",b.jsx("code",{className:"pair-command",children:"palmier init"})]}),b.jsx("li",{children:"A pairing code will display automatically"})]})]}),b.jsx("div",{className:"pair-instruction-divider"}),b.jsxs("div",{className:"pair-instruction-block",children:[b.jsx("h3",{className:"pair-instruction-heading",children:"Pairing an existing host?"}),b.jsxs("ol",{className:"pair-steps",children:[b.jsxs("li",{children:["Run ",b.jsx("code",{children:"palmier pair"})," on the host machine"]}),b.jsx("li",{children:"Enter the 6-character code below"})]})]})]}),b.jsxs("div",{className:"pair-form",children:[b.jsxs("label",{className:"form-label",htmlFor:"pair-code",children:["Pairing code",b.jsx("input",{id:"pair-code",type:"text",maxLength:6,value:e,onChange:x=>t(x.target.value.toUpperCase()),placeholder:"A7K9M2",className:"form-input form-input-mono pair-code-input",autoFocus:!0,autoComplete:"off",disabled:l})]}),$b&&b.jsxs("label",{className:"pair-checkbox",children:[b.jsx("input",{type:"checkbox",checked:r,onChange:x=>s(x.target.checked),disabled:l}),b.jsxs("span",{className:"pair-checkbox-text",children:[b.jsx("span",{className:"pair-checkbox-title",children:"Link the host to this device"}),b.jsx("span",{className:"pair-checkbox-hint",children:r?"The host will use this device for SMS, contacts, calendar, location, and alarms. Only one device can be linked to the host.":"This device won't provide SMS, contacts, calendar, location, or alarms to the host. You can link it later from the menu."})]})]}),c&&b.jsx("p",{className:"pair-error",children:c}),b.jsxs("button",{className:"btn btn-primary btn-full",onClick:g,disabled:l||!e.trim(),children:[l&&b.jsx("span",{className:"btn-spinner"}),l?"Pairing...":"Pair"]}),m.length>0&&b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>y("/"),disabled:l,children:"Cancel"}),b.jsxs("p",{className:"pair-consent",children:["By pairing, you agree to our"," ",b.jsx("a",{href:"https://www.palmier.me/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," and"," ",b.jsx("a",{href:"https://www.palmier.me/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]})]})]})})}function t4(){const e=Fr(),{connected:t,request:r,activeHost:s}=bi(),{setHostLanUrl:l,pairedHosts:o}=Wi(),c=o.length<=1,[f,d]=E.useState("loading"),[m,y]=E.useState(null),[g,x]=E.useState(null);function v(){e(`/hosts/${encodeURIComponent(s.hostId)}`,{replace:!0})}E.useEffect(()=>{if(!t||f!=="loading")return;let O=!1;return r("host.info").catch(()=>({})).then(F=>{if(O)return;l(s.hostId,F.lan_url??void 0);const ue=F.linked_client_token??null;y(ue);const H=!!ue&&ue!==s.clientToken;d(H?"confirming":"linking")}),()=>{O=!0}},[t,f,s,r,l]),E.useEffect(()=>{if(f!=="linking")return;let O=!1;return(async()=>{try{if(kn){const{token:F}=await kn.getFcmToken();if(!F)throw new Error("Could not read FCM token");await r("device.link",{fcmToken:F})}if(O)return;c?d("wizard"):v()}catch(F){if(O)return;x(F instanceof Error?F.message:String(F)),d("linkError")}})(),()=>{O=!0}},[f]);function S(){d("linking")}function j(){v()}function D(){x(null),d("linking")}const R=f==="confirming"&&mi.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:j,children:b.jsxs("div",{className:"confirm-modal",onClick:O=>O.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Link the host to this device?"}),b.jsx("p",{className:"confirm-modal-message",children:"Another device is already linked to this host. Only one device can be linked to the host — switching will disable those capabilities on the currently linked device."}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:j,children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:S,children:"Link"})]})]})}),document.body);if(f==="loading"||f==="confirming"||f==="linking"||f==="linkError"){const O=c,F=f==="loading"||f==="confirming"||f==="linking";return b.jsxs("div",{className:"pair-setup",children:[b.jsxs("div",{className:"pair-setup-inner",children:[O&&b.jsx("h1",{className:"pair-setup-title",children:"Device Capabilities"}),b.jsxs("div",{className:"pair-setup-loading",children:[F&&b.jsx("span",{className:"spinner spinner-lg"}),f==="loading"&&b.jsx("span",{children:"Connecting to host…"}),f==="confirming"&&b.jsx("span",{children:"Awaiting confirmation…"}),f==="linking"&&b.jsx("span",{children:"Linking device…"}),f==="linkError"&&b.jsxs(b.Fragment,{children:[b.jsx("p",{className:"pair-error",children:g}),b.jsx("button",{className:"btn btn-primary",onClick:D,children:"Retry"}),b.jsx("button",{className:"btn btn-secondary",onClick:v,children:"Skip linking"})]})]})]}),R]})}return b.jsx("div",{className:"pair-setup",children:b.jsxs("div",{className:"pair-setup-inner",children:[b.jsx("h1",{className:"pair-setup-title",children:"Device Capabilities"}),b.jsx("p",{className:"pair-setup-description",children:"Choose what the host can use this device for. You can change these later from the menu."}),b.jsx(Fx,{}),b.jsx("div",{className:"pair-setup-actions",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:v,children:"Finish"})})]})})}function n4(){const e=Fr();return E.useEffect(()=>{if(!kn)return;const t=kn.addListener("deepLink",({path:r})=>e(r));return()=>{t.then(r=>r.remove())}},[e]),null}function r4(){const{pairedHosts:e,lastHostId:t}=Wi();if(e.length===0)return b.jsx(Bl,{to:"/pair",replace:!0});const r=e.find(s=>s.hostId===t)??e[0];return b.jsx(Bl,{to:`/hosts/${encodeURIComponent(r.hostId)}`,replace:!0})}function i4(){const{hostId:e}=Yu(),{pairedHosts:t,setLastHostId:r}=Wi(),s=t.find(l=>l.hostId===e)??null;return E.useEffect(()=>{s&&r(s.hostId)},[s==null?void 0:s.hostId,r]),s?b.jsx(CE,{activeHost:s,children:b.jsxs(ax,{children:[b.jsx(Ar,{index:!0,element:b.jsx(wu,{},e)}),b.jsx(Ar,{path:"tasks",element:b.jsx(wu,{},e)}),b.jsx(Ar,{path:"runs/:taskId",element:b.jsx(wu,{},e)}),b.jsx(Ar,{path:"runs/:taskId/:runId",element:b.jsx(wu,{},e)}),b.jsx(Ar,{path:"pair/setup",element:b.jsx(t4,{})}),b.jsx(Ar,{path:"*",element:b.jsx(Bl,{to:".",replace:!0})})]})},`${s.hostId}|${s.clientToken}`):b.jsx(Bl,{to:"/",replace:!0})}function s4(){return b.jsxs(K_,{children:[b.jsx(n4,{}),b.jsxs(ax,{children:[b.jsx(Ar,{path:"/",element:b.jsx(r4,{})}),b.jsx(Ar,{path:"/pair",element:b.jsx(e4,{})}),b.jsx(Ar,{path:"/hosts/:hostId/*",element:b.jsx(i4,{})}),b.jsx(Ar,{path:"*",element:b.jsx(Bl,{to:"/",replace:!0})})]})]})}yS.createRoot(document.getElementById("root")).render(b.jsx(E.StrictMode,{children:b.jsx(U_,{children:b.jsx(s4,{})})}));export{$d as W};
117
+ `))}function d(v,S,j,D){const R=j.enter("tableCell"),O=j.enter("phrasing"),F=j.containerPhrasing(v,{...D,before:o,after:o});return O(),R(),F}function m(v,S){return g3(v,{align:S,alignDelimiters:s,padding:r,stringLength:l})}function y(v,S,j){const D=v.children;let R=-1;const O=[],F=S.enter("table");for(;++R<D.length;)O[R]=g(D[R],S,j);return F(),O}function g(v,S,j){const D=v.children;let R=-1;const O=[],F=S.enter("tableRow");for(;++R<D.length;)O[R]=d(D[R],v,S,j);return F(),O}function x(v,S,j){let D=F1.inlineCode(v,S,j);return j.stack.includes("tableCell")&&(D=D.replace(/\|/g,"\\$&")),D}}function rO(){return{exit:{taskListCheckValueChecked:Ib,taskListCheckValueUnchecked:Ib,paragraph:sO}}}function iO(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:aO}}}function Ib(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function sO(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const l=t.children;let o=-1,c;for(;++o<l.length;){const f=l[o];if(f.type==="paragraph"){c=f;break}}c===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function aO(e,t,r,s){const l=e.children[0],o=typeof e.checked=="boolean"&&l&&l.type==="paragraph",c="["+(e.checked?"x":" ")+"] ",f=r.createTracker(s);o&&f.move(c);let d=F1.listItem(e,t,r,{...s,...f.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),d;function m(y){return y+c}}function lO(){return[BT(),a3(),c3(),K3(),rO()]}function oO(e){return{extensions:[HT(),l3(e),f3(),nO(e),iO()]}}const uO={tokenize:pO,partial:!0},$1={tokenize:gO,partial:!0},V1={tokenize:yO,partial:!0},Y1={tokenize:bO,partial:!0},cO={tokenize:xO,partial:!0},G1={name:"wwwAutolink",tokenize:dO,previous:X1},J1={name:"protocolAutolink",tokenize:mO,previous:K1},xi={name:"emailAutolink",tokenize:hO,previous:Q1},$r={};function fO(){return{text:$r}}let vs=48;for(;vs<123;)$r[vs]=xi,vs++,vs===58?vs=65:vs===91&&(vs=97);$r[43]=xi;$r[45]=xi;$r[46]=xi;$r[95]=xi;$r[72]=[xi,J1];$r[104]=[xi,J1];$r[87]=[xi,G1];$r[119]=[xi,G1];function hO(e,t,r){const s=this;let l,o;return c;function c(g){return!jd(g)||!Q1.call(s,s.previous)||fm(s.events)?r(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return jd(g)?(e.consume(g),f):g===64?(e.consume(g),d):r(g)}function d(g){return g===46?e.check(cO,y,m)(g):g===45||g===95||En(g)?(o=!0,e.consume(g),d):y(g)}function m(g){return e.consume(g),l=!0,d}function y(g){return o&&l&&Mn(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):r(g)}}function dO(e,t,r){const s=this;return l;function l(c){return c!==87&&c!==119||!X1.call(s,s.previous)||fm(s.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(uO,e.attempt($1,e.attempt(V1,o),r),r)(c))}function o(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function mO(e,t,r){const s=this;let l="",o=!1;return c;function c(g){return(g===72||g===104)&&K1.call(s,s.previous)&&!fm(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),l+=String.fromCodePoint(g),e.consume(g),f):r(g)}function f(g){if(Mn(g)&&l.length<5)return l+=String.fromCodePoint(g),e.consume(g),f;if(g===58){const x=l.toLowerCase();if(x==="http"||x==="https")return e.consume(g),d}return r(g)}function d(g){return g===47?(e.consume(g),o?m:(o=!0,d)):r(g)}function m(g){return g===null||Hu(g)||Rt(g)||_s(g)||Wu(g)?r(g):e.attempt($1,e.attempt(V1,y),r)(g)}function y(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function pO(e,t,r){let s=0;return l;function l(c){return(c===87||c===119)&&s<3?(s++,e.consume(c),l):c===46&&s===3?(e.consume(c),o):r(c)}function o(c){return c===null?r(c):t(c)}}function gO(e,t,r){let s,l,o;return c;function c(m){return m===46||m===95?e.check(Y1,d,f)(m):m===null||Rt(m)||_s(m)||m!==45&&Wu(m)?d(m):(o=!0,e.consume(m),c)}function f(m){return m===95?s=!0:(l=s,s=void 0),e.consume(m),c}function d(m){return l||s||!o?r(m):t(m)}}function yO(e,t){let r=0,s=0;return l;function l(c){return c===40?(r++,e.consume(c),l):c===41&&s<r?o(c):c===33||c===34||c===38||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===60||c===63||c===93||c===95||c===126?e.check(Y1,t,o)(c):c===null||Rt(c)||_s(c)?t(c):(e.consume(c),l)}function o(c){return c===41&&s++,e.consume(c),l}}function bO(e,t,r){return s;function s(f){return f===33||f===34||f===39||f===41||f===42||f===44||f===46||f===58||f===59||f===63||f===95||f===126?(e.consume(f),s):f===38?(e.consume(f),o):f===93?(e.consume(f),l):f===60||f===null||Rt(f)||_s(f)?t(f):r(f)}function l(f){return f===null||f===40||f===91||Rt(f)||_s(f)?t(f):s(f)}function o(f){return Mn(f)?c(f):r(f)}function c(f){return f===59?(e.consume(f),s):Mn(f)?(e.consume(f),c):r(f)}}function xO(e,t,r){return s;function s(o){return e.consume(o),l}function l(o){return En(o)?r(o):t(o)}}function X1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Rt(e)}function K1(e){return!Mn(e)}function Q1(e){return!(e===47||jd(e))}function jd(e){return e===43||e===45||e===46||e===95||En(e)}function fm(e){let t=e.length,r=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const vO={tokenize:jO,partial:!0};function wO(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:EO,continuation:{tokenize:CO},exit:AO}},text:{91:{name:"gfmFootnoteCall",tokenize:kO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:SO,resolveTo:_O}}}}function SO(e,t,r){const s=this;let l=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;l--;){const d=s.events[l][1];if(d.type==="labelImage"){c=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return f;function f(d){if(!c||!c._balanced)return r(d);const m=Tr(s.sliceSerialize({start:c.end,end:s.now()}));return m.codePointAt(0)!==94||!o.includes(m.slice(1))?r(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),t(d))}}function _O(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},l={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};l.end.column++,l.end.offset++,l.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},l.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},f=[e[r+1],e[r+2],["enter",s,t],e[r+3],e[r+4],["enter",l,t],["exit",l,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(r,e.length-r+1,...f),e}function kO(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return f;function f(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),d}function d(g){return g!==94?r(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",m)}function m(g){if(o>999||g===93&&!c||g===null||g===91||Rt(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return l.includes(Tr(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(g)}return Rt(g)||(c=!0),o++,e.consume(g),g===92?y:m}function y(g){return g===91||g===92||g===93?(e.consume(g),o++,m):m(g)}}function EO(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,f;return d;function d(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),m}function m(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",y):r(S)}function y(S){if(c>999||S===93&&!f||S===null||S===91||Rt(S))return r(S);if(S===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return o=Tr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return Rt(S)||(f=!0),c++,e.consume(S),S===92?g:y}function g(S){return S===91||S===92||S===93?(e.consume(S),c++,y):y(S)}function x(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),l.includes(o)||l.push(o),pt(e,v,"gfmFootnoteDefinitionWhitespace")):r(S)}function v(S){return t(S)}}function CO(e,t,r){return e.check(Ql,t,e.attempt(vO,t,r))}function AO(e){e.exit("gfmFootnoteDefinition")}function jO(e,t,r){const s=this;return pt(e,l,"gfmFootnoteDefinitionIndent",5);function l(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):r(o)}}function NO(e){let r=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:l};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function l(c,f){let d=-1;for(;++d<c.length;)if(c[d][0]==="enter"&&c[d][1].type==="strikethroughSequenceTemporary"&&c[d][1]._close){let m=d;for(;m--;)if(c[m][0]==="exit"&&c[m][1].type==="strikethroughSequenceTemporary"&&c[m][1]._open&&c[d][1].end.offset-c[d][1].start.offset===c[m][1].end.offset-c[m][1].start.offset){c[d][1].type="strikethroughSequence",c[m][1].type="strikethroughSequence";const y={type:"strikethrough",start:Object.assign({},c[m][1].start),end:Object.assign({},c[d][1].end)},g={type:"strikethroughText",start:Object.assign({},c[m][1].end),end:Object.assign({},c[d][1].start)},x=[["enter",y,f],["enter",c[m][1],f],["exit",c[m][1],f],["enter",g,f]],v=f.parser.constructs.insideSpan.null;v&&rr(x,x.length,0,ec(v,c.slice(m+1,d),f)),rr(x,x.length,0,[["exit",g,f],["enter",c[d][1],f],["exit",c[d][1],f],["exit",y,f]]),rr(c,m-1,d-m+3,x),d=m+x.length-2;break}}for(d=-1;++d<c.length;)c[d][1].type==="strikethroughSequenceTemporary"&&(c[d][1].type="data");return c}function o(c,f,d){const m=this.previous,y=this.events;let g=0;return x;function x(S){return m===126&&y[y.length-1][1].type!=="characterEscape"?d(S):(c.enter("strikethroughSequenceTemporary"),v(S))}function v(S){const j=ka(m);if(S===126)return g>1?d(S):(c.consume(S),g++,v);if(g<2&&!r)return d(S);const D=c.exit("strikethroughSequenceTemporary"),R=ka(S);return D._open=!R||R===2&&!!j,D._close=!j||j===2&&!!R,f(S)}}}class TO{constructor(){this.map=[]}add(t,r,s){OO(this,t,r,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];s.push(t.slice()),t.length=0;let l=s.pop();for(;l;){for(const o of l)t.push(o);l=s.pop()}this.map.length=0}}function OO(e,t,r,s){let l=0;if(!(r===0&&s.length===0)){for(;l<e.map.length;){if(e.map[l][0]===t){e.map[l][1]+=r,e.map[l][2].push(...s);return}l+=1}e.map.push([t,r,s])}}function RO(e,t){let r=!1;const s=[];for(;t<e.length;){const l=e[t];if(r){if(l[0]==="enter")l[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(l[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const o=s.length-1;s[o]=s[o]==="left"?"center":"right"}}else if(l[1].type==="tableDelimiterRow")break}else l[0]==="enter"&&l[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return s}function MO(){return{flow:{null:{name:"table",tokenize:DO,resolveAll:LO}}}}function DO(e,t,r){const s=this;let l=0,o=0,c;return f;function f(z){let K=s.events.length-1;for(;K>-1;){const ee=s.events[K][1].type;if(ee==="lineEnding"||ee==="linePrefix")K--;else break}const I=K>-1?s.events[K][1].type:null,oe=I==="tableHead"||I==="tableRow"?P:d;return oe===P&&s.parser.lazy[s.now().line]?r(z):oe(z)}function d(z){return e.enter("tableHead"),e.enter("tableRow"),m(z)}function m(z){return z===124||(c=!0,o+=1),y(z)}function y(z){return z===null?r(z):Ie(z)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(z),e.exit("lineEnding"),v):r(z):at(z)?pt(e,y,"whitespace")(z):(o+=1,c&&(c=!1,l+=1),z===124?(e.enter("tableCellDivider"),e.consume(z),e.exit("tableCellDivider"),c=!0,y):(e.enter("data"),g(z)))}function g(z){return z===null||z===124||Rt(z)?(e.exit("data"),y(z)):(e.consume(z),z===92?x:g)}function x(z){return z===92||z===124?(e.consume(z),g):g(z)}function v(z){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(z):(e.enter("tableDelimiterRow"),c=!1,at(z)?pt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(z):S(z))}function S(z){return z===45||z===58?D(z):z===124?(c=!0,e.enter("tableCellDivider"),e.consume(z),e.exit("tableCellDivider"),j):H(z)}function j(z){return at(z)?pt(e,D,"whitespace")(z):D(z)}function D(z){return z===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(z),e.exit("tableDelimiterMarker"),R):z===45?(o+=1,R(z)):z===null||Ie(z)?ue(z):H(z)}function R(z){return z===45?(e.enter("tableDelimiterFiller"),O(z)):H(z)}function O(z){return z===45?(e.consume(z),O):z===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(z),e.exit("tableDelimiterMarker"),F):(e.exit("tableDelimiterFiller"),F(z))}function F(z){return at(z)?pt(e,ue,"whitespace")(z):ue(z)}function ue(z){return z===124?S(z):z===null||Ie(z)?!c||l!==o?H(z):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(z)):H(z)}function H(z){return r(z)}function P(z){return e.enter("tableRow"),W(z)}function W(z){return z===124?(e.enter("tableCellDivider"),e.consume(z),e.exit("tableCellDivider"),W):z===null||Ie(z)?(e.exit("tableRow"),t(z)):at(z)?pt(e,W,"whitespace")(z):(e.enter("data"),G(z))}function G(z){return z===null||z===124||Rt(z)?(e.exit("data"),W(z)):(e.consume(z),z===92?B:G)}function B(z){return z===92||z===124?(e.consume(z),G):G(z)}}function LO(e,t){let r=-1,s=!0,l=0,o=[0,0,0,0],c=[0,0,0,0],f=!1,d=0,m,y,g;const x=new TO;for(;++r<e.length;){const v=e[r],S=v[1];v[0]==="enter"?S.type==="tableHead"?(f=!1,d!==0&&(Fb(x,t,d,m,y),y=void 0,d=0),m={type:"table",start:Object.assign({},S.start),end:Object.assign({},S.end)},x.add(r,0,[["enter",m,t]])):S.type==="tableRow"||S.type==="tableDelimiterRow"?(s=!0,g=void 0,o=[0,0,0,0],c=[0,r+1,0,0],f&&(f=!1,y={type:"tableBody",start:Object.assign({},S.start),end:Object.assign({},S.end)},x.add(r,0,[["enter",y,t]])),l=S.type==="tableDelimiterRow"?2:y?3:1):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")?(s=!1,c[2]===0&&(o[1]!==0&&(c[0]=c[1],g=xu(x,t,o,l,void 0,g),o=[0,0,0,0]),c[2]=r)):S.type==="tableCellDivider"&&(s?s=!1:(o[1]!==0&&(c[0]=c[1],g=xu(x,t,o,l,void 0,g)),o=c,c=[o[1],r,0,0])):S.type==="tableHead"?(f=!0,d=r):S.type==="tableRow"||S.type==="tableDelimiterRow"?(d=r,o[1]!==0?(c[0]=c[1],g=xu(x,t,o,l,r,g)):c[1]!==0&&(g=xu(x,t,c,l,r,g)),l=0):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")&&(c[3]=r)}for(d!==0&&Fb(x,t,d,m,y),x.consume(t.events),r=-1;++r<t.events.length;){const v=t.events[r];v[0]==="enter"&&v[1].type==="table"&&(v[1]._align=RO(t.events,r))}return e}function xu(e,t,r,s,l,o){const c=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";r[0]!==0&&(o.end=Object.assign({},ca(t.events,r[0])),e.add(r[0],0,[["exit",o,t]]));const d=ca(t.events,r[1]);if(o={type:c,start:Object.assign({},d),end:Object.assign({},d)},e.add(r[1],0,[["enter",o,t]]),r[2]!==0){const m=ca(t.events,r[2]),y=ca(t.events,r[3]),g={type:f,start:Object.assign({},m),end:Object.assign({},y)};if(e.add(r[2],0,[["enter",g,t]]),s!==2){const x=t.events[r[2]],v=t.events[r[3]];if(x[1].end=Object.assign({},v[1].end),x[1].type="chunkText",x[1].contentType="text",r[3]>r[2]+1){const S=r[2]+1,j=r[3]-r[2]-1;e.add(S,j,[])}}e.add(r[3]+1,0,[["exit",g,t]])}return l!==void 0&&(o.end=Object.assign({},ca(t.events,l)),e.add(l,0,[["exit",o,t]]),o=void 0),o}function Fb(e,t,r,s,l){const o=[],c=ca(t.events,r);l&&(l.end=Object.assign({},c),o.push(["exit",l,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(r+1,0,o)}function ca(e,t){const r=e[t],s=r[0]==="enter"?"start":"end";return r[1][s]}const zO={name:"tasklistCheck",tokenize:PO};function UO(){return{text:{91:zO}}}function PO(e,t,r){const s=this;return l;function l(d){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),o)}function o(d){return Rt(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),c):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),c):r(d)}function c(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),f):r(d)}function f(d){return Ie(d)?t(d):at(d)?e.check({tokenize:BO},t,r)(d):r(d)}}function BO(e,t,r){return pt(e,s,"whitespace");function s(l){return l===null?r(l):t(l)}}function HO(e){return s1([fO(),wO(),NO(e),MO(),UO()])}const qO={};function IO(e){const t=this,r=e||qO,s=t.data(),l=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);l.push(HO(r)),o.push(lO()),c.push(oO(r))}function FO(e){j1(e,[/\r?\n|\r/g,$O])}function $O(){return{type:"break"}}function VO(){return function(e){FO(e)}}const hm=E.createContext(null);function Z1(e,t){const r=A1(t);return e&&r!==null?jT(r,e.baseFile):null}function YO({node:e,href:t,...r}){const s=E.useContext(hm),l=Z1(s,t);return!s||l===null?b.jsx("a",{...r,href:t,target:"_blank",rel:"noopener noreferrer"}):b.jsx("a",{...r,href:t,className:"md-file-link",onClick:o=>{o.preventDefault(),s.openFile(l)}})}function GO({node:e,src:t,alt:r,...s}){const l=E.useContext(hm),o=Z1(l,typeof t=="string"?t:void 0),[c,f]=E.useState(),[d,m]=E.useState(!1),y=l==null?void 0:l.loadFile;return E.useEffect(()=>{if(o===null||!y)return;let g=!1,x;return m(!1),y(o).then(v=>{g||(x=URL.createObjectURL(v),f(x))}).catch(()=>{g||m(!0)}),()=>{g=!0,x&&URL.revokeObjectURL(x)}},[o,y]),!l||o===null?b.jsx("img",{...s,src:t,alt:r}):d?b.jsx("span",{className:"md-image-missing",children:r||o}):c?b.jsx("img",{...s,src:c,alt:r,className:"md-file-image",onClick:()=>l.openFile(o)}):b.jsx("span",{className:"md-image-loading skeleton-line"})}const JO={a:YO,img:GO};function W1({content:e,files:t,baseFile:r}){const s=E.useMemo(()=>({openFile:t.openFile,loadFile:t.loadFile,baseFile:r}),[t.openFile,t.loadFile,r]);return b.jsx(hm.Provider,{value:s,children:b.jsx(wT,{remarkPlugins:[IO,VO],urlTransform:CT,components:JO,children:e})})}function XO({filePath:e,files:t,onClose:r}){const[s,l]=E.useState(null),[o,c]=E.useState(null),{loadFile:f}=t;E.useEffect(()=>{let y=!1,g;return l(null),c(null),(async()=>{try{const x=await f(e),v=MT(x.type),S={kind:v,size:x.size};if(v==="markdown"||v==="text"||v==="html"?S.text=await x.text():(g=URL.createObjectURL(x),S.objectUrl=g),y){g&&URL.revokeObjectURL(g);return}l(S)}catch(x){y||c(x instanceof Error?x.message:"Failed to load file.")}})(),()=>{y=!0,g&&URL.revokeObjectURL(g)}},[e,f]);const d=NT(e);function m(){if(o)return b.jsx("p",{className:"file-viewer-message",children:o});if(!s)return b.jsxs("div",{className:"file-viewer-loading",children:[b.jsx("div",{className:"skeleton-line",style:{width:"40%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"100%",height:"8rem"}})]});switch(s.kind){case"markdown":return b.jsx(W1,{content:s.text??"",files:t,baseFile:e});case"text":return b.jsx("pre",{className:"file-viewer-text",children:s.text});case"html":return b.jsx("iframe",{className:"file-viewer-frame",sandbox:"",srcDoc:s.text,title:d});case"image":return b.jsx("img",{src:s.objectUrl,alt:d,style:{maxWidth:"100%",height:"auto"}});case"binary":return In.isNativePlatform()?b.jsx("p",{className:"file-viewer-message",children:"Downloading this file type isn't supported in the app yet."}):b.jsxs("div",{className:"file-viewer-download",children:[b.jsxs("p",{className:"file-viewer-message",children:["This file can't be previewed (",DT(s.size),")."]}),b.jsx("a",{className:"btn btn-primary",href:s.objectUrl,download:d,children:"Download"})]})}}return b.jsx("div",{className:"report-dialog-overlay",onClick:r,children:b.jsxs("div",{className:"report-dialog",onClick:y=>y.stopPropagation(),children:[b.jsxs("div",{className:"report-dialog-header",children:[b.jsx("span",{className:"report-dialog-title",children:d}),b.jsx("button",{className:"report-dialog-close",onClick:r,"aria-label":"Close",children:b.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),b.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),b.jsx("div",{className:`report-dialog-body${(s==null?void 0:s.kind)==="html"?" report-dialog-body--frame":""}`,children:m()})]})})}function KO({connected:e,hostId:t,request:r,subscribeEvents:s,taskId:l,runId:o}){const c=Fr(),f=Yd(),[d,m]=E.useState(!0),[y,g]=E.useState([]),[x,v]=E.useState(),[S,j]=E.useState(),[D,R]=E.useState(),[O,F]=E.useState(!1),ue=x==="started",H=x==="followup",P=x==="started"||x==="followup",W=x==="needs_input",[G,B]=E.useState(null);Px(G!==null,()=>B(null));const[z,K]=E.useState(!1),[I,oe]=E.useState(""),[ee,te]=E.useState(!1),V=E.useRef(null),X=E.useRef(null),ge=E.useRef(null),[we,C]=E.useState(o==="latest"?void 0:o),L=o==="latest"&&we===null;E.useEffect(()=>{if(o!=="latest"){C(o);return}e&&(C(void 0),r("taskrun.list",{task_id:l,limit:1}).then(ae=>{var De,rt;return C(((rt=(De=ae.entries)==null?void 0:De[0])==null?void 0:rt.run_id)??null)}).catch(()=>C(null)))},[o,l,e,r]);async function J(){if(we)try{const ae=await r("task.result",{id:l,run_id:we});if(ae.error){console.error("No result:",ae.error),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0});return}g(ae.messages??[]),v(ae.running_state),j(ae.agent),R(ae.agent_version),F(!!ae.starred)}catch(ae){console.error("Failed to load result:",ae),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0})}finally{m(!1)}}async function N(){if(!we)return;const ae=!O;F(ae);try{const De=await r("taskrun.star",{task_id:l,run_id:we,starred:ae});if(De.error)throw new Error(De.error)}catch(De){console.error("Failed to update star:",De),F(!ae)}}const ve=E.useCallback(ae=>we?OT(r,l,we,ae):Promise.reject(new Error("Run not loaded.")),[r,l,we]),Ce=E.useMemo(()=>({openFile:B,loadFile:ve}),[ve]);E.useEffect(()=>{!e||!we||(m(!0),J())},[e,l,we]),E.useEffect(()=>!e||!t||!we?void 0:s(t,async De=>{try{const rt=JSON.parse(new TextDecoder().decode(De.data));if(rt.event_type!=="running-state"&&rt.event_type!=="result-updated"||De.subject.split(".").pop()!==l||rt.event_type==="result-updated"&&rt.run_id&&rt.run_id!==we)return;J()}catch{}}),[e,t,l,we,s,r]),E.useEffect(()=>{V.current&&(V.current.scrollTop=V.current.scrollHeight)},[y]),E.useEffect(()=>{d||L||!we||ge.current!==we&&(ge.current=we,requestAnimationFrame(()=>{V.current&&(V.current.scrollTop=V.current.scrollHeight),window.scrollTo({top:document.documentElement.scrollHeight,behavior:"auto"})}))},[d,L,we]);function ke(ae){if(ae==="input")return"User Input";if(ae==="confirmation")return"Confirmation"}function je(ae){return ae==="started"?"Task started":ae==="finished"?"Task finished":ae==="failed"?"Task failed":ae==="error"?"Command failed":ae==="aborted"?"Task aborted":ae==="confirmation"?"Task confirmed":ae==="stopped"?"Follow-up stopped":ae==="needs_input"?"Waiting for your reply":ae??""}const Ve=b.jsx("button",{type:"button",className:"btn btn-secondary chat-stop-btn",disabled:z,"aria-label":"Abort task",onClick:async()=>{if(confirm("Abort this task?")){K(!0);try{await r("task.abort",{id:l})}catch(ae){console.error("Abort failed:",ae)}finally{K(!1)}}},children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:b.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})});return b.jsxs("div",{className:"run-detail",children:[b.jsxs("div",{className:"run-detail-header",children:[b.jsxs("button",{className:"run-detail-back",onClick:()=>c(-1),children:[b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M15 18l-6-6 6-6"})}),"Back"]}),!d&&!L&&b.jsx($x,{starred:O,onToggle:N})]}),L?b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No runs yet"}),b.jsx("p",{className:"empty-state-hint",children:"This task hasn't been executed yet. Run it from the task menu or wait for its next trigger."})]}):d?b.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)",padding:"var(--space-sm) 0"},children:[b.jsx("div",{className:"skeleton-line",style:{width:"40%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"55%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"100%",height:"8rem",marginTop:"var(--space-sm)"}})]}):b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"chat-thread",ref:V,children:[y.map((ae,De)=>{const rt=P&&ae.role==="assistant"&&!y.slice(De+1).some(ct=>ct.role==="assistant"||ct.role==="user");return ae.role==="status"?b.jsxs("div",{className:`chat-status${ae.type==="error"?" chat-status--error":""}`,children:[b.jsxs("div",{children:[je(ae.type),ae.time>0&&b.jsx("span",{className:"chat-status-time",children:f(ae.time)})]}),ae.content&&b.jsx("pre",{className:"chat-status-detail",children:ae.content})]},De):b.jsxs("div",{className:`chat-message chat-message--${ae.role}${ae.role==="assistant"&&ae.stream==="stderr"?" chat-message--stderr":""}`,children:[ae.role==="assistant"&&S&&b.jsxs("div",{className:"chat-message-agent",children:[yd(S),D&&b.jsxs("span",{className:"chat-message-agent-version",children:[" v",D]})]}),b.jsxs("div",{className:"chat-message-content",children:[b.jsx(W1,{content:ae.content,files:Ce}),rt&&b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),ae.attachments&&ae.attachments.length>0&&b.jsx("div",{className:"chat-message-attachments",children:ae.attachments.map(ct=>b.jsx("button",{className:"chat-attachment-chip",onClick:()=>B(ct),children:ct},ct))}),b.jsxs("div",{className:"chat-message-meta",children:[ke(ae.type)&&b.jsx("span",{className:"chat-message-type",children:ke(ae.type)}),ae.model&&b.jsxs("span",{children:[ae.model," ·"]}),ae.time>0&&b.jsx("span",{children:f(ae.time)})]})]},De)}),P&&(()=>{const ae=y.filter(De=>De.role!=="status");return ae.length===0||ae[ae.length-1].role!=="assistant"})()&&b.jsxs("div",{className:"chat-message chat-message--assistant",children:[S&&b.jsxs("div",{className:"chat-message-agent",children:[yd(S),D&&b.jsxs("span",{className:"chat-message-agent-version",children:[" v",D]})]}),b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]})]}),ue||H?b.jsx("div",{className:"chat-input-bar",children:Ve}):b.jsxs("form",{className:"chat-input-bar",onSubmit:async ae=>{ae.preventDefault();const De=I.trim();if(!(!De||ee)){te(!0);try{await r("task.followup",{id:l,run_id:we,message:De}),oe("")}catch(rt){console.error("Follow-up failed:",rt)}finally{te(!1)}}},children:[b.jsx("input",{ref:X,className:"chat-input",type:"text",placeholder:W?"Reply to the agent":"Follow-up message",value:I,onChange:ae=>oe(ae.target.value),disabled:ee}),b.jsx("button",{className:"btn btn-primary chat-send-btn",type:"submit",disabled:!I.trim()||ee,children:b.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),b.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}),W&&Ve]}),b.jsxs("button",{className:"run-detail-back run-detail-back--footer",onClick:()=>c(-1),children:[b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M15 18l-6-6 6-6"})}),"Back"]})]}),G&&b.jsx(XO,{filePath:G,files:Ce,onClose:()=>B(null)})]})}function Zh({title:e,message:t,onUpdate:r,onDismiss:s}){return b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:e}),b.jsx("p",{className:"confirm-modal-message",children:t}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:r,children:"Update Now"}),s&&b.jsx("button",{className:"btn btn-secondary",onClick:s,children:"Dismiss"})]})]})})}function QO(){const{activeHost:e}=bi(),t=E.useRef(null);E.useEffect(()=>{if(In.isNativePlatform()||e.directUrl||t.current===e.hostId)return;async function r(){var s;try{if(!("serviceWorker"in navigator)||!("PushManager"in window)){console.warn("[Push] Push notifications not supported");return}const l=await navigator.serviceWorker.ready;(s=l.active)==null||s.postMessage({type:"set-host-id",hostId:e.hostId});let o=await l.pushManager.getSubscription();if(!o){const{publicKey:f}=await SE("/api/push/vapid-key");if(!f){console.warn("[Push] No VAPID public key configured on server");return}if(await Notification.requestPermission()!=="granted"){console.log("[Push] Permission denied");return}o=await l.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:f})}const c=o.toJSON();await wE("/api/push/subscribe",{hostId:e.hostId,endpoint:c.endpoint,keys:{p256dh:c.keys.p256dh,auth:c.keys.auth}}),t.current=e.hostId}catch(l){console.error("[Push] Subscription failed:",l)}}r()},[e])}const ZO="1.1.23",Wh=13e4;function vu(e,t){if(e.includes("-"))return!1;const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let l=0;l<3;l++){if((r[l]??0)<(s[l]??0))return!0;if((r[l]??0)>(s[l]??0))return!1}return!1}function wu(){const{removePairedHost:e,setHostLanUrl:t,setHostTimezone:r}=Wi(),{connected:s,request:l,subscribeEvents:o,unauthorized:c,activeHost:f}=bi(),d=f.hostId,m=f.clientToken||null,y=Fr(),g=vr(),x=Yu(),v=Ix("(min-width: 768px)"),S=g.pathname.endsWith("/tasks"),j=x.runId?void 0:x.taskId,D=!!(x.taskId&&x.runId),[R,O]=E.useState(!1),[F,ue]=E.useState(!1),[H,P]=E.useState(null),[W,G]=E.useState(null),[B,z]=E.useState(null),[K,I]=E.useState(null),[oe,ee]=E.useState({}),[te,V]=E.useState({}),[X,ge]=E.useState(null),[we,C]=E.useState(null),[L,J]=E.useState(null),[N,ve]=E.useState(null),[Ce,ke]=E.useState(new Set),[je,Ve]=E.useState([]),[ae,De]=E.useState(),[rt,ct]=E.useState("loading"),[Kt,Dt]=E.useState(0),tn=E.useRef(0),$t=E.useCallback(()=>{tn.current=0,ct("loading"),Dt(ye=>ye+1)},[]),nn=!!m&&N===m,[Ye,ft]=E.useState(new Map),[ht,xt]=E.useState(new Map),[Yt,An]=E.useState(new Map),[lt,$n]=E.useState(new Map),[ce,_e]=E.useState(new Map),[Me,Xe]=E.useState(new Map),[We,xe]=E.useState(new Map);QO(),E.useEffect(()=>{window.scrollTo(0,0)},[d]),E.useEffect(()=>{let ye=!1;return eC().then(Oe=>{ye||ke(Oe)}),()=>{ye=!0}},[]),E.useEffect(()=>{if(!s){tn.current=0,ct("loading");return}ct(Re=>Re==="error"?Re:"loading");let ye=!1,Oe;return l("host.info",void 0,{timeout:15e3}).then(Re=>{var cn,rn,Vt,yt,zt,wn,Dr,Si;if(ye)return;Ve(Re.agents??[]),ge(Re.playwright_cli??null),De(Re.host_platform),ve(Re.linked_client_token??null),zE(Re.agents??[]);const Je=Re.version??null;G(Je),O(!!Je&&vu(Je,ZO)),t(d,Re.lan_url??void 0),r(d,Re.host_timezone);const Pe=new Map,He=new Map,Ke=new Map,Lt=new Map;for(const Gt of Re.pending_prompts??[])if(Gt.type==="confirmation")Pe.set(Gt.key,{description:((cn=Gt.meta)==null?void 0:cn.description)??"",sessionName:(rn=Gt.meta)==null?void 0:rn.session_name});else if(Gt.type==="choice")He.set(Gt.key,{question:((Vt=Gt.meta)==null?void 0:Vt.description)??"",options:Gt.params??[],sessionName:(yt=Gt.meta)==null?void 0:yt.session_name});else if(Gt.type==="input"){const ns=Gt.params??((zt=Gt.meta)==null?void 0:zt.input_questions)??[];Ke.set(Gt.key,{questions:ns,description:(wn=Gt.meta)==null?void 0:wn.description,sessionName:(Dr=Gt.meta)==null?void 0:Dr.session_name,secret:(Si=Gt.meta)==null?void 0:Si.secret}),Lt.set(Gt.key,new Array(ns.length).fill(""))}ft(Pe),xt(He),An(Ke),$n(Lt),tn.current=0,ct("ready")}).catch(()=>{if(ye)return;ct("error");const Re=Math.min(2e3*2**tn.current,3e4);tn.current++,Oe=window.setTimeout(()=>Dt(Je=>Je+1),Re)}),()=>{ye=!0,clearTimeout(Oe)}},[s,d,l,t,r,Kt]),E.useEffect(()=>{if(rt!=="error")return;function ye(){document.visibilityState==="visible"&&$t()}return document.addEventListener("visibilitychange",ye),()=>document.removeEventListener("visibilitychange",ye)},[rt,$t]),E.useEffect(()=>s?o(d,Oe=>{let Re={};try{Re=JSON.parse(new TextDecoder().decode(Oe.data))}catch{return}const Je=Re.event_type,Pe=Re.session_id;if(Je==="input-request"&&Pe){const He=Re.input_questions,Ke=Re.session_name,Lt=Re.description,cn=Re.secret;He!=null&&He.length&&(An(rn=>{if(rn.has(Pe))return rn;const Vt=new Map(rn);return Vt.set(Pe,{questions:He,description:Lt,sessionName:Ke,secret:cn}),Vt}),$n(rn=>{if(rn.has(Pe))return rn;const Vt=new Map(rn);return Vt.set(Pe,new Array(He.length).fill("")),Vt}));return}if(Je==="input-resolved"&&Pe){An(He=>{if(!He.has(Pe))return He;const Ke=new Map(He);return Ke.delete(Pe),Ke}),$n(He=>{const Ke=new Map(He);return Ke.delete(Pe),Ke}),_e(He=>{if(!He.has(Pe))return He;const Ke=new Map(He);return Ke.delete(Pe),Ke});return}if(Je==="confirm-request"&&Pe){const He=Re.description,Ke=Re.session_name;He&&ft(Lt=>{if(Lt.has(Pe))return Lt;const cn=new Map(Lt);return cn.set(Pe,{description:He,sessionName:Ke}),cn});return}if(Je==="confirm-resolved"&&Pe){ft(He=>{if(!He.has(Pe))return He;const Ke=new Map(He);return Ke.delete(Pe),Ke});return}if(Je==="choice-request"&&Pe){const He=Re.description,Ke=Re.options,Lt=Re.session_name;He&&(Ke!=null&&Ke.length)&&xt(cn=>{if(cn.has(Pe))return cn;const rn=new Map(cn);return rn.set(Pe,{question:He,options:Ke,sessionName:Lt}),rn});return}if(Je==="choice-resolved"&&Pe){xt(He=>{if(!He.has(Pe))return He;const Ke=new Map(He);return Ke.delete(Pe),Ke});return}}):void 0,[s,d,o]);async function Fe(ye,Oe,Re,Je){if(!Me.has(ye)){Xe(Pe=>new Map(Pe).set(ye,Oe)),xe(Pe=>{const He=new Map(Pe);return He.delete(ye),He});try{await l("task.user_input",{id:ye,value:Re},{timeout:3e4}),Je()}catch(Pe){console.error("[Dashboard] Failed to send user input:",Pe),xe(He=>new Map(He).set(ye,"Couldn't reach the host. Try again."))}finally{Xe(Pe=>{const He=new Map(Pe);return He.delete(ye),He})}}}function Ae(ye,Oe){Fe(ye,Oe,[Oe],()=>{ft(Re=>{const Je=new Map(Re);return Je.delete(ye),Je})})}function Ge(ye,Oe){Fe(ye,Oe,[Oe],()=>{xt(Re=>{const Je=new Map(Re);return Je.delete(ye),Je})})}function gt(ye,Oe,Re){Fe(ye,Oe,Re,()=>{An(Je=>{const Pe=new Map(Je);return Pe.delete(ye),Pe}),$n(Je=>{const Pe=new Map(Je);return Pe.delete(ye),Pe}),_e(Je=>{const Pe=new Map(Je);return Pe.delete(ye),Pe})})}function dt(ye,Oe){if(!Ss())return;const Re=`/hosts/${encodeURIComponent(d)}/runs/${encodeURIComponent(ye)}`;y(Oe?`${Re}/${encodeURIComponent(Oe)}`:Re)}E.useEffect(()=>{if(!W)return;let ye=!1;return fetch("https://registry.npmjs.org/palmier/latest").then(Oe=>Oe.ok?Oe.json():null).then(Oe=>{!ye&&(Oe!=null&&Oe.version)&&z(Oe.version)}).catch(()=>{}),()=>{ye=!0}},[W]),E.useEffect(()=>{let ye=!1;for(const Oe of je)!Oe.version||!Oe.npmPackage||fetch(`https://registry.npmjs.org/${Oe.npmPackage}/latest`).then(Re=>Re.ok?Re.json():null).then(Re=>{ye||!(Re!=null&&Re.version)||ee(Je=>Je[Oe.key]===Re.version?Je:{...Je,[Oe.key]:Re.version})}).catch(()=>{});return()=>{ye=!0}},[je]);const Qt=je.find(ye=>{if(!ye.version)return!1;const Oe=oe[ye.key];return!Oe||!vu(ye.version,Oe)?!1:te[ye.key]!==Oe});function gn(ye,Oe){V(Re=>({...Re,[ye]:Oe}))}async function vi(ye){ue("agent"),P(null);try{const Oe=await l("host.updateAgent",{key:ye},{timeout:Wh});if(Oe.error){P(Oe.error),ue(!1);return}const Re=await l("host.info");Re.agents&&Ve(Re.agents)}catch(Oe){P(Oe instanceof Error?Oe.message:String(Oe))}finally{ue(!1)}}E.useEffect(()=>{if(!(X!=null&&X.npmPackage))return;let ye=!1;return fetch(`https://registry.npmjs.org/${X.npmPackage}/latest`).then(Oe=>Oe.ok?Oe.json():null).then(Oe=>{!ye&&(Oe!=null&&Oe.version)&&C(Oe.version)}).catch(()=>{}),()=>{ye=!0}},[X==null?void 0:X.npmPackage,X==null?void 0:X.version]);const ar=X&&we&&vu(X.version,we)&&L!==we?X:null;function wr(ye){J(ye)}async function Mr(){ue("playwright"),P(null);try{const ye=await l("host.updatePlaywrightCli",void 0,{timeout:Wh});if(ye.error){P(ye.error),ue(!1);return}const Oe=await l("host.info");ge(Oe.playwright_cli??null)}catch(ye){P(ye instanceof Error?ye.message:String(ye))}finally{ue(!1)}}const jn=!R&&!!W&&!!B&&vu(W,B)&&K!==B;function Vr(){B&&I(B)}async function Yr(){ue("daemon"),P(null);try{const ye=await l("host.update",void 0,{timeout:Wh});if(ye.error){P(ye.error),ue(!1);return}}catch{}setTimeout(()=>window.location.reload(),3e4)}const Gr=Ye.size>0||ht.size>0||Yt.size>0,wi=s&&!c;return b.jsxs("div",{className:"dashboard",children:[v&&b.jsx(Q0,{daemonVersion:W,agents:je,playwrightCli:X,linkedClientToken:N,request:l,onEnabledCapabilitiesChange:ke,onLinkedClientTokenChange:ve}),b.jsxs("div",{className:"dashboard-content",children:[b.jsxs("header",{className:"app-header",children:[b.jsxs("div",{className:"app-title-bar",children:[!v&&b.jsx(Q0,{daemonVersion:W,agents:je,playwrightCli:X,linkedClientToken:N,request:l,onEnabledCapabilitiesChange:ke,onLinkedClientTokenChange:ve}),b.jsx("h1",{className:"app-title",children:"Palmier"}),b.jsx(aC,{})]}),b.jsx("div",{className:"tab-bar",children:b.jsx(QE,{})})]}),b.jsx("main",{className:"dashboard-main",children:c?b.jsxs("div",{className:"revoked-state",children:[b.jsx("div",{className:"revoked-icon",children:b.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),b.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}),b.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"18"})]})}),b.jsx("h2",{className:"revoked-title",children:"Client Revoked"}),b.jsx("p",{className:"revoked-description",children:"This client was revoked by the host. To reconnect, generate a new pairing code on the host machine."}),b.jsx("div",{className:"revoked-command",children:b.jsx("code",{children:"palmier pair"})}),b.jsxs("div",{className:"revoked-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>{Ss()&&y("/pair")},children:"Re-pair Device"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{e(d),y("/",{replace:!0})},children:"Remove Host"})]})]}):wi?b.jsxs(b.Fragment,{children:[S&&!D&&b.jsx(KE,{connected:s,hostId:d,request:l,subscribeEvents:o,agents:je,hostPlatform:ae,isNotificationListener:nn&&Ce.has("notifications"),onViewRun:dt,hostInfoStatus:rt,onRetryHostInfo:$t}),D?b.jsx(KO,{connected:s,hostId:d,request:l,subscribeEvents:o,taskId:x.taskId,runId:decodeURIComponent(x.runId)}):S?null:b.jsx(cC,{connected:s,hostId:d,request:l,subscribeEvents:o,agents:je,hostPlatform:ae,filterTaskId:j,onClearFilter:()=>{Ss()&&y(`/hosts/${encodeURIComponent(d)}`)},hostInfoStatus:rt,onRetryHostInfo:$t})]}):b.jsx("div",{className:"empty-state",children:b.jsx("p",{className:"empty-state-text",children:"Connecting to host…"})})}),(R||jn)&&!F&&!H&&!Gr&&b.jsx(Zh,{title:R?"Update Required":"Update Available",message:R?`Your Palmier host${W?` (v${W})`:""} is too old for this version of the app. Please update to continue.`:`A new version of Palmier (v${B}) is available. You're running v${W}.`,onUpdate:Yr,onDismiss:R?void 0:Vr}),!R&&!jn&&Qt&&!F&&!H&&!Gr&&b.jsx(Zh,{title:"Agent Update Available",message:`A new version of ${Qt.label} (v${oe[Qt.key]}) is available. You're running v${Qt.version}.`,onUpdate:()=>vi(Qt.key),onDismiss:()=>gn(Qt.key,oe[Qt.key])}),!R&&!jn&&!Qt&&ar&&we&&!F&&!H&&!Gr&&b.jsx(Zh,{title:"Browser Automation Update Available",message:`A new version of ${ar.label} (v${we}) is available. You're running v${ar.version}.`,onUpdate:Mr,onDismiss:()=>wr(we)}),F&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Updating..."}),b.jsx("p",{className:"confirm-modal-message",children:F==="daemon"?"Installing update and restarting daemon. Please wait...":"Installing update. Please wait..."})]})}),H&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Update Failed"}),b.jsx("p",{className:"confirm-modal-message",style:{whiteSpace:"pre-line"},children:H}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>{P(null)},children:"Retry"})})]})})]}),mi.createPortal(b.jsxs(b.Fragment,{children:[[...Ye.entries()].map(([ye,{description:Oe,sessionName:Re}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Confirmation Required"}),Re&&b.jsx("p",{className:"confirm-modal-subtitle",children:Re}),b.jsx("p",{className:"confirm-modal-message",children:Oe}),We.has(ye)&&b.jsx("p",{className:"form-error",children:We.get(ye)}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsxs("button",{className:"btn btn-primary",disabled:Me.has(ye),onClick:()=>Ae(ye,"confirmed"),children:[Me.get(ye)==="confirmed"&&b.jsx("span",{className:"btn-spinner"}),"Confirm"]}),b.jsxs("button",{className:"btn btn-secondary",disabled:Me.has(ye),onClick:()=>Ae(ye,"aborted"),children:[Me.get(ye)==="aborted"&&b.jsx("span",{className:"btn-spinner btn-spinner-current"}),"Abort"]})]})]})},ye)),[...ht.entries()].map(([ye,{question:Oe,options:Re,sessionName:Je}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Question"}),Je&&b.jsx("p",{className:"confirm-modal-subtitle",children:Je}),b.jsx("p",{className:"confirm-modal-message",children:Oe}),We.has(ye)&&b.jsx("p",{className:"form-error",children:We.get(ye)}),b.jsx("div",{className:`confirm-modal-actions${Re.length===2&&Re.every(Pe=>Pe.length<=16)?"":" choice-options-stacked"}`,children:Re.map((Pe,He)=>b.jsxs("button",{className:"btn btn-secondary",disabled:Me.has(ye),onClick:()=>Ge(ye,String(He)),children:[Me.get(ye)===String(He)&&b.jsx("span",{className:"btn-spinner btn-spinner-current"}),Pe]},He))}),b.jsxs("button",{className:"prompt-abort-link",disabled:Me.has(ye),onClick:()=>Ge(ye,"aborted"),children:[Me.get(ye)==="aborted"&&b.jsx("span",{className:"btn-spinner btn-spinner-current"}),"Abort Task"]})]})},ye)),[...Yt.entries()].map(([ye,{questions:Oe,description:Re,sessionName:Je,secret:Pe}])=>{const He=lt.get(ye)??new Array(Oe.length).fill("");return b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal input-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:Pe?"Password Required":"Input Required"}),Je&&b.jsx("p",{className:"confirm-modal-subtitle",children:Je}),Re&&b.jsx("p",{className:"confirm-modal-message",children:Re}),b.jsx("div",{className:"input-list",children:Oe.map((Ke,Lt)=>b.jsxs("div",{className:"input-item",children:[b.jsx("label",{className:"input-label",children:Ke}),b.jsx("input",{type:Pe?"password":"text",autoComplete:Pe?"off":void 0,className:"input-field",value:He[Lt]??"",onChange:cn=>{$n(rn=>{const Vt=new Map(rn),yt=[...Vt.get(ye)??[]];return yt[Lt]=cn.target.value,Vt.set(ye,yt),Vt})},disabled:Me.has(ye),autoFocus:Lt===0})]},Lt))}),Pe&&b.jsxs("label",{className:"toggle-label input-save-toggle",children:[b.jsx("input",{type:"checkbox",checked:ce.get(ye)??!0,disabled:Me.has(ye),onChange:Ke=>_e(Lt=>new Map(Lt).set(ye,Ke.target.checked))}),"Save this password"]}),We.has(ye)&&b.jsx("p",{className:"form-error",children:We.get(ye)}),b.jsx("div",{className:"input-actions",children:b.jsxs("button",{className:"btn btn-primary",disabled:Me.has(ye)||He.some(Ke=>!Ke.trim()),onClick:()=>{const Ke=Pe?[...He,ce.get(ye)??!0?"save":"nosave"]:He;gt(ye,"submit",Ke)},children:[Me.get(ye)==="submit"&&b.jsx("span",{className:"btn-spinner"}),"Submit"]})}),b.jsxs("button",{className:"prompt-abort-link",disabled:Me.has(ye),onClick:()=>gt(ye,"aborted",["aborted"]),children:[Me.get(ye)==="aborted"&&b.jsx("span",{className:"btn-spinner btn-spinner-current"}),"Abort"]})]})},ye)})]}),document.body)]})}const WO=ks("Preferences",{web:()=>Vd(()=>import("./web-CyFdutiL.js"),[]).then(e=>new e.PreferencesWeb)}),Al=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),$b=In.isNativePlatform();function e4(){const[e,t]=E.useState(""),[r,s]=E.useState(!0),[l,o]=E.useState(!1),[c,f]=E.useState(null),{addPairedHost:d,pairedHosts:m}=Wi(),y=Fr();async function g(){const x=e.trim().toUpperCase();if(!x){f("Enter a pairing code.");return}o(!0),f(null);try{let v;if(Al){const D=await fetch("/pair",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:x,label:navigator.userAgent})});if(!D.ok){const R=await D.json().catch(()=>({error:"Connection failed"}));throw new Error(R.error||`HTTP ${D.status}`)}v=await D.json()}else{const D=await fetch(`${Bu}/api/config`);if(!D.ok)throw new Error("Failed to fetch server config");const R=await D.json();if(!R.natsWsUrl)throw new Error("Server has no NATS WebSocket URL configured");const O=await Dx({servers:R.natsWsUrl,authenticator:Ex(R.natsJwt,new TextEncoder().encode(R.natsNkeySeed))}),F=Ru(),ue=`pair.${x}`,H=await O.request(ue,F.encode(JSON.stringify({label:navigator.userAgent})),{timeout:1e4});v=JSON.parse(F.decode(H.data)),await O.close()}const S={hostId:v.hostId,clientToken:v.clientToken,directUrl:Al?window.location.origin:void 0,...v.hostName?{name:v.hostName}:{}};if(d(S),In.isNativePlatform()&&kn){await WO.set({key:"hostId",value:v.hostId});try{const{token:D}=await kn.getFcmToken();await fetch(`${Bu}/api/fcm/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostId:v.hostId,fcmToken:D})})}catch(D){console.warn("FCM token registration failed:",D)}}const j=`/hosts/${encodeURIComponent(v.hostId)}`;y($b&&r?`${j}/pair/setup`:j)}catch(v){const S=v instanceof Error?v.message:String(v);S.includes("timeout")||S.includes("TIMEOUT")||S.includes("503")||S.toLowerCase().includes("no responders")?f("Code not found or expired. Check the code and try again."):f(S)}finally{o(!1)}}return b.jsx("div",{className:"pair-page",children:b.jsxs("div",{className:"pair-card",children:[b.jsxs("div",{className:"pair-header",children:[b.jsx("h1",{className:"pair-title",children:Al?"Pair":"Pair with Host"}),b.jsx("p",{className:"pair-subtitle",children:Al?"Enter the pairing code shown in your terminal.":"Connect this device to a Palmier host"})]}),!Al&&b.jsxs("div",{className:"pair-instructions",children:[b.jsxs("div",{className:"pair-instruction-block",children:[b.jsx("h3",{className:"pair-instruction-heading",children:"Setting up a new host?"}),b.jsxs("ol",{className:"pair-steps",children:[b.jsxs("li",{children:["Install Palmier on your host machine.",b.jsx("span",{className:"pair-platform-label",children:"Linux / macOS:"}),b.jsx("code",{className:"pair-command",children:"curl -fsSL https://palmier.me/install.sh | bash"}),b.jsx("span",{className:"pair-platform-label",children:"Windows (PowerShell):"}),b.jsx("code",{className:"pair-command",children:"irm https://palmier.me/install.ps1 | iex"})]}),b.jsxs("li",{children:["Run the setup wizard:",b.jsx("code",{className:"pair-command",children:"palmier init"})]}),b.jsx("li",{children:"A pairing code will display automatically"})]})]}),b.jsx("div",{className:"pair-instruction-divider"}),b.jsxs("div",{className:"pair-instruction-block",children:[b.jsx("h3",{className:"pair-instruction-heading",children:"Pairing an existing host?"}),b.jsxs("ol",{className:"pair-steps",children:[b.jsxs("li",{children:["Run ",b.jsx("code",{children:"palmier pair"})," on the host machine"]}),b.jsx("li",{children:"Enter the 6-character code below"})]})]})]}),b.jsxs("div",{className:"pair-form",children:[b.jsxs("label",{className:"form-label",htmlFor:"pair-code",children:["Pairing code",b.jsx("input",{id:"pair-code",type:"text",maxLength:6,value:e,onChange:x=>t(x.target.value.toUpperCase()),placeholder:"A7K9M2",className:"form-input form-input-mono pair-code-input",autoFocus:!0,autoComplete:"off",disabled:l})]}),$b&&b.jsxs("label",{className:"pair-checkbox",children:[b.jsx("input",{type:"checkbox",checked:r,onChange:x=>s(x.target.checked),disabled:l}),b.jsxs("span",{className:"pair-checkbox-text",children:[b.jsx("span",{className:"pair-checkbox-title",children:"Link the host to this device"}),b.jsx("span",{className:"pair-checkbox-hint",children:r?"The host will use this device for SMS, contacts, calendar, location, and alarms. Only one device can be linked to the host.":"This device won't provide SMS, contacts, calendar, location, or alarms to the host. You can link it later from the menu."})]})]}),c&&b.jsx("p",{className:"pair-error",children:c}),b.jsxs("button",{className:"btn btn-primary btn-full",onClick:g,disabled:l||!e.trim(),children:[l&&b.jsx("span",{className:"btn-spinner"}),l?"Pairing...":"Pair"]}),m.length>0&&b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>y("/"),disabled:l,children:"Cancel"}),b.jsxs("p",{className:"pair-consent",children:["By pairing, you agree to our"," ",b.jsx("a",{href:"https://www.palmier.me/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," and"," ",b.jsx("a",{href:"https://www.palmier.me/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]})]})]})})}function t4(){const e=Fr(),{connected:t,request:r,activeHost:s}=bi(),{setHostLanUrl:l,pairedHosts:o}=Wi(),c=o.length<=1,[f,d]=E.useState("loading"),[m,y]=E.useState(null),[g,x]=E.useState(null);function v(){e(`/hosts/${encodeURIComponent(s.hostId)}`,{replace:!0})}E.useEffect(()=>{if(!t||f!=="loading")return;let O=!1;return r("host.info").catch(()=>({})).then(F=>{if(O)return;l(s.hostId,F.lan_url??void 0);const ue=F.linked_client_token??null;y(ue);const H=!!ue&&ue!==s.clientToken;d(H?"confirming":"linking")}),()=>{O=!0}},[t,f,s,r,l]),E.useEffect(()=>{if(f!=="linking")return;let O=!1;return(async()=>{try{if(kn){const{token:F}=await kn.getFcmToken();if(!F)throw new Error("Could not read FCM token");await r("device.link",{fcmToken:F})}if(O)return;c?d("wizard"):v()}catch(F){if(O)return;x(F instanceof Error?F.message:String(F)),d("linkError")}})(),()=>{O=!0}},[f]);function S(){d("linking")}function j(){v()}function D(){x(null),d("linking")}const R=f==="confirming"&&mi.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:j,children:b.jsxs("div",{className:"confirm-modal",onClick:O=>O.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Link the host to this device?"}),b.jsx("p",{className:"confirm-modal-message",children:"Another device is already linked to this host. Only one device can be linked to the host — switching will disable those capabilities on the currently linked device."}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:j,children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:S,children:"Link"})]})]})}),document.body);if(f==="loading"||f==="confirming"||f==="linking"||f==="linkError"){const O=c,F=f==="loading"||f==="confirming"||f==="linking";return b.jsxs("div",{className:"pair-setup",children:[b.jsxs("div",{className:"pair-setup-inner",children:[O&&b.jsx("h1",{className:"pair-setup-title",children:"Device Capabilities"}),b.jsxs("div",{className:"pair-setup-loading",children:[F&&b.jsx("span",{className:"spinner spinner-lg"}),f==="loading"&&b.jsx("span",{children:"Connecting to host…"}),f==="confirming"&&b.jsx("span",{children:"Awaiting confirmation…"}),f==="linking"&&b.jsx("span",{children:"Linking device…"}),f==="linkError"&&b.jsxs(b.Fragment,{children:[b.jsx("p",{className:"pair-error",children:g}),b.jsx("button",{className:"btn btn-primary",onClick:D,children:"Retry"}),b.jsx("button",{className:"btn btn-secondary",onClick:v,children:"Skip linking"})]})]})]}),R]})}return b.jsx("div",{className:"pair-setup",children:b.jsxs("div",{className:"pair-setup-inner",children:[b.jsx("h1",{className:"pair-setup-title",children:"Device Capabilities"}),b.jsx("p",{className:"pair-setup-description",children:"Choose what the host can use this device for. You can change these later from the menu."}),b.jsx(Fx,{}),b.jsx("div",{className:"pair-setup-actions",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:v,children:"Finish"})})]})})}function n4(){const e=Fr();return E.useEffect(()=>{if(!kn)return;const t=kn.addListener("deepLink",({path:r})=>e(r));return()=>{t.then(r=>r.remove())}},[e]),null}function r4(){const{pairedHosts:e,lastHostId:t}=Wi();if(e.length===0)return b.jsx(Bl,{to:"/pair",replace:!0});const r=e.find(s=>s.hostId===t)??e[0];return b.jsx(Bl,{to:`/hosts/${encodeURIComponent(r.hostId)}`,replace:!0})}function i4(){const{hostId:e}=Yu(),{pairedHosts:t,setLastHostId:r}=Wi(),s=t.find(l=>l.hostId===e)??null;return E.useEffect(()=>{s&&r(s.hostId)},[s==null?void 0:s.hostId,r]),s?b.jsx(CE,{activeHost:s,children:b.jsxs(ax,{children:[b.jsx(Ar,{index:!0,element:b.jsx(wu,{},e)}),b.jsx(Ar,{path:"tasks",element:b.jsx(wu,{},e)}),b.jsx(Ar,{path:"runs/:taskId",element:b.jsx(wu,{},e)}),b.jsx(Ar,{path:"runs/:taskId/:runId",element:b.jsx(wu,{},e)}),b.jsx(Ar,{path:"pair/setup",element:b.jsx(t4,{})}),b.jsx(Ar,{path:"*",element:b.jsx(Bl,{to:".",replace:!0})})]})},`${s.hostId}|${s.clientToken}`):b.jsx(Bl,{to:"/",replace:!0})}function s4(){return b.jsxs(K_,{children:[b.jsx(n4,{}),b.jsxs(ax,{children:[b.jsx(Ar,{path:"/",element:b.jsx(r4,{})}),b.jsx(Ar,{path:"/pair",element:b.jsx(e4,{})}),b.jsx(Ar,{path:"/hosts/:hostId/*",element:b.jsx(i4,{})}),b.jsx(Ar,{path:"*",element:b.jsx(Bl,{to:"/",replace:!0})})]})]})}yS.createRoot(document.getElementById("root")).render(b.jsx(E.StrictMode,{children:b.jsx(U_,{children:b.jsx(s4,{})})}));export{$d as W};