palmier 0.9.20 → 0.9.21

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,10 +84,10 @@ ${d}`),g(_);return}f(null,j),s.strategy===xr.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:u,headers:s.headers}),c}else{const u=new xx(this.protocol.muxSubscriptions,t,s,l);this.protocol.request(u);try{this.publish(t,r,{reply:`${this.protocol.muxSubscriptions.baseInbox}${u.token}`,headers:s.headers})}catch(f){u.cancel(f)}const c=Promise.race([u.timer,u.deferred]);return c.catch(()=>{u.cancel()}),c}}flush(){return this.isClosed()?Promise.reject(Ne.errorForCode(ke.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(Ne.errorForCode(ke.ConnectionClosed)):this.isDraining()?Promise.reject(Ne.errorForCode(ke.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 sn;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 Bk(this,t);if(t.checkAPI!==!1)try{await r.getAccountInfo()}catch(s){const l=s;throw l.code===ke.NoResponders&&(l.code=ke.JetStreamNotEnabled),l}return r}jetstream(t={}){return new Hd(this,t)}getServerVersion(){const t=this.info;return t?ms(t.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw Ne.errorForCode(ke.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 Ik(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(Ne.errorForCode(ke.ConnectionClosed)):this.isDraining()?Promise.reject(Ne.errorForCode(ke.ConnectionDraining)):this.protocol.reconnect()}}class Ik{constructor(t){C(this,"nc");this.nc=t}add(t){try{return new Vl(this.nc,t).start()}catch(r){return Promise.reject(r)}}client(t,r){return new wk(this.nc,t,r)}}class Fk{constructor(t,r,s){C(this,"bucket");C(this,"sm");C(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(Uu)||"PUT"}get length(){const t=this.sm.header.get(kn.MessageSizeHdr)||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class $k{constructor(t,r,s){C(this,"bucket");C(this,"key");C(this,"sm");this.bucket=t,this.key=r,this.sm=s}get value(){return this.sm.data}get created(){return new Date(Ld(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var t;return((t=this.sm.headers)==null?void 0:t.get(Uu))||"PUT"}get delta(){return this.sm.info.pending}get length(){var r;const t=((r=this.sm.headers)==null?void 0:r.get(kn.MessageSizeHdr))||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Rx extends w2{constructor(r,s,l){super(r.nc,s,l);C(this,"js");C(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=ni(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const u=this.info;u.config.name=Pi.next(),u.ordered_consumer_sequence.delivery_seq=0,u.flow_control.heartbeat_count=0,u.flow_control.fc_count=0,u.flow_control.consumer_restarts++,u.deliver=s,u.config.deliver_subject=s,u.config.deliver_policy=Vt.StartSequence,u.config.opt_start_seq=r;const c={};c.stream_name=this.info.stream,c.config=u.config;const f=`${u.api.prefix}.CONSUMER.CREATE.${u.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 Ne(`unable to recreate ordered consumer ${u.stream} at seq ${r}`,ke.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(Ld(r))}_setupHbMonitoring(r,s=0){const l={cancelAfter:0,maxOut:2};s&&(l.cancelAfter=s);const u=this.sub,c=f=>{var y,g,x,w;const d=t2(409,`${or.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 _=((x=(g=this.info)==null?void 0:g.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(_+1),(w=this.monitor)==null||w.restart(),!1}return!u.noIterator};this.monitor=new Ud(r,c,l)}_checkHbOrderConsumer(r){const s=r.headers.get(kn.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const l=parseInt(r.headers.get(kn.LastConsumerSeqHdr),10),u=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,l!==u.delivery_seq&&this._resetOrderedConsumer(u.stream_seq+1),!1}_checkOrderedConsumer(r){const s=this.info.ordered_consumer_sequence,l=r.info.streamSequence,u=r.info.deliverySequence;return u!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=u,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}`,u=await r.api._request(l);return r.last=u,u}}class Yk extends Rx{constructor(t,r,s){super(t,r,s)}pull(t={batch:1}){const{stream:r,config:s,name:l}=this.sub.info,u=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(ht.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=zt(f));let d=0;if(t.idle_heartbeat&&t.idle_heartbeat>0&&(d=t.idle_heartbeat,c.idle_heartbeat=zt(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}.${u}`,g=this.sub.subject;m.nc.publish(y,m.jc.encode(c),{reply:g})}}}function Vk(e,t){return e?Jk(t):Gk(t)}function Gk(e){return(t,r)=>t?[t,null]:(t=ua(r),t?[t,null]:[null,Hl(r,e)])}function Jk(e){return(t,r)=>{if(t)return[t,null];const s=ua(r);return s!==null?[Mx(s),null]:[null,Hl(r,e)]}}function Mx(e){if(e!==null)switch(e.code){case ke.JetStream404NoMessages:case ke.JetStream408RequestTimeout:return null;case ke.JetStream409:return n2(e)?e:null;default:return e}return null}function Xk(e){e&&e.ack()}function Kk(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 Qk{constructor(t,r){C(this,"msg");C(this,"di");C(this,"didAck");C(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=Kk(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]===xl[0]&&t[1]===xl[1]&&t[2]===xl[2]&&t[3]===xl[3]}async ackAck(t){var s;t=t||{},t.timeout=t.timeout||this.timeout;const r=Ut();if(this.didAck)r.resolve(!1);else if(this.didAck=!0,this.msg.reply){const u=this.msg.publisher,c=!((s=u.options)!=null&&s.noAsyncTraces),f=new xx(u.muxSubscriptions,this.msg.reply,{timeout:t.timeout},c);u.request(f);try{u.publish(this.msg.reply,L0,{reply:`${u.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(L0)}nak(t){let r=Ok;t&&(r=Ou().encode(`-NAK ${JSON.stringify({delay:zt(t)})}`)),this.doAck(r)}working(){this.doAck(xl)}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=zt(r.expires));const l=vr().encode(s),u=ga.concat(Rk,Dk,l),c=t?{reply:t}:void 0;this.msg.respond(u,c)}term(t=""){let r=Mk;(t==null?void 0:t.length)>0&&(r=Ou().encode(`+TERM ${t}`)),this.doAck(r)}json(){return this.msg.json()}string(){return this.msg.string()}}const Zk="1.30.3",Wk="nats.ws";class eE{constructor(){C(this,"version");C(this,"lang");C(this,"closeError");C(this,"connected");C(this,"done");C(this,"socket");C(this,"options");C(this,"socketClosed");C(this,"encrypted");C(this,"peeked");C(this,"yields");C(this,"signal");C(this,"closedNotification");this.version=Zk,this.lang=Wk,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=Ut(),this.closedNotification=Ut()}async connect(t,r){const s=Ut();if(r.tls)return s.reject(new Ne("tls",ke.InvalidOption)),s;this.options=r;const l=t.src;if(r.wsFactory){const{socket:u,encrypted:c}=await r.wsFactory(t.src,r);this.socket=u,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=u=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(u.data)),this.peeked){this.signal.resolve();return}const c=ga.concat(...this.yields),f=A2(c);if(f!==""){const d=dk.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]);fk(m,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(m){s.reject(m);return}}},this.socket.onclose=u=>{if(this.isDiscarded())return;this.socketClosed=!0;let c;this.done||(u.wasClean||(c=new Error(u.reason)),this._closed(c))},this.socket.onerror=u=>{if(this.isDiscarded())return;const c=u,f=new Ne(c.message,ke.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 Sa(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=Ut())}}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 tE(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 u,c;const f=s.hostname,d=s.pathname,m=s.search||"";switch(l){case"http:":case"ws:":case"nats:":c=s.port||"80",u="ws:";break;case"https:":case"wss:":case"tls:":c=s.port||"443",u="wss:";break;default:c=s.port||t===!0?"443":"80",u=t===!0?"wss:":"ws:";break}return`${u}//${f}:${c}${d}${m}`}function Dx(e={}){return S2({defaultPort:443,urlParseFn:tE,factory:()=>new eE}),qd.connect(e)}/*! Capacitor: https://capacitorjs.com/ - MIT License */var ya;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(ya||(ya={}));class Th extends Error{constructor(t,r,s){super(t),this.message=t,this.code=r,this.data=s}}const nE=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"},rE=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},s=r.Plugins=r.Plugins||{},l=()=>t!==null?t.name:nE(e),u=()=>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(w=>w.name===g)},d=g=>e.console.error(g),m=new Map,y=(g,x={})=>{const w=m.get(g);if(w)return console.warn(`Capacitor plugin "${g}" already registered. Cannot register plugins twice.`),w.proxy;const _=l(),j=f(g);let D;const N=async()=>(!D&&_ in x?D=typeof x[_]=="function"?D=await x[_]():D=x[_]:t!==null&&!D&&"web"in x&&(D=typeof x.web=="function"?D=await x.web():D=x.web),D),H=($,q)=>{var L,G;if(j){const J=j==null?void 0:j.methods.find(oe=>q===oe.name);if(J)return J.rtype==="promise"?oe=>r.nativePromise(g,q.toString(),oe):(oe,le)=>r.nativeCallback(g,q.toString(),oe,le);if($)return(L=$[q])===null||L===void 0?void 0:L.bind($)}else{if($)return(G=$[q])===null||G===void 0?void 0:G.bind($);throw new Th(`"${g}" plugin is not implemented on ${_}`,ya.Unimplemented)}},F=$=>{let q;const L=(...G)=>{const J=N().then(oe=>{const le=H(oe,$);if(le){const K=le(...G);return q=K==null?void 0:K.remove,K}else throw new Th(`"${g}.${$}()" is not implemented on ${_}`,ya.Unimplemented)});return $==="addListener"&&(J.remove=async()=>q()),J};return L.toString=()=>`${$.toString()}() { [capacitor code] }`,Object.defineProperty(L,"name",{value:$,writable:!1,configurable:!1}),L},fe=F("addListener"),z=F("removeListener"),R=($,q)=>{const L=fe({eventName:$},q),G=async()=>{const oe=await L;z({eventName:$,callbackId:oe},q)},J=new Promise(oe=>L.then(()=>oe({remove:G})));return J.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await G()},J},ee=new Proxy({},{get($,q){switch(q){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return j?R:fe;case"removeListener":return z;default:return F(q)}}});return s[g]=ee,m.set(g,{name:g,proxy:ee,platforms:new Set([...Object.keys(x),...j?[_]:[]])}),ee};return r.convertFileSrc||(r.convertFileSrc=g=>g),r.getPlatform=l,r.handleError=d,r.isNativePlatform=u,r.isPluginAvailable=c,r.registerPlugin=y,r.Exception=Th,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},iE=e=>e.Capacitor=rE(e),Jn=iE(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ys=Jn.registerPlugin;class Id{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 u=this.windowListeners[t];u&&!u.registered&&this.addWindowListener(u),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 u=this.retainedEventArguments[t];u||(u=[]),u.push(r),this.retainedEventArguments[t]=u}return}l.forEach(u=>u(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 Jn.Exception(t,ya.Unimplemented)}unavailable(t="not available"){return new Jn.Exception(t,ya.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 U0=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),B0=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class sE extends Id{async getCookies(){const t=document.cookie,r={};return t.split(";").forEach(s=>{if(s.length<=0)return;let[l,u]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");l=B0(l).trim(),u=B0(u).trim(),r[l]=u}),r}async setCookie(t){try{const r=U0(t.key),s=U0(t.value),l=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",u=(t.path||"/").replace("path=",""),c=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${r}=${s||""}${l}; path=${u}; ${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)}}}ys("CapacitorCookies",{web:()=>new sE});const aE=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)}),lE=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(l=>l.toLocaleLowerCase()).reduce((l,u,c)=>(l[u]=e[t[c]],l),{})},oE=(e,t=!0)=>e?Object.entries(e).reduce((s,l)=>{const[u,c]=l;let f,d;return Array.isArray(c)?(d="",c.forEach(m=>{f=t?encodeURIComponent(m):m,d+=`${u}=${f}&`}),d.slice(0,-1)):(f=t?encodeURIComponent(c):c,d=`${u}=${f}`),`${s}&${d}`},"").substr(1):null,uE=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),l=lE(e.headers)["content-type"]||"";if(typeof e.data=="string")r.body=e.data;else if(l.includes("application/x-www-form-urlencoded")){const u=new URLSearchParams;for(const[c,f]of Object.entries(e.data||{}))u.set(c,f);r.body=u.toString()}else if(l.includes("multipart/form-data")||e.data instanceof FormData){const u=new FormData;if(e.data instanceof FormData)e.data.forEach((f,d)=>{u.append(d,f)});else for(const f of Object.keys(e.data))u.append(f,e.data[f]);r.body=u;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 cE extends Id{async request(t){const r=uE(t,t.webFetchExtra),s=oE(t.params,t.shouldEncodeUrlParams),l=s?`${t.url}?${s}`:t.url,u=await fetch(l,r),c=u.headers.get("content-type")||"";let{responseType:f="text"}=u.ok?t:{};c.includes("application/json")&&(f="json");let d,m;switch(f){case"arraybuffer":case"blob":m=await u.blob(),d=await aE(m);break;case"json":d=await u.json();break;case"document":case"text":default:d=await u.text()}const y={};return u.headers.forEach((g,x)=>{y[x]=g}),{data:d,headers:y,status:u.status,url:u.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"}))}}ys("CapacitorHttp",{web:()=>new cE});var P0;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(P0||(P0={}));var H0;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})(H0||(H0={}));class fE extends Id{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")}}ys("SystemBars",{web:()=>new fE});const hE="modulepreload",dE=function(e){return"/"+e},q0={},Fd=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=dE(m),m in q0)return;q0[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":hE,y||(x.as="script"),x.crossOrigin="",x.href=m,d&&x.setAttribute("nonce",d),document.head.appendChild(x),y)return new Promise((w,_)=>{x.addEventListener("load",w),x.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${m}`)))})}))}function u(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"&&u(f.reason);return t().catch(u)})},dd=ys("App",{web:()=>Fd(()=>import("./web-DVnCcdDQ.js"),[]).then(e=>new e.AppWeb)}),mE=ys("Network",{web:()=>Fd(()=>import("./web-Dnq4poOz.js"),[]).then(e=>new e.NetworkWeb)}),Bu=Jn.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 pE(e,t,r){return Lx("POST",e,t)}function gE(e,t){return Lx("GET",e,void 0)}const I0=Jn.isNativePlatform(),zx=A.createContext(null),yE=2e3,jh=6e3,bE=1500,xE=6e4;function vE({children:e,activeHost:t}){const[r,s]=A.useState(null),[l,u]=A.useState(!1),c=A.useRef(null),[f,d]=A.useState(!1),[m,y]=A.useState(!1),[g,x]=A.useState(!1),[w,_]=A.useState(!1),j=A.useRef(Ou()),D=A.useRef(new Set),N=A.useRef(0),H=!!t.directUrl,F=I0&&!H&&!!t.lanUrl&&w,fe=m||g?"disconnected":H?f?"direct":"connecting":l?F?"lan":"nats":"connecting",z=fe!=="connecting"&&fe!=="disconnected";A.useEffect(()=>{y(!1),x(!1)},[t.hostId,t.clientToken]),A.useEffect(()=>{if(!I0||H||!t.lanUrl){_(!1);return}let $=!1;const q=t.lanUrl,L=t.hostId;async function G(){console.log("[HOST/LAN] probing",q);try{const K=await fetch(`${q}/health`,{signal:AbortSignal.timeout(bE)});if($)return;if(!K.ok){console.log("[HOST/LAN] probe got non-ok:",K.status),_(!1);return}const U=await K.json(),W=U.hostId===L;W?console.log("[HOST/LAN] reachable"):console.log("[HOST/LAN] hostId mismatch — got:",U.hostId,"expected:",L),_(W)}catch(K){$||(console.log("[HOST/LAN] probe failed:",K instanceof Error?K.message:K),_(!1))}}G();const J=window.setInterval(G,xE),oe=dd.addListener("appStateChange",K=>{K.isActive&&G()}),le=mE.addListener("networkStatusChange",()=>G());return()=>{$=!0,clearInterval(J),oe.then(K=>K.remove()),le.then(K=>K.remove())}},[t.hostId,t.lanUrl,H]),A.useEffect(()=>{if(H){c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1));return}let $=!1,q=1e3;const L=3e4;async function G(){for(;!$;)try{const J=await fetch(`${Bu}/api/nats-credentials/${t.hostId}`);if($)return;if(J.status===401||J.status===403||J.status===404){console.error("[NATS] Host not found or rejected by relay:",J.status),x(!0);return}if(!J.ok)throw new Error(`credentials fetch ${J.status}`);const oe=await J.json();if(!oe.natsWsUrl){console.error("[NATS] Relay returned empty natsWsUrl — treating as terminal"),x(!0);return}if($)return;console.log("[NATS] Connecting to",oe.natsWsUrl);const le=await Dx({servers:oe.natsWsUrl,authenticator:Ex(oe.natsJwt,new TextEncoder().encode(oe.natsNkeySeed)),pingInterval:3e4,maxPingOut:2});if($){le.close().catch(()=>{});return}if(console.log("[NATS] Connected"),c.current=le,s(le),u(!0),q=1e3,await le.closed(),$)return;console.log("[NATS] Connection closed, will reconnect"),c.current=null,s(null),u(!1)}catch(J){if($)return;console.warn(`[NATS] Connect failed, retrying in ${q}ms:`,J),u(!1),await new Promise(oe=>setTimeout(oe,q)),q=Math.min(q*2,L)}}return G(),()=>{$=!0,c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1))}},[H,t]),A.useEffect(()=>{if(H)return;const $=dd.addListener("appStateChange",q=>{if(!q.isActive||!c.current)return;const L=c.current;Promise.race([L.flush(),new Promise((G,J)=>setTimeout(()=>J(new Error("ping timeout")),2e3))]).catch(()=>{console.log("[NATS] Resume probe failed — cycling conn"),L.close().catch(()=>{})})});return()=>{$.then(q=>q.remove())}},[H]),A.useEffect(()=>{if(!H){d(!1);return}const $=new AbortController;async function q(){var oe;const G=new AbortController,J=setTimeout(()=>G.abort(),yE);$.signal.addEventListener("abort",()=>G.abort());try{const le=await fetch(`${t.directUrl}/events`,{headers:{Authorization:`Bearer ${t.clientToken}`},signal:G.signal});return clearTimeout(J),le.ok?((oe=le.body)==null?void 0:oe.getReader())??null:null}catch{return clearTimeout(J),null}}async function L(G){d(!0),console.log("[HOST] SSE connected to",t.directUrl),N.current=Date.now();function J(){setTimeout(()=>{$.signal.aborted||Date.now()-N.current<jh||(console.log("[HOST] Heartbeat timeout — no data for",jh/1e3,"s"),$.abort(),d(!1),console.log("[HOST] Direct host unreachable"))},jh)}J();const oe=new TextDecoder;let le="";try{for(;;){const{done:K,value:U}=await G.read();if(K)break;le+=oe.decode(U,{stream:!0}),N.current=Date.now(),J();const W=le.split(`
87
+ ${f.stack}`),c.reject(m)):c.resolve(y))}});return d.requestSubject=t,this.protocol.publish(t,r,{reply:u,headers:s.headers}),c}else{const u=new xx(this.protocol.muxSubscriptions,t,s,l);this.protocol.request(u);try{this.publish(t,r,{reply:`${this.protocol.muxSubscriptions.baseInbox}${u.token}`,headers:s.headers})}catch(f){u.cancel(f)}const c=Promise.race([u.timer,u.deferred]);return c.catch(()=>{u.cancel()}),c}}flush(){return this.isClosed()?Promise.reject(Ne.errorForCode(ke.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(Ne.errorForCode(ke.ConnectionClosed)):this.isDraining()?Promise.reject(Ne.errorForCode(ke.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 sn;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 Bk(this,t);if(t.checkAPI!==!1)try{await r.getAccountInfo()}catch(s){const l=s;throw l.code===ke.NoResponders&&(l.code=ke.JetStreamNotEnabled),l}return r}jetstream(t={}){return new Hd(this,t)}getServerVersion(){const t=this.info;return t?ms(t.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw Ne.errorForCode(ke.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 Ik(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(Ne.errorForCode(ke.ConnectionClosed)):this.isDraining()?Promise.reject(Ne.errorForCode(ke.ConnectionDraining)):this.protocol.reconnect()}}class Ik{constructor(t){C(this,"nc");this.nc=t}add(t){try{return new Vl(this.nc,t).start()}catch(r){return Promise.reject(r)}}client(t,r){return new wk(this.nc,t,r)}}class Fk{constructor(t,r,s){C(this,"bucket");C(this,"sm");C(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(Uu)||"PUT"}get length(){const t=this.sm.header.get(kn.MessageSizeHdr)||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class $k{constructor(t,r,s){C(this,"bucket");C(this,"key");C(this,"sm");this.bucket=t,this.key=r,this.sm=s}get value(){return this.sm.data}get created(){return new Date(Ld(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var t;return((t=this.sm.headers)==null?void 0:t.get(Uu))||"PUT"}get delta(){return this.sm.info.pending}get length(){var r;const t=((r=this.sm.headers)==null?void 0:r.get(kn.MessageSizeHdr))||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Rx extends w2{constructor(r,s,l){super(r.nc,s,l);C(this,"js");C(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=ni(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const u=this.info;u.config.name=Pi.next(),u.ordered_consumer_sequence.delivery_seq=0,u.flow_control.heartbeat_count=0,u.flow_control.fc_count=0,u.flow_control.consumer_restarts++,u.deliver=s,u.config.deliver_subject=s,u.config.deliver_policy=Vt.StartSequence,u.config.opt_start_seq=r;const c={};c.stream_name=this.info.stream,c.config=u.config;const f=`${u.api.prefix}.CONSUMER.CREATE.${u.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 Ne(`unable to recreate ordered consumer ${u.stream} at seq ${r}`,ke.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(Ld(r))}_setupHbMonitoring(r,s=0){const l={cancelAfter:0,maxOut:2};s&&(l.cancelAfter=s);const u=this.sub,c=f=>{var y,g,x,w;const d=t2(409,`${or.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 _=((x=(g=this.info)==null?void 0:g.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(_+1),(w=this.monitor)==null||w.restart(),!1}return!u.noIterator};this.monitor=new Ud(r,c,l)}_checkHbOrderConsumer(r){const s=r.headers.get(kn.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const l=parseInt(r.headers.get(kn.LastConsumerSeqHdr),10),u=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,l!==u.delivery_seq&&this._resetOrderedConsumer(u.stream_seq+1),!1}_checkOrderedConsumer(r){const s=this.info.ordered_consumer_sequence,l=r.info.streamSequence,u=r.info.deliverySequence;return u!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=u,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}`,u=await r.api._request(l);return r.last=u,u}}class Yk extends Rx{constructor(t,r,s){super(t,r,s)}pull(t={batch:1}){const{stream:r,config:s,name:l}=this.sub.info,u=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(ht.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=zt(f));let d=0;if(t.idle_heartbeat&&t.idle_heartbeat>0&&(d=t.idle_heartbeat,c.idle_heartbeat=zt(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}.${u}`,g=this.sub.subject;m.nc.publish(y,m.jc.encode(c),{reply:g})}}}function Vk(e,t){return e?Jk(t):Gk(t)}function Gk(e){return(t,r)=>t?[t,null]:(t=ua(r),t?[t,null]:[null,Hl(r,e)])}function Jk(e){return(t,r)=>{if(t)return[t,null];const s=ua(r);return s!==null?[Mx(s),null]:[null,Hl(r,e)]}}function Mx(e){if(e!==null)switch(e.code){case ke.JetStream404NoMessages:case ke.JetStream408RequestTimeout:return null;case ke.JetStream409:return n2(e)?e:null;default:return e}return null}function Xk(e){e&&e.ack()}function Kk(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 Qk{constructor(t,r){C(this,"msg");C(this,"di");C(this,"didAck");C(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=Kk(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]===xl[0]&&t[1]===xl[1]&&t[2]===xl[2]&&t[3]===xl[3]}async ackAck(t){var s;t=t||{},t.timeout=t.timeout||this.timeout;const r=Ut();if(this.didAck)r.resolve(!1);else if(this.didAck=!0,this.msg.reply){const u=this.msg.publisher,c=!((s=u.options)!=null&&s.noAsyncTraces),f=new xx(u.muxSubscriptions,this.msg.reply,{timeout:t.timeout},c);u.request(f);try{u.publish(this.msg.reply,L0,{reply:`${u.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(L0)}nak(t){let r=Ok;t&&(r=Ou().encode(`-NAK ${JSON.stringify({delay:zt(t)})}`)),this.doAck(r)}working(){this.doAck(xl)}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=zt(r.expires));const l=vr().encode(s),u=ga.concat(Rk,Dk,l),c=t?{reply:t}:void 0;this.msg.respond(u,c)}term(t=""){let r=Mk;(t==null?void 0:t.length)>0&&(r=Ou().encode(`+TERM ${t}`)),this.doAck(r)}json(){return this.msg.json()}string(){return this.msg.string()}}const Zk="1.30.3",Wk="nats.ws";class eE{constructor(){C(this,"version");C(this,"lang");C(this,"closeError");C(this,"connected");C(this,"done");C(this,"socket");C(this,"options");C(this,"socketClosed");C(this,"encrypted");C(this,"peeked");C(this,"yields");C(this,"signal");C(this,"closedNotification");this.version=Zk,this.lang=Wk,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=Ut(),this.closedNotification=Ut()}async connect(t,r){const s=Ut();if(r.tls)return s.reject(new Ne("tls",ke.InvalidOption)),s;this.options=r;const l=t.src;if(r.wsFactory){const{socket:u,encrypted:c}=await r.wsFactory(t.src,r);this.socket=u,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=u=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(u.data)),this.peeked){this.signal.resolve();return}const c=ga.concat(...this.yields),f=A2(c);if(f!==""){const d=dk.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]);fk(m,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(m){s.reject(m);return}}},this.socket.onclose=u=>{if(this.isDiscarded())return;this.socketClosed=!0;let c;this.done||(u.wasClean||(c=new Error(u.reason)),this._closed(c))},this.socket.onerror=u=>{if(this.isDiscarded())return;const c=u,f=new Ne(c.message,ke.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 Sa(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=Ut())}}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 tE(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 u,c;const f=s.hostname,d=s.pathname,m=s.search||"";switch(l){case"http:":case"ws:":case"nats:":c=s.port||"80",u="ws:";break;case"https:":case"wss:":case"tls:":c=s.port||"443",u="wss:";break;default:c=s.port||t===!0?"443":"80",u=t===!0?"wss:":"ws:";break}return`${u}//${f}:${c}${d}${m}`}function Dx(e={}){return S2({defaultPort:443,urlParseFn:tE,factory:()=>new eE}),qd.connect(e)}/*! Capacitor: https://capacitorjs.com/ - MIT License */var ya;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(ya||(ya={}));class Th extends Error{constructor(t,r,s){super(t),this.message=t,this.code=r,this.data=s}}const nE=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"},rE=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},s=r.Plugins=r.Plugins||{},l=()=>t!==null?t.name:nE(e),u=()=>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(w=>w.name===g)},d=g=>e.console.error(g),m=new Map,y=(g,x={})=>{const w=m.get(g);if(w)return console.warn(`Capacitor plugin "${g}" already registered. Cannot register plugins twice.`),w.proxy;const _=l(),j=f(g);let D;const N=async()=>(!D&&_ in x?D=typeof x[_]=="function"?D=await x[_]():D=x[_]:t!==null&&!D&&"web"in x&&(D=typeof x.web=="function"?D=await x.web():D=x.web),D),H=($,q)=>{var L,G;if(j){const J=j==null?void 0:j.methods.find(oe=>q===oe.name);if(J)return J.rtype==="promise"?oe=>r.nativePromise(g,q.toString(),oe):(oe,le)=>r.nativeCallback(g,q.toString(),oe,le);if($)return(L=$[q])===null||L===void 0?void 0:L.bind($)}else{if($)return(G=$[q])===null||G===void 0?void 0:G.bind($);throw new Th(`"${g}" plugin is not implemented on ${_}`,ya.Unimplemented)}},F=$=>{let q;const L=(...G)=>{const J=N().then(oe=>{const le=H(oe,$);if(le){const K=le(...G);return q=K==null?void 0:K.remove,K}else throw new Th(`"${g}.${$}()" is not implemented on ${_}`,ya.Unimplemented)});return $==="addListener"&&(J.remove=async()=>q()),J};return L.toString=()=>`${$.toString()}() { [capacitor code] }`,Object.defineProperty(L,"name",{value:$,writable:!1,configurable:!1}),L},fe=F("addListener"),z=F("removeListener"),R=($,q)=>{const L=fe({eventName:$},q),G=async()=>{const oe=await L;z({eventName:$,callbackId:oe},q)},J=new Promise(oe=>L.then(()=>oe({remove:G})));return J.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await G()},J},ee=new Proxy({},{get($,q){switch(q){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return j?R:fe;case"removeListener":return z;default:return F(q)}}});return s[g]=ee,m.set(g,{name:g,proxy:ee,platforms:new Set([...Object.keys(x),...j?[_]:[]])}),ee};return r.convertFileSrc||(r.convertFileSrc=g=>g),r.getPlatform=l,r.handleError=d,r.isNativePlatform=u,r.isPluginAvailable=c,r.registerPlugin=y,r.Exception=Th,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},iE=e=>e.Capacitor=rE(e),Jn=iE(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ys=Jn.registerPlugin;class Id{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 u=this.windowListeners[t];u&&!u.registered&&this.addWindowListener(u),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 u=this.retainedEventArguments[t];u||(u=[]),u.push(r),this.retainedEventArguments[t]=u}return}l.forEach(u=>u(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 Jn.Exception(t,ya.Unimplemented)}unavailable(t="not available"){return new Jn.Exception(t,ya.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 U0=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),B0=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class sE extends Id{async getCookies(){const t=document.cookie,r={};return t.split(";").forEach(s=>{if(s.length<=0)return;let[l,u]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");l=B0(l).trim(),u=B0(u).trim(),r[l]=u}),r}async setCookie(t){try{const r=U0(t.key),s=U0(t.value),l=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",u=(t.path||"/").replace("path=",""),c=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${r}=${s||""}${l}; path=${u}; ${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)}}}ys("CapacitorCookies",{web:()=>new sE});const aE=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)}),lE=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(l=>l.toLocaleLowerCase()).reduce((l,u,c)=>(l[u]=e[t[c]],l),{})},oE=(e,t=!0)=>e?Object.entries(e).reduce((s,l)=>{const[u,c]=l;let f,d;return Array.isArray(c)?(d="",c.forEach(m=>{f=t?encodeURIComponent(m):m,d+=`${u}=${f}&`}),d.slice(0,-1)):(f=t?encodeURIComponent(c):c,d=`${u}=${f}`),`${s}&${d}`},"").substr(1):null,uE=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),l=lE(e.headers)["content-type"]||"";if(typeof e.data=="string")r.body=e.data;else if(l.includes("application/x-www-form-urlencoded")){const u=new URLSearchParams;for(const[c,f]of Object.entries(e.data||{}))u.set(c,f);r.body=u.toString()}else if(l.includes("multipart/form-data")||e.data instanceof FormData){const u=new FormData;if(e.data instanceof FormData)e.data.forEach((f,d)=>{u.append(d,f)});else for(const f of Object.keys(e.data))u.append(f,e.data[f]);r.body=u;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 cE extends Id{async request(t){const r=uE(t,t.webFetchExtra),s=oE(t.params,t.shouldEncodeUrlParams),l=s?`${t.url}?${s}`:t.url,u=await fetch(l,r),c=u.headers.get("content-type")||"";let{responseType:f="text"}=u.ok?t:{};c.includes("application/json")&&(f="json");let d,m;switch(f){case"arraybuffer":case"blob":m=await u.blob(),d=await aE(m);break;case"json":d=await u.json();break;case"document":case"text":default:d=await u.text()}const y={};return u.headers.forEach((g,x)=>{y[x]=g}),{data:d,headers:y,status:u.status,url:u.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"}))}}ys("CapacitorHttp",{web:()=>new cE});var P0;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(P0||(P0={}));var H0;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})(H0||(H0={}));class fE extends Id{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")}}ys("SystemBars",{web:()=>new fE});const hE="modulepreload",dE=function(e){return"/"+e},q0={},Fd=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=dE(m),m in q0)return;q0[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":hE,y||(x.as="script"),x.crossOrigin="",x.href=m,d&&x.setAttribute("nonce",d),document.head.appendChild(x),y)return new Promise((w,_)=>{x.addEventListener("load",w),x.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${m}`)))})}))}function u(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"&&u(f.reason);return t().catch(u)})},dd=ys("App",{web:()=>Fd(()=>import("./web-BQQlSLPT.js"),[]).then(e=>new e.AppWeb)}),mE=ys("Network",{web:()=>Fd(()=>import("./web-CpqzX7Jk.js"),[]).then(e=>new e.NetworkWeb)}),Bu=Jn.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 pE(e,t,r){return Lx("POST",e,t)}function gE(e,t){return Lx("GET",e,void 0)}const I0=Jn.isNativePlatform(),zx=A.createContext(null),yE=2e3,jh=6e3,bE=1500,xE=6e4;function vE({children:e,activeHost:t}){const[r,s]=A.useState(null),[l,u]=A.useState(!1),c=A.useRef(null),[f,d]=A.useState(!1),[m,y]=A.useState(!1),[g,x]=A.useState(!1),[w,_]=A.useState(!1),j=A.useRef(Ou()),D=A.useRef(new Set),N=A.useRef(0),H=!!t.directUrl,F=I0&&!H&&!!t.lanUrl&&w,fe=m||g?"disconnected":H?f?"direct":"connecting":l?F?"lan":"nats":"connecting",z=fe!=="connecting"&&fe!=="disconnected";A.useEffect(()=>{y(!1),x(!1)},[t.hostId,t.clientToken]),A.useEffect(()=>{if(!I0||H||!t.lanUrl){_(!1);return}let $=!1;const q=t.lanUrl,L=t.hostId;async function G(){console.log("[HOST/LAN] probing",q);try{const K=await fetch(`${q}/health`,{signal:AbortSignal.timeout(bE)});if($)return;if(!K.ok){console.log("[HOST/LAN] probe got non-ok:",K.status),_(!1);return}const U=await K.json(),W=U.hostId===L;W?console.log("[HOST/LAN] reachable"):console.log("[HOST/LAN] hostId mismatch — got:",U.hostId,"expected:",L),_(W)}catch(K){$||(console.log("[HOST/LAN] probe failed:",K instanceof Error?K.message:K),_(!1))}}G();const J=window.setInterval(G,xE),oe=dd.addListener("appStateChange",K=>{K.isActive&&G()}),le=mE.addListener("networkStatusChange",()=>G());return()=>{$=!0,clearInterval(J),oe.then(K=>K.remove()),le.then(K=>K.remove())}},[t.hostId,t.lanUrl,H]),A.useEffect(()=>{if(H){c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1));return}let $=!1,q=1e3;const L=3e4;async function G(){for(;!$;)try{const J=await fetch(`${Bu}/api/nats-credentials/${t.hostId}`);if($)return;if(J.status===401||J.status===403||J.status===404){console.error("[NATS] Host not found or rejected by relay:",J.status),x(!0);return}if(!J.ok)throw new Error(`credentials fetch ${J.status}`);const oe=await J.json();if(!oe.natsWsUrl){console.error("[NATS] Relay returned empty natsWsUrl — treating as terminal"),x(!0);return}if($)return;console.log("[NATS] Connecting to",oe.natsWsUrl);const le=await Dx({servers:oe.natsWsUrl,authenticator:Ex(oe.natsJwt,new TextEncoder().encode(oe.natsNkeySeed)),pingInterval:3e4,maxPingOut:2});if($){le.close().catch(()=>{});return}if(console.log("[NATS] Connected"),c.current=le,s(le),u(!0),q=1e3,await le.closed(),$)return;console.log("[NATS] Connection closed, will reconnect"),c.current=null,s(null),u(!1)}catch(J){if($)return;console.warn(`[NATS] Connect failed, retrying in ${q}ms:`,J),u(!1),await new Promise(oe=>setTimeout(oe,q)),q=Math.min(q*2,L)}}return G(),()=>{$=!0,c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1))}},[H,t]),A.useEffect(()=>{if(H)return;const $=dd.addListener("appStateChange",q=>{if(!q.isActive||!c.current)return;const L=c.current;Promise.race([L.flush(),new Promise((G,J)=>setTimeout(()=>J(new Error("ping timeout")),2e3))]).catch(()=>{console.log("[NATS] Resume probe failed — cycling conn"),L.close().catch(()=>{})})});return()=>{$.then(q=>q.remove())}},[H]),A.useEffect(()=>{if(!H){d(!1);return}const $=new AbortController;async function q(){var oe;const G=new AbortController,J=setTimeout(()=>G.abort(),yE);$.signal.addEventListener("abort",()=>G.abort());try{const le=await fetch(`${t.directUrl}/events`,{headers:{Authorization:`Bearer ${t.clientToken}`},signal:G.signal});return clearTimeout(J),le.ok?((oe=le.body)==null?void 0:oe.getReader())??null:null}catch{return clearTimeout(J),null}}async function L(G){d(!0),console.log("[HOST] SSE connected to",t.directUrl),N.current=Date.now();function J(){setTimeout(()=>{$.signal.aborted||Date.now()-N.current<jh||(console.log("[HOST] Heartbeat timeout — no data for",jh/1e3,"s"),$.abort(),d(!1),console.log("[HOST] Direct host unreachable"))},jh)}J();const oe=new TextDecoder;let le="";try{for(;;){const{done:K,value:U}=await G.read();if(K)break;le+=oe.decode(U,{stream:!0}),N.current=Date.now(),J();const W=le.split(`
88
88
  `);le=W.pop()??"";for(const ue of W)if(ue.startsWith("data: ")){const we=ue.slice(6);try{const M=JSON.parse(we);if(M.task_id&&M.event_type){const P=`host-event.${t.hostId}.${M.task_id}`;for(const te of D.current)te({subject:P,data:j.current.encode(we)})}}catch{}}}}catch{}}return(async()=>{const G=await q();G&&await L(G)})(),()=>{$.abort(),d(!1)}},[t,H]);const R=A.useCallback(async($,q,L)=>{function G(le){le&&typeof le=="object"&&le.error==="Unauthorized"&&y(!0)}async function J(le,K){console.log(`[HOST/${K}] → ${$}`,q??"");const U=await fetch(`${le}/rpc/${$}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.clientToken}`},body:q!=null?JSON.stringify(q):void 0,signal:L!=null&&L.timeout?AbortSignal.timeout(L.timeout):void 0});if(U.status===401)throw y(!0),new Error("Unauthorized");const W=await U.json();return G(W),console.log(`[HOST/${K}] ← ${$}`,W),W}async function oe(){if(!c.current)throw new Error("Not connected");const le=`host.${t.hostId}.rpc.${$}`,K={...q??{},clientToken:t.clientToken},U=j.current.encode(JSON.stringify(K));console.log(`[HOST/NATS] → ${$}`,q??"");const W=await c.current.request(le,U,{timeout:(L==null?void 0:L.timeout)??1e4}),ue=JSON.parse(j.current.decode(W.data));return G(ue),console.log(`[HOST/NATS] ← ${$}`,ue),ue}if(H)return J(t.directUrl,"HTTP");if(F&&t.lanUrl)try{return await J(t.lanUrl,"LAN")}catch(le){if(le instanceof Error&&le.message==="Unauthorized")throw le;console.log("[HOST/LAN] failed, falling back to NATS:",le),_(!1)}return oe()},[t,H,F]),ee=A.useCallback(($,q)=>{if(H)return D.current.add(q),()=>{D.current.delete(q)};if(c.current){const L=c.current.subscribe(`host-event.${$}.>`);let G=!1;return(async()=>{try{for await(const J of L){if(G)break;q({subject:J.subject,data:J.data})}}catch{}})(),()=>{G=!0,L.unsubscribe()}}return()=>{}},[t,H]);return b.jsx(zx.Provider,{value:{connected:z,mode:fe,nc:r,request:R,subscribeEvents:ee,activeHost:t,unauthorized:m},children:e})}function si(){const e=A.useContext(zx);if(!e)throw new Error("useHostConnection must be used within HostConnectionProvider");return e}const dn=Jn.isNativePlatform()?ys("Device"):null;function wE(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 $d(){const{activeHost:e}=si(),t=e.timezone;return A.useCallback(r=>wE(r,t),[t])}function SE(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(u=>u.type===s))==null?void 0:l.value)??""};return{date:`${r("year")}-${r("month")}-${r("day")}`,time:`${r("hour")}:${r("minute")}`}}function _E(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(u=>u.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 kE(e,t,r){return new Date(Date.UTC(e,t-1,r)).getUTCDay()}function EE(e,t){return new Date(Date.UTC(e,t,0)).getUTCDate()}function F0(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 Ol(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 CE(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")},u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")%24,l("minute"),l("second"));return r-(u-r)}function AE(e,t){const r=e.split(" ");if(r.length!==5)return null;const[s,l,u,,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=F0({...t,hour:d,minute:f},g);if(kE(x.year,x.month,x.day)===y&&Ol(x,t)>0)return x}return null}if(u!=="*"){const y=Number(u);if(Number.isNaN(y))return null;let g=t.year,x=t.month;for(let w=0;w<24;w++){if(y<=EE(g,x)){const _={year:g,month:x,day:y,hour:d,minute:f};if(Ol(_,t)>0)return _}x++,x>12&&(x=1,g++)}return null}const m={...t,hour:d,minute:f};return Ol(m,t)>0?m:F0(m,1)}function TE(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 jE(e,t,r){if(!e||!t||t.length===0||e==="on_new_notification"||e==="on_new_sms")return null;const s=_E(r),l=[];for(const u of t)if(e==="specific_times"){const c=TE(u);c&&Ol(c,s)>0&&l.push(c)}else{const c=AE(u,s);c&&l.push(c)}return l.length===0?null:(l.sort(Ol),CE(l[0],r))}const Ux={};function NE(e){for(const t of e)Ux[t.key]=t.label}function md(e){return Ux[e]??e}const OE=()=>window.matchMedia("(max-width: 600px)").matches;function RE({task:e,lastEvent:t,onEdit:r,onDelete:s,onViewRun:l}){var le;const{request:u,activeHost:c}=si(),f=$d(),d=c.timezone,[m,y]=A.useState(!1),[g,x]=A.useState(!1),[w,_]=A.useState(!1),j=A.useRef(null),D=(t==null?void 0:t.running_state)==="started",N=(((le=e.schedule_values)==null?void 0:le.length)??0)>0,H=e.schedule_type==="on_new_notification"||e.schedule_type==="on_new_sms",fe=!!e.schedule_enabled&&!!e.schedule_type&&(N||H)?D?"var(--color-success)":(t==null?void 0:t.running_state)==="failed"?"var(--color-error)":"var(--color-success)":"var(--color-text-secondary)";A.useEffect(()=>{if(!g)return;function K(U){j.current&&!j.current.contains(U.target)&&x(!1)}return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[g]);function z(){OE()?_(!0):x(K=>!K)}function R(){x(!1),_(!1)}async function ee(){if(R(),!!confirm("Abort this task?")){y(!0);try{await u("task.abort",{id:e.id})}catch(K){console.error("Abort failed:",K)}finally{y(!1)}}}async function $(){R();try{const K=await u("task.run",{id:e.id});l(e.id,K.run_id)}catch(K){console.error("Run failed:",K)}}async function q(){if(R(),!!confirm("Delete this task? Results and reports will be kept."))try{await u("task.delete",{id:e.id}),s(e.id)}catch(K){console.error("Delete failed:",K)}}const L={started:"Started",finished:"Finished",aborted:"Aborted",failed:"Failed"};function G(){if(e.schedule_type==="on_new_notification")return"On new notification";if(e.schedule_type==="on_new_sms")return"On new SMS";const K=jE(e.schedule_type,e.schedule_values,d);return K===null?"No upcoming runs":`Next: ${f(K)}`}const J=G(),oe=b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:()=>{R(),r(e)},children:[b.jsx("span",{className:"menu-icon",children:"✎"}),"Edit"]}),b.jsxs("button",{onClick:()=>{R(),l(e.id)},children:[b.jsx("span",{className:"menu-icon",children:"📄"}),"View All Runs"]}),D?b.jsxs("button",{className:"menu-item-danger",onClick:ee,disabled:m,children:[b.jsx("span",{className:"menu-icon",children:"◼"}),"Abort"]}):b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:$,children:[b.jsx("span",{className:"menu-icon",children:"▶"}),"Run Now"]}),b.jsxs("button",{className:"menu-item-danger",onClick:q,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,"latest"),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:fe}}),b.jsx("h3",{className:"task-card-name",children:e.name||e.user_prompt})]}),b.jsx("div",{className:"task-card-actions",onClick:K=>K.stopPropagation(),children:b.jsxs("div",{className:"task-card-menu",ref:j,children:[b.jsx("button",{className:"task-card-menu-btn",onClick:z,"aria-label":"Task actions",children:"⋮"}),g&&b.jsx("div",{className:"task-card-menu-dropdown",children:oe})]})})]}),b.jsxs("div",{className:"task-card-meta",children:[e.agent&&b.jsx("span",{className:"task-card-agent",children:md(e.agent)}),t&&L[t.running_state]&&b.jsxs("span",{className:"task-card-last-event",children:[L[t.running_state]," ",f(t.time_stamp)]}),e.schedule_type&&(N||H)&&b.jsx("span",{className:"task-card-triggers",children:e.schedule_enabled?J:"Schedule disabled"})]})]}),w&&ds.createPortal(b.jsx("div",{className:"bottom-sheet-overlay",onClick:()=>_(!1),children:b.jsxs("div",{className:"bottom-sheet",onClick:K=>K.stopPropagation(),children:[b.jsx("div",{className:"bottom-sheet-handle"}),b.jsx("div",{className:"bottom-sheet-title",children:e.name||e.user_prompt}),b.jsx("div",{className:"bottom-sheet-actions",children:oe})]})}),document.body)]})}function ME({permissions:e}){return b.jsxs("div",{className:"permissions-dialog",children:[b.jsx("h2",{children:"Granted Permissions"}),b.jsx("div",{className:"permissions-dialog-scroll",children:e&&e.length>0?b.jsx("div",{className:"permissions-section",children:b.jsx("ul",{className:"permissions-list",children:e.map((t,r)=>b.jsxs("li",{className:"permission-item",children:[b.jsx("span",{className:"permission-tool",children:t.name}),b.jsx("span",{className:"permission-desc",children:t.description})]},r))})}):b.jsx("p",{className:"permissions-empty",children:"No permissions have been granted for this task."})}),b.jsx("div",{className:"permissions-dialog-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>history.back(),children:"Back"})})]})}const ra=[];function DE(){const e=ra.pop();e&&(e.pushed.current=!1,e.close())}let $0=!1;function LE(){$0||($0=!0,window.addEventListener("popstate",DE))}function pd(e,t){const r=A.useRef(!1),s=A.useRef(t);s.current=t;const l=A.useCallback(()=>s.current(),[]),u=A.useRef({close:l,pushed:r});u.current.close=l,A.useEffect(()=>{if(e&&!r.current)LE(),history.pushState({modal:!0},""),ra.push(u.current),r.current=!0;else if(!e&&r.current){r.current=!1;const c=ra.indexOf(u.current);c!==-1&&ra.splice(c,1),history.back()}},[e,l]),A.useEffect(()=>{const c=u.current;return()=>{if(r.current){r.current=!1;const f=ra.indexOf(c);f!==-1&&ra.splice(f,1),history.back()}}},[])}const zE=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],UE=["specific_times","hourly","daily","weekly","monthly"];function pu(e){return UE.includes(e)}function BE(e){return e==="on_new_notification"||e==="on_new_sms"}function ti(e="daily"){return{schedule:e,time:"00:00",dayOfWeek:"1",dayOfMonth:"1",onceDate:"",onceTime:"00:00"}}function PE(e){const t=e.split(" ");if(t.length!==5)return ti();const[r,s,l,,u]=t;if(s==="*")return ti("hourly");const c=`${s.padStart(2,"0")}:${r.padStart(2,"0")}`;return u!=="*"?{...ti("weekly"),time:c,dayOfWeek:u}:l!=="*"?{...ti("monthly"),time:c,dayOfMonth:l}:{...ti("daily"),time:c}}function Bx(e,t){if(e==="specific_times"){const[r,s]=t.split("T");return{...ti("specific_times"),onceDate:r??"",onceTime:(s??"09:00").slice(0,5)}}return PE(t)}function HE(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 qE(e){return e.schedule==="specific_times"?e.onceDate?`${e.onceDate}T${e.onceTime}`:null:HE(e)}function Nh(e){return e==="specific_times"?"specific_times":e==="on_new_notification"?"on_new_notification":e==="on_new_sms"?"on_new_sms":"crons"}function Oh(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 IE({initial:e,agents:t,hostPlatform:r,isNotificationListener:s,onSaved:l,onRun:u,onCancel:c}){var Je;const{request:f,activeHost:d}=si(),{setHostLastAgent:m}=qi(),y=()=>{var Le;const pe=d.lastAgent,Pe=t.map(Ct=>Ct.key);return pe&&Pe.includes(pe)?pe:((Le=t[0])==null?void 0:Le.key)??""},[g,x]=A.useState((e==null?void 0:e.user_prompt)??""),[w,_]=A.useState((e==null?void 0:e.agent)??y()),j=!!((Je=e==null?void 0:e.permissions)!=null&&Je.length)&&w===(e==null?void 0:e.agent),[D,N]=A.useState(!1),H=A.useCallback(()=>N(!1),[]);pd(D,H);const[F,fe]=A.useState(null),[z,R]=A.useState(()=>Oh(e)),[ee,$]=A.useState(()=>{const pe=e==null?void 0:e.schedule_type,Pe=e==null?void 0:e.schedule_values;if(Pe&&(pe==="crons"||pe==="specific_times"))return Pe.map(Ct=>Bx(pe,Ct));const Le=Oh(e);return pu(Le)?[ti(Le)]:[]}),[q,L]=A.useState((e==null?void 0:e.requires_confirmation)??!1),[G,J]=A.useState(e!=null&&e.schedule_type?e.schedule_enabled??!0:!0),[oe,le]=A.useState((e==null?void 0:e.yolo_mode)??!1),[K,U]=A.useState((e==null?void 0:e.foreground_mode)??!1),[W,ue]=A.useState((e==null?void 0:e.command)??""),[we,M]=A.useState(!1),P=(e==null?void 0:e.schedule_type)==="on_new_notification"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[te,S]=A.useState(P),[xe,Ae]=A.useState([]),[ve,Ue]=A.useState(!1),[Ve,Te]=A.useState(!1),[et,Pt]=A.useState(""),Gt=A.useCallback(()=>Te(!1),[]);pd(Ve,Gt),A.useEffect(()=>{if(z!=="on_new_notification"||!s||!Jn.isNativePlatform()||!dn)return;let pe=!1;return Ue(!0),dn.getInstalledApps().then(({apps:Pe})=>{if(pe)return;const Le="com.palmier.app",Ct=Pe.filter(Dt=>Dt.packageName!==Le).sort((Dt,bn)=>(Dt.appName||Dt.packageName).localeCompare(bn.appName||bn.packageName));Ae(Ct)}).catch(()=>{}).finally(()=>{pe||Ue(!1)}),()=>{pe=!0}},[z,s]);const Ft=(e==null?void 0:e.schedule_type)==="on_new_sms"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[De,ot]=A.useState(Ft),tt=A.useRef(null),vt=pu(z),ft=z==="command",gn=BE(z),an=t.find(pe=>pe.key===w),Wt=!!(an!=null&&an.supportsYolo);A.useEffect(()=>{!Wt&&oe&&le(!1)},[Wt,oe]);const yn=!!e,Kn=Oh(e),pt=!yn||g!==((e==null?void 0:e.user_prompt)??"")||w!==((e==null?void 0:e.agent)??"")||z!==Kn||q!==((e==null?void 0:e.requires_confirmation)??!1)||G!==(e!=null&&e.schedule_type?e.schedule_enabled??!0:!0)||oe!==((e==null?void 0:e.yolo_mode)??!1)||K!==((e==null?void 0:e.foreground_mode)??!1)||ft&&W!==((e==null?void 0:e.command)??"")||vt&&(JSON.stringify(Fe())!==JSON.stringify((e==null?void 0:e.schedule_values)??[])||Nh(z)!==((e==null?void 0:e.schedule_type)??void 0))||gn&&z!==(e==null?void 0:e.schedule_type)||z==="on_new_notification"&&te.trim()!==P.trim()||z==="on_new_sms"&&De.trim()!==Ft.trim(),je=SE(d.timezone),Q=vt&&ee.some(pe=>pe.schedule==="specific_times"&&(!pe.onceDate||pe.onceDate<je.date||pe.onceDate===je.date&&(pe.onceTime??"")<=je.time)),he=pt&&!!g.trim()&&!Q&&(!ft||!!W.trim())&&(!vt||ee.length>0);function _e(pe,Pe){$(Le=>Le.map((Ct,Dt)=>Dt===pe?{...Ct,...Pe}:Ct))}function Oe(pe){$(Pe=>Pe.filter((Le,Ct)=>Ct!==pe))}function Ie(){pu(z)&&$(pe=>[...pe,pe.length>0?{...pe[pe.length-1]}:ti(z)])}function Ke(pe){R(pe),pu(pe)?$([ti(pe)]):($([]),L(!1)),pe==="command"?setTimeout(()=>{var Pe;return(Pe=tt.current)==null?void 0:Pe.focus()},0):ue(""),pe!=="on_new_notification"&&S(P),pe!=="on_new_sms"&&ot(Ft)}function Fe(){return ee.flatMap(pe=>{const Pe=qE(pe);return Pe?[Pe]:[]})}function Ge(){return oe?confirm(`Yolo mode is enabled. The agent will auto-approve all tool calls — it can read, write, delete files, run arbitrary commands, and access the network without asking for permission.
89
89
 
90
- Are you sure you want to continue?`):!0}async function $e(){M(!0),fe(null);try{const pe=vt?Fe():z==="on_new_notification"&&te.trim()?[te.trim()]:z==="on_new_sms"&&De.trim()?[De.trim()]:[],Pe=vt||gn?Nh(z):null,Le={user_prompt:g,agent:w,schedule_type:Pe,schedule_values:pe.length>0?pe:null,schedule_enabled:z==="ondemand"?!0:G,requires_confirmation:vt?q:!1,yolo_mode:oe,foreground_mode:K,command:ft?W:""};yn&&(Le.id=e.id);const Dt=await f(yn?"task.update":"task.create",Le,{timeout:45e3});if(Dt.error){fe(Dt.error);return}if(yn||m(d.hostId,w),ft&&!yn){l(Dt);try{const bn=await f("task.run",{id:Dt.id});bn.run_id?u(Dt.id,bn.run_id):bn.error||u(Dt.id)}catch{}return}l(Dt)}catch(pe){fe(pe instanceof Error?pe.message:String(pe))}finally{M(!1)}}const Qe=yn?"Save":ft?"Run":(vt||gn)&&G?"Schedule":"Save";return b.jsxs("div",{className:"task-form-overlay",children:[b.jsx("div",{className:"task-form",children:D?b.jsx(ME,{permissions:e==null?void 0:e.permissions}):b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"task-form-header",children:b.jsx("h2",{children:e?"Edit Task":"New Task"})}),F&&b.jsx("div",{className:"form-error",children:F}),b.jsx("textarea",{autoFocus:!e,className:"form-textarea",value:g,onChange:pe=>x(pe.target.value),placeholder:ft?"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:we}),b.jsxs("div",{className:"plan-actions",children:[b.jsxs("div",{className:"agent-picker-section-inline",children:[b.jsx("span",{className:"agent-picker-label",children:"Run with"}),b.jsx("select",{className:"form-select form-select-sm",value:w,onChange:pe=>_(pe.target.value),disabled:we,children:t.map(pe=>b.jsx("option",{value:pe.key,children:pe.label},pe.key))})]}),Wt&&b.jsxs("label",{className:"yolo-inline",style:{marginLeft:"auto"},children:[b.jsx("input",{type:"checkbox",checked:oe,onChange:pe=>le(pe.target.checked),disabled:we}),"Yolo"]}),Wt&&oe&&b.jsx("p",{className:"yolo-warning",children:"The agent will auto-approve all tool calls without asking for permission."}),j&&b.jsx("div",{className:"granted-permissions-row",children:b.jsx("button",{className:"btn btn-link",onClick:()=>N(!0),children:"Granted Permissions"})})]}),b.jsx("div",{className:"toggles-group",children:b.jsxs("div",{className:"schedule-section",children:[b.jsxs("h3",{className:"schedule-section-title",children:["Schedule ",b.jsx("span",{className:"schedule-section-hint",children:"based on host time"})]}),b.jsxs("select",{className:"form-select",value:z,onChange:pe=>Ke(pe.target.value),disabled:we,children:[b.jsx("option",{value:"ondemand",children:"On 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:"Command-triggered"})]}),gn&&b.jsxs("div",{className:"schedule-reactive",children:[b.jsxs("p",{className:"command-help-text",children:[z==="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 ",z==="on_new_notification"?"notification":"SMS","”."]}),z==="on_new_notification"&&(()=>{const pe=xe.find(Le=>Le.packageName===te),Pe=(pe==null?void 0:pe.appName)||te;return b.jsxs(b.Fragment,{children:[s?te.trim()?b.jsxs("div",{className:"app-filter-selected",children:[b.jsx("span",{className:"app-filter-selected-name",children:Pe}),(pe==null?void 0:pe.appName)&&b.jsx("span",{className:"app-filter-selected-pkg",children:pe.packageName}),b.jsx("button",{type:"button",className:"app-filter-selected-clear",onClick:()=>S(""),"aria-label":"Clear app filter",disabled:we,children:"✕"})]}):b.jsx("button",{type:"button",className:"btn btn-link app-filter-trigger",onClick:()=>{Pt(""),Te(!0)},disabled:we,children:"Select app"}):b.jsx("input",{className:"form-input",type:"text",value:te,onChange:Le=>S(Le.target.value),placeholder:"App (optional), e.g. com.google.android.gm",disabled:we}),b.jsx("p",{className:"command-help-text app-filter-help",children:te.trim()?`Only notifications from ${Pe} will trigger this task.`:"Every notification from your device triggers this task."})]})})(),z==="on_new_sms"&&b.jsxs(b.Fragment,{children:[b.jsx("input",{className:"form-input",type:"text",value:De,onChange:pe=>ot(pe.target.value),placeholder:"From (optional), e.g. +1 555-1234)",disabled:we}),b.jsx("p",{className:"command-help-text app-filter-help",children:De.trim()?`Only SMS from ${De.trim()} will trigger this task. Formatting (spaces, dashes, parens) is ignored.`:"Every SMS that arrives on your device triggers this task."})]})]}),ft&&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:tt,className:"form-input form-input-mono",type:"text",value:W,onChange:pe=>ue(pe.target.value),placeholder:"gws gmail +watch --project my-project",disabled:we})]}),vt&&z!=="hourly"&&b.jsxs(b.Fragment,{children:[ee.map((pe,Pe)=>b.jsxs("div",{className:"trigger-row-card",children:[b.jsxs("div",{className:"trigger-row-content",children:[z==="daily"&&b.jsx("input",{className:"form-input",type:"time",value:pe.time,onChange:Le=>_e(Pe,{time:Le.target.value})}),z==="weekly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:pe.dayOfWeek,onChange:Le=>_e(Pe,{dayOfWeek:Le.target.value}),children:zE.map((Le,Ct)=>b.jsx("option",{value:String(Ct),children:Le},Ct))}),b.jsx("input",{className:"form-input",type:"time",value:pe.time,onChange:Le=>_e(Pe,{time:Le.target.value})})]}),z==="monthly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:pe.dayOfMonth,onChange:Le=>_e(Pe,{dayOfMonth:Le.target.value}),children:Array.from({length:28},(Le,Ct)=>Ct+1).map(Le=>b.jsxs("option",{value:String(Le),children:["Day ",Le]},Le))}),b.jsx("input",{className:"form-input",type:"time",value:pe.time,onChange:Le=>_e(Pe,{time:Le.target.value})})]}),z==="specific_times"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("input",{className:"form-input",type:"date",value:pe.onceDate,min:je.date,onChange:Le=>_e(Pe,{onceDate:Le.target.value})}),b.jsx("input",{className:"form-input",type:"time",value:pe.onceTime,min:pe.onceDate===je.date?je.time:void 0,onChange:Le=>_e(Pe,{onceTime:Le.target.value})})]})]}),ee.length>1&&b.jsx("button",{className:"trigger-remove-btn",onClick:()=>Oe(Pe),title:"Remove trigger",children:"×"})]},Pe)),b.jsx("button",{className:"trigger-add-btn",onClick:Ie,children:"+ Add"})]}),r==="win32"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:K,onChange:pe=>U(pe.target.checked),disabled:we}),"Run in the foreground (host must login to Windows)"]}),vt&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:q,onChange:pe=>L(pe.target.checked),disabled:we}),"Confirm before each run"]}),z!=="ondemand"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:G,onChange:pe=>J(pe.target.checked),disabled:we}),"Enabled"]})]})}),!oe&&an&&!an.supportsPermissions&&b.jsxs("div",{className:"form-warning",children:["Palmier does not support runtime permission granting for ",an.label,". The task may fail if required permissions are not pre-configured."]}),b.jsxs("div",{className:"form-actions",children:[b.jsxs("button",{className:"btn btn-primary",onClick:()=>Ge()&&$e(),disabled:!he||we,children:[we&&b.jsx("span",{className:"btn-spinner"}),Qe]}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{pt&&g.trim()&&!confirm("You have unsaved changes. Discard?")||c()},style:{marginLeft:"auto"},children:"Cancel"})]})]})}),Ve&&(()=>{const pe=et.trim().toLowerCase(),Pe=pe?xe.filter(Le=>Le.packageName.toLowerCase().includes(pe)||Le.appName.toLowerCase().includes(pe)):xe;return b.jsx("div",{className:"app-filter-overlay",onClick:Gt,children:b.jsxs("div",{className:"app-filter-dialog",onClick:Le=>Le.stopPropagation(),children:[b.jsxs("div",{className:"app-filter-header",children:[b.jsx("h2",{children:"Select app"}),b.jsx("button",{className:"app-filter-close",onClick:Gt,"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:et,onChange:Le=>Pt(Le.target.value),onKeyDown:Le=>{Le.key==="Enter"&&et.trim()&&(S(et.trim()),Gt())},placeholder:"Search or type a package name",autoFocus:!0}),b.jsxs("ul",{className:"app-filter-list",children:[ve&&xe.length===0?Array.from({length:6}).map((Le,Ct)=>b.jsx("li",{className:"app-filter-row app-filter-skeleton",children:b.jsx("div",{className:"app-filter-skeleton-bar"})},`sk-${Ct}`)):Pe.length===0&&!et.trim()?b.jsx("li",{className:"app-filter-empty",children:"No apps"}):Pe.map(Le=>b.jsx("li",{className:"app-filter-row",onClick:()=>{S(Le.packageName),Gt()},children:b.jsxs("div",{className:"app-filter-row-labels",children:[b.jsx("div",{className:"app-filter-row-name",children:Le.appName||Le.packageName}),Le.appName&&b.jsx("div",{className:"app-filter-row-pkg",children:Le.packageName})]})},Le.packageName)),et.trim()&&b.jsx("li",{className:"app-filter-row",onClick:()=>{S(et.trim()),Gt()},children:b.jsx("div",{className:"app-filter-row-labels",children:b.jsx("div",{className:"app-filter-row-name",children:et.trim()})})})]})]})})})()]})}function Px({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 Hx({onRefresh:e,threshold:t=70,maxPull:r=110,enabled:s=!0}){const[l,u]=A.useState(0),[c,f]=A.useState(!1),d=A.useRef(null),m=A.useRef(!1),y=A.useRef(0),g=A.useRef(!1),x=A.useRef(e);return A.useEffect(()=>{x.current=e}),A.useEffect(()=>{if(!s)return;const w=D=>{if(g.current||window.scrollY>0){d.current=null;return}if(FE(D.target)){d.current=null;return}d.current=D.touches[0].clientY,m.current=!1,y.current=0},_=D=>{if(g.current||d.current==null)return;const N=D.touches[0].clientY-d.current;if(N<=0){m.current=!1,y.current=0,u(0);return}m.current=!0;const H=Math.min(r,N*.5);y.current=H,u(H),D.cancelable&&D.preventDefault()},j=()=>{if(!m.current){d.current=null,u(0);return}const D=y.current;d.current=null,m.current=!1,y.current=0,D>=t?(g.current=!0,f(!0),u(t),Promise.resolve(x.current()).catch(()=>{}).finally(()=>{g.current=!1,f(!1),u(0)})):u(0)};return window.addEventListener("touchstart",w,{passive:!0}),window.addEventListener("touchmove",_,{passive:!1}),window.addEventListener("touchend",j,{passive:!0}),window.addEventListener("touchcancel",j,{passive:!0}),()=>{window.removeEventListener("touchstart",w),window.removeEventListener("touchmove",_),window.removeEventListener("touchend",j),window.removeEventListener("touchcancel",j)}},[s,t,r]),{pullDistance:l,refreshing:c,threshold:t}}function FE(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 $E({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:u,isNotificationListener:c,onViewRun:f}){const[d,m]=A.useState([]),[y,g]=A.useState(!1),[x,w]=A.useState(null),[_,j]=A.useState(new Map),[D,N]=A.useState(!1),[H,F]=A.useState(void 0),fe=A.useCallback(()=>{N(!1),F(void 0)},[]),z=A.useCallback(async()=>{if(e){g(!0),w(null);try{const L=(await r("task.list")).tasks??[],G=new Map;for(const J of L)J.status&&G.set(J.id,J.status);j(G),m(L)}catch(q){const L=q instanceof Error?q.message:String(q);L==="Not connected"||L.includes("503")||L.toLowerCase().includes("no responders")?w(null):w(L),m([])}finally{g(!1)}}},[e,t,r]);A.useEffect(()=>{e?z():(m([]),g(!1))},[e,t,z]);const R=Hx({onRefresh:z,enabled:e});A.useEffect(()=>!e||!t?void 0:s(t,async L=>{const G=L.subject.split(".");if(G.length<3)return;const J=G.slice(2).join(".");let oe={};try{oe=JSON.parse(new TextDecoder().decode(L.data))}catch{return}const le=oe.event_type;if(!(le!=="running-state"&&le!=="permission-resolved"))try{const K=await r("task.status",{id:J},{timeout:5e3});if(K.error)return;j(U=>{const W=new Map(U);return W.set(J,K),W})}catch{}}),[e,t,s,r]);function ee(q){m(L=>{const G=L.findIndex(J=>J.id===q.id);if(G>=0){const J=[...L];return J[G]=q,J}return[q,...L]}),N(!1),F(void 0)}function $(q){m(L=>L.filter(G=>G.id!==q)),j(L=>{const G=new Map(L);return G.delete(q),G})}return b.jsxs(b.Fragment,{children:[b.jsx(Px,{pullDistance:R.pullDistance,refreshing:R.refreshing,threshold:R.threshold}),x&&b.jsxs("div",{className:"form-error",children:[x,x.toLowerCase().includes("failed to fetch")&&b.jsxs(b.Fragment,{children:[" ",b.jsx("a",{href:"#",onClick:q=>{q.preventDefault(),window.location.reload()},children:"Reload"})]})]}),y&&!d.length?b.jsx("div",{className:"task-list",children:[0,1,2].map(q=>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+q*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%"}})]})]},q))}):d.length===0?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:d.map(q=>b.jsx(RE,{task:q,lastEvent:_.get(q.id),onEdit:async L=>{try{const G=await r("task.get",{id:L.id});F(G.error?L:G)}catch{F(L)}N(!0)},onDelete:$,onViewRun:f},q.id))}),b.jsx("button",{className:"fab",onClick:()=>{F(void 0),N(!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"})]})}),D&&b.jsx(IE,{initial:H,agents:l,hostPlatform:u,isNotificationListener:c,onSaved:ee,onRun:f,onCancel:fe})]})}let ha=null;function Y0(e){ha&&(e.preventDefault(),e.returnValue="")}function Rh(e){const t=!!ha;ha=e;const r=!!ha;r&&!t?window.addEventListener("beforeunload",Y0):!r&&t&&window.removeEventListener("beforeunload",Y0)}function ps(){return ha?window.confirm(ha):!0}function YE(){const e=Mr(),t=cr(),{hostId:r}=Yu(),s=t.pathname.endsWith("/tasks"),l=!s;function u(c){ps()&&r&&e(`/hosts/${encodeURIComponent(r)}${c}`)}return b.jsxs(b.Fragment,{children:[b.jsxs("button",{className:`tab-btn ${l?"tab-btn-active":""}`,onClick:()=>u(""),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:()=>u("/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 qx(e){const[t,r]=A.useState(()=>window.matchMedia(e).matches);return A.useEffect(()=>{const s=window.matchMedia(e),l=u=>r(u.matches);return s.addEventListener("change",l),r(s.matches),()=>s.removeEventListener("change",l)},[e]),t}const Eu=Jn.isNativePlatform(),VE=["Device","Data","Messaging"],GE=[{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 JE(){if(!Eu||!dn)return new Set;try{const{capabilities:e}=await dn.getCapabilityStatus();return new Set(e.filter(t=>t.enabled).map(t=>t.name))}catch{return new Set}}function Ix({onChange:e,confirmDisable:t=!1}){const[r,s]=A.useState(new Map),[l,u]=A.useState(null),[c,f]=A.useState(null),d=A.useCallback(async()=>{if(!(!Eu||!dn))try{const{capabilities:_}=await dn.getCapabilityStatus(),j=new Map;for(const D of _)j.set(D.name,D);s(j),e==null||e(new Set(_.filter(D=>D.enabled).map(D=>D.name)))}catch(_){console.error("Failed to read capability status:",_)}},[e]);A.useEffect(()=>{d()},[d]),A.useEffect(()=>{if(!Eu)return;const _=dd.addListener("resume",d);return()=>{_.then(j=>j.remove())}},[d]);async function m(_,j){if(dn){u(_.capability);try{const D=await dn.setCapabilityEnabled({capability:_.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 ${_.capability}:`,D)}finally{u(null)}}}function y(_){const j=r.get(_.capability);if(j){if(j.enabled&&t){f(_);return}m(_,!j.enabled)}}function g(){const _=c;_&&(f(null),m(_,!1))}if(!Eu)return null;const x=VE.map(_=>({group:_,items:GE.filter(j=>{const D=r.get(j.capability);return j.group===_&&(D==null?void 0:D.supported)})})).filter(_=>_.items.length>0);if(x.length===0)return b.jsx("div",{className:"capability-toggles-loading",children:b.jsx("span",{className:"spinner"})});const w=c&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>f(null),children:b.jsxs("div",{className:"confirm-modal",onClick:_=>_.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:_,items:j},D)=>b.jsx("div",{className:D>0?"drawer-toggle-group drawer-toggle-group-divided":"drawer-toggle-group",children:j.map(N=>{const H=r.get(N.capability),F=!!(H!=null&&H.enabled);return b.jsxs("label",{className:"drawer-toggle",children:[b.jsx("span",{className:"drawer-toggle-label",children:N.label}),b.jsx("button",{className:`toggle-switch ${F?"toggle-switch-on":""}`,onClick:()=>y(N),disabled:l===N.capability,role:"switch","aria-checked":F,children:b.jsx("span",{className:"toggle-switch-thumb"})})]},N.capability)})},_)),w]})}const V0=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),XE=Jn.isNativePlatform();function G0({daemonVersion:e,agents:t,linkedClientToken:r,request:s,onEnabledCapabilitiesChange:l,onLinkedClientTokenChange:u}){var Ft;const{pairedHosts:c,removePairedHost:f,renamePairedHost:d}=qi(),{activeHost:m}=si(),y=Mr(),g=cr(),w=Yu().hostId??null,_=m.clientToken||null,j=!!_&&r===_,D=qx("(min-width: 768px)"),[N,H]=A.useState(!1),[F,fe]=A.useState(()=>Date.now());A.useEffect(()=>{const De=()=>fe(Date.now()),ot=6e4-Date.now()%6e4,tt=setTimeout(()=>{De();const vt=setInterval(De,6e4);tt._iv=vt},ot);return()=>{const vt=tt._iv;vt&&clearInterval(vt),clearTimeout(tt)}},[]);const z=m.timezone?new Date(F).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:m.timezone}):"";async function R(){if(!(!dn||!s||!_)){H(!0);try{const{token:De}=await dn.getFcmToken();if(!De)return;await s("device.link",{fcmToken:De}),u==null||u(_)}catch(De){console.error("Failed to make this the linked device:",De)}finally{H(!1)}}}async function ee(De){const ot=De===w;if(ot&&s)try{await s("clients.revoke_self")}catch{}f(De),ue(null),ot&&y("/",{replace:!0})}function $(De){const tt=g.pathname.endsWith("/tasks")?"/tasks":"";y(`/hosts/${encodeURIComponent(De)}${tt}`)}const[q,L]=A.useState(!1),[G,J]=A.useState(!1),[oe,le]=A.useState(null),[K,U]=A.useState(""),[W,ue]=A.useState(null),[we,M]=A.useState(!1),P=A.useRef(null),te=A.useRef(null),S=A.useCallback(()=>{J(!0)},[]);function xe(){G&&(L(!1),J(!1))}function Ae(){J(!1),L(!0)}function ve(De,ot){le(De),U(ot)}function Ue(){oe&&K.trim()&&d(oe,K.trim()),le(null),U("")}function Ve(){le(null),U("")}A.useEffect(()=>{oe&&te.current&&(te.current.focus(),te.current.select())},[oe]),A.useEffect(()=>{if(!q||G)return;function De(ot){ot.key==="Escape"&&S()}return document.addEventListener("keydown",De),()=>{document.removeEventListener("keydown",De)}},[q,G,S]);const Te=b.jsxs(b.Fragment,{children:[!D&&b.jsx("button",{className:"drawer-close-btn",onClick:S,"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"})})}),!V0&&c.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:c.map(De=>{const ot=De.hostId===w,tt=oe===De.hostId,vt=De.name||De.hostId.slice(0,8);return b.jsx("div",{className:"host-picker-item-wrapper",children:b.jsxs("div",{className:`host-picker-item ${ot?"host-picker-item-active":""}`,onClick:()=>{if(!tt&&!ot){if(!ps())return;$(De.hostId),D||S()}},role:"option","aria-selected":ot,children:[tt?b.jsx("input",{ref:te,className:"form-input host-picker-rename-input",type:"text",value:K,onChange:ft=>U(ft.target.value),onKeyDown:ft=>{ft.key==="Enter"&&Ue(),ft.key==="Escape"&&Ve()},onBlur:Ue,onClick:ft=>ft.stopPropagation()}):b.jsx("span",{className:"host-picker-item-name",children:vt}),b.jsxs("div",{className:"host-picker-item-actions",children:[ot&&!tt&&b.jsx("button",{className:"host-picker-edit-btn",onClick:ft=>{ft.stopPropagation(),ve(De.hostId,vt)},"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"})})}),!ot&&b.jsx("button",{className:"host-picker-delete-btn",onClick:ft=>{ft.stopPropagation(),ue(De.hostId)},"aria-label":`Unpair ${vt}`,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"})})})]})]})},De.hostId)})})})]}),!V0&&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:()=>{ps()&&(y("/pair"),D||S())},children:"Add New Host"})})]}),XE&&s&&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"}),j?b.jsx(Ix,{onChange:l,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:()=>{r&&r!==_?M(!0):R()},disabled:N,children:N?"Linking…":"Link the host to this device"})]})]})]}),b.jsxs("div",{className:"drawer-footer",children:[m.timezone&&b.jsxs("div",{className:"drawer-host-time",children:["Host time: ",z," · ",m.timezone]}),e&&b.jsxs("div",{className:"drawer-version",children:["Host version: v",e]}),t&&t.length>0&&(()=>{const De=t.filter(tt=>tt.version),ot=t.filter(tt=>!tt.version);return b.jsxs("div",{className:"drawer-agents",children:[De.length>0&&b.jsxs("div",{className:"drawer-agents-section",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Agents"}),De.map(tt=>b.jsxs("div",{className:"drawer-agents-row",children:[b.jsx("span",{children:tt.label}),b.jsxs("span",{className:"drawer-agents-version",children:["v",tt.version]})]},tt.key))]}),ot.length>0&&b.jsxs("div",{className:"drawer-agents-section",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Version not managed by Palmier"}),ot.map(tt=>b.jsx("div",{className:"drawer-agents-row",children:b.jsx("span",{children:tt.label})},tt.key))]})]})})(),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"})]})]})]}),et=!!W&&W===w&&j,Pt=W&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>ue(null),children:b.jsxs("div",{className:"confirm-modal",onClick:De=>De.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Remove host?"}),b.jsxs("p",{className:"confirm-modal-message",children:['"',((Ft=c.find(De=>De.hostId===W))==null?void 0:Ft.name)||W.slice(0,8),'" will be ',et?"removed and unlinked":"removed",".",et&&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:()=>ue(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:()=>ee(W),children:"Remove"})]})]})}),document.body),Gt=we&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>M(!1),children:b.jsxs("div",{className:"confirm-modal",onClick:De=>De.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:()=>M(!1),children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:()=>{M(!1),R()},children:"Link"})]})]})}),document.body);return D?b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-panel drawer-panel-desktop",ref:P,children:Te}),Pt,Gt]}):b.jsxs(b.Fragment,{children:[b.jsx("button",{className:"hamburger-btn",onClick:Ae,"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"})})}),q&&ds.createPortal(b.jsx("div",{className:`drawer-overlay ${G?"drawer-overlay-closing":""}`,onClick:S,onAnimationEnd:xe,children:b.jsx("div",{className:`drawer-panel ${G?"drawer-panel-closing":""}`,ref:P,onClick:De=>De.stopPropagation(),children:Te})}),document.body),Pt,Gt]})}const KE=Jn.isNativePlatform(),Yd={width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function QE(){return b.jsxs("svg",{...Yd,"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 J0(){return b.jsxs("svg",{...Yd,"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 ZE(){return b.jsxs("svg",{...Yd,"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 WE(){const{mode:e}=si(),[t,r]=A.useState(!1),s=A.useRef(null);if(A.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,u,c;switch(e){case"lan":l=b.jsx(QE,{}),u="Connected via LAN",c="lan";break;case"nats":l=b.jsx(J0,{}),u=KE?"Connected via relay":"Connected",c="relay";break;case"disconnected":l=b.jsx(ZE,{}),u="Disconnected",c="disconnected";break;case"connecting":default:l=b.jsx(J0,{}),u="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":u,onClick:()=>r(f=>!f),children:l}),b.jsx("div",{className:`conn-status-popover ${t?"conn-status-popover--open":""}`,role:"tooltip",children:u})]})}function X0(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 eC({agents:e,hostPlatform:t,onStarted:r}){const{request:s,activeHost:l}=si(),{setHostLastAgent:u}=qi(),[c,f]=A.useState(""),[d,m]=A.useState(()=>X0(e,l.lastAgent)),[y,g]=A.useState(!1),[x,w]=A.useState(!1),[_,j]=A.useState(null);A.useEffect(()=>{e.length&&(e.find(R=>R.key===d)||m(X0(e,l.lastAgent)))},[e,d,l.lastAgent]),A.useEffect(()=>{const R=c.trim().length>0;return Rh(R?"Your session draft will be lost. Continue?":null),()=>Rh(null)},[c]);const D=e.find(R=>R.key===d),N=!!(D!=null&&D.supportsYolo);A.useEffect(()=>{!N&&y&&g(!1)},[N,y]);const H=!!c.trim()&&!!d&&!x;function F(){return y?confirm(`Yolo mode is enabled. The agent will auto-approve all tool calls — it can read, write, delete files, run arbitrary commands, and access the network without asking for permission.
90
+ Are you sure you want to continue?`):!0}async function $e(){M(!0),fe(null);try{const pe=vt?Fe():z==="on_new_notification"&&te.trim()?[te.trim()]:z==="on_new_sms"&&De.trim()?[De.trim()]:[],Pe=vt||gn?Nh(z):null,Le={user_prompt:g,agent:w,schedule_type:Pe,schedule_values:pe.length>0?pe:null,schedule_enabled:z==="ondemand"?!0:G,requires_confirmation:vt?q:!1,yolo_mode:oe,foreground_mode:K,command:ft?W:""};yn&&(Le.id=e.id);const Dt=await f(yn?"task.update":"task.create",Le,{timeout:45e3});if(Dt.error){fe(Dt.error);return}if(yn||m(d.hostId,w),ft&&!yn){l(Dt);try{const bn=await f("task.run",{id:Dt.id});bn.run_id?u(Dt.id,bn.run_id):bn.error||u(Dt.id)}catch{}return}l(Dt)}catch(pe){fe(pe instanceof Error?pe.message:String(pe))}finally{M(!1)}}const Qe=yn?"Save":ft?"Run":(vt||gn)&&G?"Schedule":"Save";return b.jsxs("div",{className:"task-form-overlay",children:[b.jsx("div",{className:"task-form",children:D?b.jsx(ME,{permissions:e==null?void 0:e.permissions}):b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"task-form-header",children:b.jsx("h2",{children:e?"Edit Task":"New Task"})}),F&&b.jsx("div",{className:"form-error",children:F}),b.jsx("textarea",{autoFocus:!e,className:"form-textarea",value:g,onChange:pe=>x(pe.target.value),placeholder:ft?"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:we}),b.jsxs("div",{className:"plan-actions",children:[b.jsxs("div",{className:"agent-picker-section-inline",children:[b.jsx("span",{className:"agent-picker-label",children:"Run with"}),b.jsx("select",{className:"form-select form-select-sm",value:w,onChange:pe=>_(pe.target.value),disabled:we,children:t.map(pe=>b.jsx("option",{value:pe.key,children:pe.label},pe.key))})]}),Wt&&b.jsxs("label",{className:"yolo-inline",style:{marginLeft:"auto"},children:[b.jsx("input",{type:"checkbox",checked:oe,onChange:pe=>le(pe.target.checked),disabled:we}),"Yolo"]}),Wt&&oe&&b.jsx("p",{className:"yolo-warning",children:"The agent will auto-approve all tool calls without asking for permission."}),j&&b.jsx("div",{className:"granted-permissions-row",children:b.jsx("button",{className:"btn btn-link",onClick:()=>N(!0),children:"Granted Permissions"})})]}),b.jsx("div",{className:"toggles-group",children:b.jsxs("div",{className:"schedule-section",children:[b.jsxs("h3",{className:"schedule-section-title",children:["Schedule ",b.jsx("span",{className:"schedule-section-hint",children:"based on host time"})]}),b.jsxs("select",{className:"form-select",value:z,onChange:pe=>Ke(pe.target.value),disabled:we,children:[b.jsx("option",{value:"ondemand",children:"On 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:"Command-triggered"})]}),gn&&b.jsxs("div",{className:"schedule-reactive",children:[b.jsxs("p",{className:"command-help-text",children:[z==="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 ",z==="on_new_notification"?"notification":"SMS","”."]}),z==="on_new_notification"&&(()=>{const pe=xe.find(Le=>Le.packageName===te),Pe=(pe==null?void 0:pe.appName)||te;return b.jsxs(b.Fragment,{children:[s?te.trim()?b.jsxs("div",{className:"app-filter-selected",children:[b.jsx("span",{className:"app-filter-selected-name",children:Pe}),(pe==null?void 0:pe.appName)&&b.jsx("span",{className:"app-filter-selected-pkg",children:pe.packageName}),b.jsx("button",{type:"button",className:"app-filter-selected-clear",onClick:()=>S(""),"aria-label":"Clear app filter",disabled:we,children:"✕"})]}):b.jsx("button",{type:"button",className:"btn btn-link app-filter-trigger",onClick:()=>{Pt(""),Te(!0)},disabled:we,children:"Select app"}):b.jsx("input",{className:"form-input",type:"text",value:te,onChange:Le=>S(Le.target.value),placeholder:"App (optional), e.g. com.google.android.gm",disabled:we}),b.jsx("p",{className:"command-help-text app-filter-help",children:te.trim()?`Only notifications from ${Pe} will trigger this task.`:"Every notification from your device triggers this task."})]})})(),z==="on_new_sms"&&b.jsxs(b.Fragment,{children:[b.jsx("input",{className:"form-input",type:"text",value:De,onChange:pe=>ot(pe.target.value),placeholder:"From (optional), e.g. +1 555-1234)",disabled:we}),b.jsx("p",{className:"command-help-text app-filter-help",children:De.trim()?`Only SMS from ${De.trim()} will trigger this task. Formatting (spaces, dashes, parens) is ignored.`:"Every SMS that arrives on your device triggers this task."})]})]}),ft&&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:tt,className:"form-input form-input-mono",type:"text",value:W,onChange:pe=>ue(pe.target.value),placeholder:"gws gmail +watch --project my-project",disabled:we})]}),vt&&z!=="hourly"&&b.jsxs(b.Fragment,{children:[ee.map((pe,Pe)=>b.jsxs("div",{className:"trigger-row-card",children:[b.jsxs("div",{className:"trigger-row-content",children:[z==="daily"&&b.jsx("input",{className:"form-input",type:"time",value:pe.time,onChange:Le=>_e(Pe,{time:Le.target.value})}),z==="weekly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:pe.dayOfWeek,onChange:Le=>_e(Pe,{dayOfWeek:Le.target.value}),children:zE.map((Le,Ct)=>b.jsx("option",{value:String(Ct),children:Le},Ct))}),b.jsx("input",{className:"form-input",type:"time",value:pe.time,onChange:Le=>_e(Pe,{time:Le.target.value})})]}),z==="monthly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:pe.dayOfMonth,onChange:Le=>_e(Pe,{dayOfMonth:Le.target.value}),children:Array.from({length:28},(Le,Ct)=>Ct+1).map(Le=>b.jsxs("option",{value:String(Le),children:["Day ",Le]},Le))}),b.jsx("input",{className:"form-input",type:"time",value:pe.time,onChange:Le=>_e(Pe,{time:Le.target.value})})]}),z==="specific_times"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("input",{className:"form-input",type:"date",value:pe.onceDate,min:je.date,onChange:Le=>_e(Pe,{onceDate:Le.target.value})}),b.jsx("input",{className:"form-input",type:"time",value:pe.onceTime,min:pe.onceDate===je.date?je.time:void 0,onChange:Le=>_e(Pe,{onceTime:Le.target.value})})]})]}),ee.length>1&&b.jsx("button",{className:"trigger-remove-btn",onClick:()=>Oe(Pe),title:"Remove trigger",children:"×"})]},Pe)),b.jsx("button",{className:"trigger-add-btn",onClick:Ie,children:"+ Add"})]}),r==="win32"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:K,onChange:pe=>U(pe.target.checked),disabled:we}),"Run in the foreground (host must login to Windows)"]}),vt&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:q,onChange:pe=>L(pe.target.checked),disabled:we}),"Confirm before each run"]}),z!=="ondemand"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:G,onChange:pe=>J(pe.target.checked),disabled:we}),"Enabled"]})]})}),!oe&&an&&!an.supportsPermissions&&b.jsxs("div",{className:"form-warning",children:["Palmier does not support runtime permission granting for ",an.label,". The task may fail if required permissions are not pre-configured."]}),b.jsxs("div",{className:"form-actions",children:[b.jsxs("button",{className:"btn btn-primary",onClick:()=>Ge()&&$e(),disabled:!he||we,children:[we&&b.jsx("span",{className:"btn-spinner"}),Qe]}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{pt&&g.trim()&&!confirm("You have unsaved changes. Discard?")||c()},style:{marginLeft:"auto"},children:"Cancel"})]})]})}),Ve&&(()=>{const pe=et.trim().toLowerCase(),Pe=pe?xe.filter(Le=>Le.packageName.toLowerCase().includes(pe)||Le.appName.toLowerCase().includes(pe)):xe;return b.jsx("div",{className:"app-filter-overlay",onClick:Gt,children:b.jsxs("div",{className:"app-filter-dialog",onClick:Le=>Le.stopPropagation(),children:[b.jsxs("div",{className:"app-filter-header",children:[b.jsx("h2",{children:"Select app"}),b.jsx("button",{className:"app-filter-close",onClick:Gt,"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:et,onChange:Le=>Pt(Le.target.value),onKeyDown:Le=>{Le.key==="Enter"&&et.trim()&&(S(et.trim()),Gt())},placeholder:"Search or type a package name",autoFocus:!0}),b.jsxs("ul",{className:"app-filter-list",children:[ve&&xe.length===0?Array.from({length:6}).map((Le,Ct)=>b.jsx("li",{className:"app-filter-row app-filter-skeleton",children:b.jsx("div",{className:"app-filter-skeleton-bar"})},`sk-${Ct}`)):Pe.length===0&&!et.trim()?b.jsx("li",{className:"app-filter-empty",children:"No apps"}):Pe.map(Le=>b.jsx("li",{className:"app-filter-row",onClick:()=>{S(Le.packageName),Gt()},children:b.jsxs("div",{className:"app-filter-row-labels",children:[b.jsx("div",{className:"app-filter-row-name",children:Le.appName||Le.packageName}),Le.appName&&b.jsx("div",{className:"app-filter-row-pkg",children:Le.packageName})]})},Le.packageName)),et.trim()&&b.jsx("li",{className:"app-filter-row",onClick:()=>{S(et.trim()),Gt()},children:b.jsx("div",{className:"app-filter-row-labels",children:b.jsx("div",{className:"app-filter-row-name",children:et.trim()})})})]})]})})})()]})}function Px({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 Hx({onRefresh:e,threshold:t=70,maxPull:r=110,enabled:s=!0}){const[l,u]=A.useState(0),[c,f]=A.useState(!1),d=A.useRef(null),m=A.useRef(!1),y=A.useRef(0),g=A.useRef(!1),x=A.useRef(e);return A.useEffect(()=>{x.current=e}),A.useEffect(()=>{if(!s)return;const w=D=>{if(g.current||window.scrollY>0){d.current=null;return}if(FE(D.target)){d.current=null;return}d.current=D.touches[0].clientY,m.current=!1,y.current=0},_=D=>{if(g.current||d.current==null)return;const N=D.touches[0].clientY-d.current;if(N<=0){m.current=!1,y.current=0,u(0);return}m.current=!0;const H=Math.min(r,N*.5);y.current=H,u(H),D.cancelable&&D.preventDefault()},j=()=>{if(!m.current){d.current=null,u(0);return}const D=y.current;d.current=null,m.current=!1,y.current=0,D>=t?(g.current=!0,f(!0),u(t),Promise.resolve(x.current()).catch(()=>{}).finally(()=>{g.current=!1,f(!1),u(0)})):u(0)};return window.addEventListener("touchstart",w,{passive:!0}),window.addEventListener("touchmove",_,{passive:!1}),window.addEventListener("touchend",j,{passive:!0}),window.addEventListener("touchcancel",j,{passive:!0}),()=>{window.removeEventListener("touchstart",w),window.removeEventListener("touchmove",_),window.removeEventListener("touchend",j),window.removeEventListener("touchcancel",j)}},[s,t,r]),{pullDistance:l,refreshing:c,threshold:t}}function FE(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 $E({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:u,isNotificationListener:c,onViewRun:f}){const[d,m]=A.useState([]),[y,g]=A.useState(!1),[x,w]=A.useState(null),[_,j]=A.useState(new Map),[D,N]=A.useState(!1),[H,F]=A.useState(void 0),fe=A.useCallback(()=>{N(!1),F(void 0)},[]),z=A.useCallback(async()=>{if(e){g(!0),w(null);try{const L=(await r("task.list")).tasks??[],G=new Map;for(const J of L)J.status&&G.set(J.id,J.status);j(G),m(L)}catch(q){const L=q instanceof Error?q.message:String(q);L==="Not connected"||L.includes("503")||L.toLowerCase().includes("no responders")?w(null):w(L),m([])}finally{g(!1)}}},[e,t,r]);A.useEffect(()=>{e?z():(m([]),g(!1))},[e,t,z]);const R=Hx({onRefresh:z,enabled:e});A.useEffect(()=>!e||!t?void 0:s(t,async L=>{const G=L.subject.split(".");if(G.length<3)return;const J=G.slice(2).join(".");let oe={};try{oe=JSON.parse(new TextDecoder().decode(L.data))}catch{return}const le=oe.event_type;if(!(le!=="running-state"&&le!=="permission-resolved"))try{const K=await r("task.status",{id:J},{timeout:5e3});if(K.error)return;j(U=>{const W=new Map(U);return W.set(J,K),W})}catch{}}),[e,t,s,r]);function ee(q){m(L=>{const G=L.findIndex(J=>J.id===q.id);if(G>=0){const J=[...L];return J[G]=q,J}return[q,...L]}),N(!1),F(void 0)}function $(q){m(L=>L.filter(G=>G.id!==q)),j(L=>{const G=new Map(L);return G.delete(q),G})}return b.jsxs(b.Fragment,{children:[b.jsx(Px,{pullDistance:R.pullDistance,refreshing:R.refreshing,threshold:R.threshold}),x&&b.jsxs("div",{className:"form-error",children:[x,x.toLowerCase().includes("failed to fetch")&&b.jsxs(b.Fragment,{children:[" ",b.jsx("a",{href:"#",onClick:q=>{q.preventDefault(),window.location.reload()},children:"Reload"})]})]}),y&&!d.length?b.jsx("div",{className:"task-list",children:[0,1,2].map(q=>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+q*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%"}})]})]},q))}):d.length===0?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:d.map(q=>b.jsx(RE,{task:q,lastEvent:_.get(q.id),onEdit:async L=>{try{const G=await r("task.get",{id:L.id});F(G.error?L:G)}catch{F(L)}N(!0)},onDelete:$,onViewRun:f},q.id))}),b.jsx("button",{className:"fab",onClick:()=>{F(void 0),N(!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"})]})}),D&&b.jsx(IE,{initial:H,agents:l,hostPlatform:u,isNotificationListener:c,onSaved:ee,onRun:f,onCancel:fe})]})}let ha=null;function Y0(e){ha&&(e.preventDefault(),e.returnValue="")}function Rh(e){const t=!!ha;ha=e;const r=!!ha;r&&!t?window.addEventListener("beforeunload",Y0):!r&&t&&window.removeEventListener("beforeunload",Y0)}function ps(){return ha?window.confirm(ha):!0}function YE(){const e=Mr(),t=cr(),{hostId:r}=Yu(),s=t.pathname.endsWith("/tasks"),l=!s;function u(c){ps()&&r&&e(`/hosts/${encodeURIComponent(r)}${c}`)}return b.jsxs(b.Fragment,{children:[b.jsxs("button",{className:`tab-btn ${l?"tab-btn-active":""}`,onClick:()=>u(""),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:()=>u("/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 qx(e){const[t,r]=A.useState(()=>window.matchMedia(e).matches);return A.useEffect(()=>{const s=window.matchMedia(e),l=u=>r(u.matches);return s.addEventListener("change",l),r(s.matches),()=>s.removeEventListener("change",l)},[e]),t}const Eu=Jn.isNativePlatform(),VE=["Device","Data","Messaging"],GE=[{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 JE(){if(!Eu||!dn)return new Set;try{const{capabilities:e}=await dn.getCapabilityStatus();return new Set(e.filter(t=>t.enabled).map(t=>t.name))}catch{return new Set}}function Ix({onChange:e,confirmDisable:t=!1}){const[r,s]=A.useState(new Map),[l,u]=A.useState(null),[c,f]=A.useState(null),d=A.useCallback(async()=>{if(!(!Eu||!dn))try{const{capabilities:_}=await dn.getCapabilityStatus(),j=new Map;for(const D of _)j.set(D.name,D);s(j),e==null||e(new Set(_.filter(D=>D.enabled).map(D=>D.name)))}catch(_){console.error("Failed to read capability status:",_)}},[e]);A.useEffect(()=>{d()},[d]),A.useEffect(()=>{if(!Eu)return;const _=dd.addListener("resume",d);return()=>{_.then(j=>j.remove())}},[d]);async function m(_,j){if(dn){u(_.capability);try{const D=await dn.setCapabilityEnabled({capability:_.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 ${_.capability}:`,D)}finally{u(null)}}}function y(_){const j=r.get(_.capability);if(j){if(j.enabled&&t){f(_);return}m(_,!j.enabled)}}function g(){const _=c;_&&(f(null),m(_,!1))}if(!Eu)return null;const x=VE.map(_=>({group:_,items:GE.filter(j=>{const D=r.get(j.capability);return j.group===_&&(D==null?void 0:D.supported)})})).filter(_=>_.items.length>0);if(x.length===0)return b.jsx("div",{className:"capability-toggles-loading",children:b.jsx("span",{className:"spinner"})});const w=c&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>f(null),children:b.jsxs("div",{className:"confirm-modal",onClick:_=>_.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:_,items:j},D)=>b.jsx("div",{className:D>0?"drawer-toggle-group drawer-toggle-group-divided":"drawer-toggle-group",children:j.map(N=>{const H=r.get(N.capability),F=!!(H!=null&&H.enabled);return b.jsxs("label",{className:"drawer-toggle",children:[b.jsx("span",{className:"drawer-toggle-label",children:N.label}),b.jsx("button",{className:`toggle-switch ${F?"toggle-switch-on":""}`,onClick:()=>y(N),disabled:l===N.capability,role:"switch","aria-checked":F,children:b.jsx("span",{className:"toggle-switch-thumb"})})]},N.capability)})},_)),w]})}const V0=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),XE=Jn.isNativePlatform();function G0({daemonVersion:e,agents:t,linkedClientToken:r,request:s,onEnabledCapabilitiesChange:l,onLinkedClientTokenChange:u}){var Ft;const{pairedHosts:c,removePairedHost:f,renamePairedHost:d}=qi(),{activeHost:m}=si(),y=Mr(),g=cr(),w=Yu().hostId??null,_=m.clientToken||null,j=!!_&&r===_,D=qx("(min-width: 768px)"),[N,H]=A.useState(!1),[F,fe]=A.useState(()=>Date.now());A.useEffect(()=>{const De=()=>fe(Date.now()),ot=6e4-Date.now()%6e4,tt=setTimeout(()=>{De();const vt=setInterval(De,6e4);tt._iv=vt},ot);return()=>{const vt=tt._iv;vt&&clearInterval(vt),clearTimeout(tt)}},[]);const z=m.timezone?new Date(F).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:m.timezone}):"";async function R(){if(!(!dn||!s||!_)){H(!0);try{const{token:De}=await dn.getFcmToken();if(!De)return;await s("device.link",{fcmToken:De}),u==null||u(_)}catch(De){console.error("Failed to make this the linked device:",De)}finally{H(!1)}}}async function ee(De){const ot=De===w;if(ot&&s)try{await s("clients.revoke_self")}catch{}f(De),ue(null),ot&&y("/",{replace:!0})}function $(De){const tt=g.pathname.endsWith("/tasks")?"/tasks":"";y(`/hosts/${encodeURIComponent(De)}${tt}`)}const[q,L]=A.useState(!1),[G,J]=A.useState(!1),[oe,le]=A.useState(null),[K,U]=A.useState(""),[W,ue]=A.useState(null),[we,M]=A.useState(!1),P=A.useRef(null),te=A.useRef(null),S=A.useCallback(()=>{J(!0)},[]);function xe(){G&&(L(!1),J(!1))}function Ae(){J(!1),L(!0)}function ve(De,ot){le(De),U(ot)}function Ue(){oe&&K.trim()&&d(oe,K.trim()),le(null),U("")}function Ve(){le(null),U("")}A.useEffect(()=>{oe&&te.current&&(te.current.focus(),te.current.select())},[oe]),A.useEffect(()=>{if(!q||G)return;function De(ot){ot.key==="Escape"&&S()}return document.addEventListener("keydown",De),()=>{document.removeEventListener("keydown",De)}},[q,G,S]);const Te=b.jsxs(b.Fragment,{children:[!D&&b.jsx("button",{className:"drawer-close-btn",onClick:S,"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"})})}),!V0&&c.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:c.map(De=>{const ot=De.hostId===w,tt=oe===De.hostId,vt=De.name||De.hostId.slice(0,8);return b.jsx("div",{className:"host-picker-item-wrapper",children:b.jsxs("div",{className:`host-picker-item ${ot?"host-picker-item-active":""}`,onClick:()=>{if(!tt&&!ot){if(!ps())return;$(De.hostId),D||S()}},role:"option","aria-selected":ot,children:[tt?b.jsx("input",{ref:te,className:"form-input host-picker-rename-input",type:"text",value:K,onChange:ft=>U(ft.target.value),onKeyDown:ft=>{ft.key==="Enter"&&Ue(),ft.key==="Escape"&&Ve()},onBlur:Ue,onClick:ft=>ft.stopPropagation()}):b.jsx("span",{className:"host-picker-item-name",children:vt}),b.jsxs("div",{className:"host-picker-item-actions",children:[ot&&!tt&&b.jsx("button",{className:"host-picker-edit-btn",onClick:ft=>{ft.stopPropagation(),ve(De.hostId,vt)},"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"})})}),!ot&&b.jsx("button",{className:"host-picker-delete-btn",onClick:ft=>{ft.stopPropagation(),ue(De.hostId)},"aria-label":`Unpair ${vt}`,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"})})})]})]})},De.hostId)})})})]}),!V0&&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:()=>{ps()&&(y("/pair"),D||S())},children:"Add New Host"})})]}),XE&&s&&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"}),j?b.jsx(Ix,{onChange:l,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:()=>{r&&r!==_?M(!0):R()},disabled:N,children:N?"Linking…":"Link the host to this device"})]})]})]}),b.jsxs("div",{className:"drawer-footer",children:[t&&t.length>0&&(()=>{const De=t.filter(tt=>tt.version),ot=t.filter(tt=>!tt.version);return b.jsxs("div",{className:"drawer-agents",children:[De.length>0&&b.jsxs("div",{className:"drawer-agents-section",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Agents"}),De.map(tt=>b.jsxs("div",{className:"drawer-agents-row",children:[b.jsx("span",{children:tt.label}),b.jsxs("span",{className:"drawer-agents-version",children:["v",tt.version]})]},tt.key))]}),ot.length>0&&b.jsxs("div",{className:"drawer-agents-section",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Version not managed by Palmier"}),ot.map(tt=>b.jsx("div",{className:"drawer-agents-row",children:b.jsx("span",{children:tt.label})},tt.key))]})]})})(),(m.timezone||e)&&b.jsxs("div",{className:"drawer-host-info",children:[b.jsx("div",{className:"drawer-agents-heading",children:"Host"}),m.timezone&&b.jsxs("div",{className:"drawer-host-time",children:[z," · ",m.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"})]})]})]}),et=!!W&&W===w&&j,Pt=W&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>ue(null),children:b.jsxs("div",{className:"confirm-modal",onClick:De=>De.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Remove host?"}),b.jsxs("p",{className:"confirm-modal-message",children:['"',((Ft=c.find(De=>De.hostId===W))==null?void 0:Ft.name)||W.slice(0,8),'" will be ',et?"removed and unlinked":"removed",".",et&&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:()=>ue(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:()=>ee(W),children:"Remove"})]})]})}),document.body),Gt=we&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>M(!1),children:b.jsxs("div",{className:"confirm-modal",onClick:De=>De.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:()=>M(!1),children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:()=>{M(!1),R()},children:"Link"})]})]})}),document.body);return D?b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-panel drawer-panel-desktop",ref:P,children:Te}),Pt,Gt]}):b.jsxs(b.Fragment,{children:[b.jsx("button",{className:"hamburger-btn",onClick:Ae,"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"})})}),q&&ds.createPortal(b.jsx("div",{className:`drawer-overlay ${G?"drawer-overlay-closing":""}`,onClick:S,onAnimationEnd:xe,children:b.jsx("div",{className:`drawer-panel ${G?"drawer-panel-closing":""}`,ref:P,onClick:De=>De.stopPropagation(),children:Te})}),document.body),Pt,Gt]})}const KE=Jn.isNativePlatform(),Yd={width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function QE(){return b.jsxs("svg",{...Yd,"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 J0(){return b.jsxs("svg",{...Yd,"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 ZE(){return b.jsxs("svg",{...Yd,"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 WE(){const{mode:e}=si(),[t,r]=A.useState(!1),s=A.useRef(null);if(A.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,u,c;switch(e){case"lan":l=b.jsx(QE,{}),u="Connected via LAN",c="lan";break;case"nats":l=b.jsx(J0,{}),u=KE?"Connected via relay":"Connected",c="relay";break;case"disconnected":l=b.jsx(ZE,{}),u="Disconnected",c="disconnected";break;case"connecting":default:l=b.jsx(J0,{}),u="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":u,onClick:()=>r(f=>!f),children:l}),b.jsx("div",{className:`conn-status-popover ${t?"conn-status-popover--open":""}`,role:"tooltip",children:u})]})}function X0(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 eC({agents:e,hostPlatform:t,onStarted:r}){const{request:s,activeHost:l}=si(),{setHostLastAgent:u}=qi(),[c,f]=A.useState(""),[d,m]=A.useState(()=>X0(e,l.lastAgent)),[y,g]=A.useState(!1),[x,w]=A.useState(!1),[_,j]=A.useState(null);A.useEffect(()=>{e.length&&(e.find(R=>R.key===d)||m(X0(e,l.lastAgent)))},[e,d,l.lastAgent]),A.useEffect(()=>{const R=c.trim().length>0;return Rh(R?"Your session draft will be lost. Continue?":null),()=>Rh(null)},[c]);const D=e.find(R=>R.key===d),N=!!(D!=null&&D.supportsYolo);A.useEffect(()=>{!N&&y&&g(!1)},[N,y]);const H=!!c.trim()&&!!d&&!x;function F(){return y?confirm(`Yolo mode is enabled. The agent will auto-approve all tool calls — it can read, write, delete files, run arbitrary commands, and access the network without asking for permission.
91
91
 
92
92
  Are you sure you want to continue?`):!0}async function fe(){if(!(!H||!F())){w(!0),j(null);try{const R=await s("task.run_oneoff",{user_prompt:c,agent:d,yolo_mode:y,...t==="win32"?{foreground_mode:!0}:{}});if(R.error){j(R.error);return}u(l.hostId,d),f(""),Rh(null),R.task_id&&r(R.task_id,R.run_id)}catch(R){j(R instanceof Error?R.message:String(R))}finally{w(!1)}}}function z(R){R.key==="Enter"&&(R.metaKey||R.ctrlKey)&&(R.preventDefault(),fe())}return b.jsxs("div",{className:"session-composer",children:[_&&b.jsx("div",{className:"form-error",children:_}),b.jsx("textarea",{className:"session-composer-textarea",value:c,onChange:R=>f(R.target.value),onKeyDown:z,placeholder:"What can I do for you?",rows:3,disabled:x}),b.jsxs("div",{className:"session-composer-controls",children:[b.jsxs("div",{className:"agent-picker-section-inline",children:[b.jsx("span",{className:"agent-picker-label",children:"Run with"}),b.jsx("select",{className:"form-select form-select-sm",value:d,onChange:R=>m(R.target.value),disabled:x||!e.length,children:e.map(R=>b.jsx("option",{value:R.key,children:R.label},R.key))})]}),N&&b.jsxs("label",{className:"session-composer-yolo",children:[b.jsx("input",{type:"checkbox",checked:y,onChange:R=>g(R.target.checked),disabled:x}),"Yolo"]}),b.jsx("button",{className:"btn btn-primary chat-send-btn",onClick:fe,disabled:!H,"aria-label":"Run session",title:"Run session",children:x?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"})]})})]}),N&&y&&b.jsx("p",{className:"command-help-text",children:"The agent will auto-approve all tool calls without asking for permission."})]})}const fs=72,K0=6;function tC({id:e,revealedId:t,setRevealedId:r,onDelete:s,onClick:l,children:u,actionLabel:c="Delete",confirmMessage:f="Delete this item? This can't be undone."}){const d=t===e,[m,y]=A.useState(0),[g,x]=A.useState(!1),w=A.useRef(0),_=A.useRef(0),j=A.useRef(null),D=A.useRef(0),N=A.useRef(!1),H=A.useRef(null);A.useEffect(()=>{d||y(0)},[d]),A.useEffect(()=>{if(!d)return;function $(q){var L;(L=H.current)!=null&&L.contains(q.target)||r(null)}return document.addEventListener("pointerdown",$),()=>document.removeEventListener("pointerdown",$)},[d,r]);function F($){$.button!==void 0&&$.button!==0||(w.current=$.clientX,_.current=$.clientY,j.current=null,D.current=d?-fs:0,N.current=!1)}function fe($){if($.pointerType==="mouse"&&$.buttons===0)return;const q=$.clientX-w.current,L=$.clientY-_.current;if(j.current===null){if(Math.abs(q)<K0&&Math.abs(L)<K0)return;if(j.current=Math.abs(q)>Math.abs(L)?"x":"y",j.current==="x")try{$.currentTarget.setPointerCapture($.pointerId)}catch{}}if(j.current!=="x")return;N.current=!0,g||x(!0);let G=D.current+q;G>0&&(G=G/4),G<-fs&&(G=-fs+(G+fs)/4),y(G)}function z(){if(j.current!=="x"){x(!1);return}j.current=null,x(!1),m<=-36?(y(-fs),r(e)):(y(0),d&&r(null))}function R($){if(N.current){N.current=!1,$.stopPropagation(),$.preventDefault();return}d&&($.stopPropagation(),$.preventDefault(),r(null))}const ee=m!==0?m:d?-fs:0;return b.jsxs("div",{ref:H,className:"swipe-row",children:[b.jsxs("button",{type:"button",className:"swipe-row-action",style:{width:fs},onClick:$=>{$.stopPropagation(),window.confirm(f)&&s()},tabIndex:d?0:-1,"aria-hidden":!d,"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 ${g?"swipe-row-content-dragging":""}`,style:{transform:`translateX(${ee}px)`},onPointerDown:F,onPointerMove:fe,onPointerUp:z,onPointerCancel:z,onClickCapture:R,onClick:l,children:u})]})}const nC=10;function rC({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:u,filterTaskId:c,onClearFilter:f}){const d=$d(),[m,y]=A.useState([]),[g,x]=A.useState(0),[w,_]=A.useState(!1),[j,D]=A.useState(!1),[N,H]=A.useState(null),F=Mr();async function fe(U){const W=`${U.task_id}:${U.run_id}`;y(ue=>ue.filter(we=>`${we.task_id}:${we.run_id}`!==W)),x(ue=>Math.max(0,ue-1)),H(null);try{await r("taskrun.delete",{task_id:U.task_id,run_id:U.run_id})}catch(ue){console.error("Failed to delete run:",ue),y(we=>[U,...we]),x(we=>we+1)}}const z=A.useRef(null),R=A.useCallback(U=>{const W={offset:U,limit:nC};return c&&(W.task_id=c),W},[c]),ee=A.useCallback(async(U,W)=>{if(e){W?D(!0):_(!0);try{const ue=await r("taskrun.list",R(U)),we=ue.entries??[];x(ue.total??0),y(W?M=>{const P=new Set(M.map(S=>`${S.task_id}:${S.run_id}`)),te=we.filter(S=>!P.has(`${S.task_id}:${S.run_id}`));return[...M,...te]}:we)}catch(ue){ue instanceof Error&&ue.message==="Not connected"||console.error("Failed to load runs:",ue)}finally{_(!1),D(!1)}}},[e,r,R]);A.useEffect(()=>{e?(y([]),x(0),ee(0,!1)):(y([]),x(0))},[e,t,ee,c]);const $=Hx({onRefresh:()=>ee(0,!1),enabled:e});A.useEffect(()=>!e||!t?void 0:s(t,async W=>{try{const ue=JSON.parse(new TextDecoder().decode(W.data));if(ue.event_type==="running-state"&&ue.running_state&&["monitoring","started","finished","failed","aborted"].includes(ue.running_state)){const we=await r("taskrun.list",R(0)),M=we.entries??[];x(we.total??0),y(P=>{const te=new Map(M.map(ve=>[`${ve.task_id}:${ve.run_id}`,ve])),S=P.map(ve=>{const Ue=`${ve.task_id}:${ve.run_id}`;return te.get(Ue)??ve}),xe=new Set(S.map(ve=>`${ve.task_id}:${ve.run_id}`));return[...M.filter(ve=>!xe.has(`${ve.task_id}:${ve.run_id}`)),...S]})}}catch{}}),[e,t,s,r]),A.useEffect(()=>{const U=z.current;if(!U)return;const W=new IntersectionObserver(ue=>{ue[0].isIntersecting&&!j&&m.length<g&&ee(m.length,!0)},{threshold:.1});return W.observe(U),()=>W.disconnect()},[m.length,g,j,ee]);function q(U,W){if(!U||!W)return"";const ue=Math.round((W-U)/1e3);if(ue<60)return`${ue}s`;const we=Math.floor(ue/60),M=ue%60;return`${we}m ${M}s`}const L={monitoring:"Monitoring",started:"Running",finished:"Finished",failed:"Failed",aborted:"Aborted"};function G(U,W){ps()&&t&&F(`/hosts/${encodeURIComponent(t)}/runs/${encodeURIComponent(U)}/${encodeURIComponent(W)}`)}const J=!c&&b.jsx(eC,{agents:l,hostPlatform:u,onStarted:(U,W)=>{if(!t)return;const ue=`/hosts/${encodeURIComponent(t)}/runs/${encodeURIComponent(U)}`;F(W?`${ue}/${encodeURIComponent(W)}`:ue)}}),oe=b.jsx(Px,{pullDistance:$.pullDistance,refreshing:$.refreshing,threshold:$.threshold}),le=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 K(U){if(U==="failed")return"var(--color-error)";if(U==="aborted")return"var(--color-warning, #d97706)"}return w&&m.length===0&&e?b.jsxs(b.Fragment,{children:[oe,J,b.jsx("div",{className:"task-list",children:[0,1,2].map(U=>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+U*10}%`}})})}),b.jsx("div",{className:"task-card-meta",children:b.jsx("div",{className:"skeleton-line",style:{width:"45%"}})})]},U))})]}):!e||w&&m.length===0?b.jsxs(b.Fragment,{children:[oe,J,b.jsx("div",{className:"sessions-view",children:b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"Sessions"}),b.jsx("p",{className:"empty-state-hint",children:"Your sessions will appear here"})]})})]}):m.length===0?b.jsxs(b.Fragment,{children:[oe,J,le,b.jsx("div",{className:"sessions-view",children: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:[oe,J,le,b.jsxs("div",{className:"task-list",children:[m.map((U,W)=>{const ue=`${U.task_id}:${U.run_id}`;return b.jsx(tC,{id:ue,revealedId:N,setRevealedId:H,onDelete:()=>fe(U),confirmMessage:"Delete this session? Its run history will be removed from the host.",onClick:()=>!U.error&&G(U.task_id,U.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:U.task_name||U.task_id}),b.jsxs("div",{className:"sessions-card-meta",children:[U.running_state==="started"?b.jsx("span",{className:"status-spinner","aria-label":"Running",children:b.jsx("span",{})}):b.jsx("span",{style:{color:K(U.running_state)},children:L[U.running_state??""]??U.running_state}),U.end_time&&b.jsx("span",{children:d(U.end_time)}),U.start_time&&U.end_time&&b.jsx("span",{style:{color:"var(--color-muted)"},children:q(U.start_time,U.end_time)}),U.error&&b.jsx("span",{style:{color:"var(--color-muted)"},children:U.error})]})]}),b.jsx("span",{className:"sessions-card-chevron",children:"›"})]})},`${ue}-${W}`)}),b.jsx("div",{ref:z,style:{height:1}}),j&&b.jsx("div",{className:"loading-state",style:{padding:"var(--space-md)"},children:b.jsx("div",{className:"spinner"})})]})]})}function iC(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const sC=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,aC=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,lC={};function Q0(e,t){return(lC.jsx?aC:sC).test(e)}const oC=/[ \t\n\f\r]/g;function uC(e){return typeof e=="object"?e.type==="text"?Z0(e.value):!1:Z0(e)}function Z0(e){return e.replace(oC,"")===""}class Gl{constructor(t,r,s){this.normal=r,this.property=t,s&&(this.space=s)}}Gl.prototype.normal={};Gl.prototype.property={};Gl.prototype.space=void 0;function Fx(e,t){const r={},s={};for(const l of e)Object.assign(r,l.property),Object.assign(s,l.normal);return new Gl(r,s,t)}function gd(e){return e.toLowerCase()}class Rn{constructor(t,r){this.attribute=r,this.property=t}}Rn.prototype.attribute="";Rn.prototype.booleanish=!1;Rn.prototype.boolean=!1;Rn.prototype.commaOrSpaceSeparated=!1;Rn.prototype.commaSeparated=!1;Rn.prototype.defined=!1;Rn.prototype.mustUseProperty=!1;Rn.prototype.number=!1;Rn.prototype.overloadedBoolean=!1;Rn.prototype.property="";Rn.prototype.spaceSeparated=!1;Rn.prototype.space=void 0;let cC=0;const We=bs(),Zt=bs(),yd=bs(),Se=bs(),Nt=bs(),da=bs(),qn=bs();function bs(){return 2**++cC}const bd=Object.freeze(Object.defineProperty({__proto__:null,boolean:We,booleanish:Zt,commaOrSpaceSeparated:qn,commaSeparated:da,number:Se,overloadedBoolean:yd,spaceSeparated:Nt},Symbol.toStringTag,{value:"Module"})),Mh=Object.keys(bd);class Vd extends Rn{constructor(t,r,s,l){let u=-1;if(super(t,r),W0(this,"space",l),typeof s=="number")for(;++u<Mh.length;){const c=Mh[u];W0(this,Mh[u],(s&bd[c])===bd[c])}}}Vd.prototype.defined=!0;function W0(e,t,r){r&&(e[t]=r)}function _a(e){const t={},r={};for(const[s,l]of Object.entries(e.properties)){const u=new Vd(s,e.transform(e.attributes||{},s),l,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(u.mustUseProperty=!0),t[s]=u,r[gd(s)]=s,r[gd(u.attribute)]=s}return new Gl(t,r,e.space)}const $x=_a({properties:{ariaActiveDescendant:null,ariaAtomic:Zt,ariaAutoComplete:null,ariaBusy:Zt,ariaChecked:Zt,ariaColCount:Se,ariaColIndex:Se,ariaColSpan:Se,ariaControls:Nt,ariaCurrent:null,ariaDescribedBy:Nt,ariaDetails:null,ariaDisabled:Zt,ariaDropEffect:Nt,ariaErrorMessage:null,ariaExpanded:Zt,ariaFlowTo:Nt,ariaGrabbed:Zt,ariaHasPopup:null,ariaHidden:Zt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Nt,ariaLevel:Se,ariaLive:null,ariaModal:Zt,ariaMultiLine:Zt,ariaMultiSelectable:Zt,ariaOrientation:null,ariaOwns:Nt,ariaPlaceholder:null,ariaPosInSet:Se,ariaPressed:Zt,ariaReadOnly:Zt,ariaRelevant:null,ariaRequired:Zt,ariaRoleDescription:Nt,ariaRowCount:Se,ariaRowIndex:Se,ariaRowSpan:Se,ariaSelected:Zt,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 Yx(e,t){return t in e?e[t]:t}function Vx(e,t){return Yx(e,t.toLowerCase())}const fC=_a({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:da,acceptCharset:Nt,accessKey:Nt,action:null,allow:null,allowFullScreen:We,allowPaymentRequest:We,allowUserMedia:We,alt:null,as:null,async:We,autoCapitalize:null,autoComplete:Nt,autoFocus:We,autoPlay:We,blocking:Nt,capture:null,charSet:null,checked:We,cite:null,className:Nt,cols:Se,colSpan:null,content:null,contentEditable:Zt,controls:We,controlsList:Nt,coords:Se|da,crossOrigin:null,data:null,dateTime:null,decoding:null,default:We,defer:We,dir:null,dirName:null,disabled:We,download:yd,draggable:Zt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:We,formTarget:null,headers:Nt,height:Se,hidden:yd,high:Se,href:null,hrefLang:null,htmlFor:Nt,httpEquiv:Nt,id:null,imageSizes:null,imageSrcSet:null,inert:We,inputMode:null,integrity:null,is:null,isMap:We,itemId:null,itemProp:Nt,itemRef:Nt,itemScope:We,itemType:Nt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:We,low:Se,manifest:null,max:null,maxLength:Se,media:null,method:null,min:null,minLength:Se,multiple:We,muted:We,name:null,nonce:null,noModule:We,noValidate:We,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:We,optimum:Se,pattern:null,ping:Nt,placeholder:null,playsInline:We,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:We,referrerPolicy:null,rel:Nt,required:We,reversed:We,rows:Se,rowSpan:Se,sandbox:Nt,scope:null,scoped:We,seamless:We,selected:We,shadowRootClonable:We,shadowRootDelegatesFocus:We,shadowRootMode:null,shape:null,size:Se,sizes:null,slot:null,span:Se,spellCheck:Zt,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:We,useMap:null,value:Zt,width:Se,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Nt,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:We,declare:We,event:null,face:null,frame:null,frameBorder:null,hSpace:Se,leftMargin:Se,link:null,longDesc:null,lowSrc:null,marginHeight:Se,marginWidth:Se,noResize:We,noHref:We,noShade:We,noWrap:We,object:null,profile:null,prompt:null,rev:null,rightMargin:Se,rules:null,scheme:null,scrolling:Zt,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:We,disableRemotePlayback:We,prefix:null,property:null,results:Se,security:null,unselectable:null},space:"html",transform:Vx}),hC=_a({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:qn,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:Nt,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:We,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:da,g2:da,glyphName:da,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:qn,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:Nt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Se,pointsAtY:Se,pointsAtZ:Se,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:qn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:qn,rev:qn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:qn,requiredFeatures:qn,requiredFonts:qn,requiredFormats:qn,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:qn,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:qn,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:qn,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:Yx}),Gx=_a({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()}}),Jx=_a({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Vx}),Xx=_a({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),dC={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"},mC=/[A-Z]/g,eb=/-[a-z]/g,pC=/^data[-\w.:]+$/i;function gC(e,t){const r=gd(t);let s=t,l=Rn;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&pC.test(t)){if(t.charAt(4)==="-"){const u=t.slice(5).replace(eb,bC);s="data"+u.charAt(0).toUpperCase()+u.slice(1)}else{const u=t.slice(4);if(!eb.test(u)){let c=u.replace(mC,yC);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}l=Vd}return new l(s,t)}function yC(e){return"-"+e.toLowerCase()}function bC(e){return e.charAt(1).toUpperCase()}const xC=Fx([$x,fC,Gx,Jx,Xx],"html"),Gd=Fx([$x,hC,Gx,Jx,Xx],"svg");function vC(e){return e.join(" ").trim()}var ta={},Dh,tb;function wC(){if(tb)return Dh;tb=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,l=/^:\s*/,u=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,f=/^\s+|\s+$/g,d=`
93
93
  `,m="/",y="*",g="",x="comment",w="declaration";function _(D,N){if(typeof D!="string")throw new TypeError("First argument must be a string");if(!D)return[];N=N||{};var H=1,F=1;function fe(le){var K=le.match(t);K&&(H+=K.length);var U=le.lastIndexOf(d);F=~U?le.length-U:F+le.length}function z(){var le={line:H,column:F};return function(K){return K.position=new R(le),q(),K}}function R(le){this.start=le,this.end={line:H,column:F},this.source=N.source}R.prototype.content=D;function ee(le){var K=new Error(N.source+":"+H+":"+F+": "+le);if(K.reason=le,K.filename=N.source,K.line=H,K.column=F,K.source=D,!N.silent)throw K}function $(le){var K=le.exec(D);if(K){var U=K[0];return fe(U),D=D.slice(U.length),K}}function q(){$(r)}function L(le){var K;for(le=le||[];K=G();)K!==!1&&le.push(K);return le}function G(){var le=z();if(!(m!=D.charAt(0)||y!=D.charAt(1))){for(var K=2;g!=D.charAt(K)&&(y!=D.charAt(K)||m!=D.charAt(K+1));)++K;if(K+=2,g===D.charAt(K-1))return ee("End of comment missing");var U=D.slice(2,K-2);return F+=2,fe(U),D=D.slice(K),F+=2,le({type:x,comment:U})}}function J(){var le=z(),K=$(s);if(K){if(G(),!$(l))return ee("property missing ':'");var U=$(u),W=le({type:w,property:j(K[0].replace(e,g)),value:U?j(U[0].replace(e,g)):g});return $(c),W}}function oe(){var le=[];L(le);for(var K;K=J();)K!==!1&&(le.push(K),L(le));return le}return q(),oe()}function j(D){return D?D.replace(f,g):g}return Dh=_,Dh}var nb;function SC(){if(nb)return ta;nb=1;var e=ta&&ta.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ta,"__esModule",{value:!0}),ta.default=r;const t=e(wC());function r(s,l){let u=null;if(!s||typeof s!="string")return u;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&&(u=u||{},u[m]=y)}),u}return ta}var vl={},rb;function _C(){if(rb)return vl;rb=1,Object.defineProperty(vl,"__esModule",{value:!0}),vl.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,l=/^-(ms)-/,u=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={}),u(m)?m:(m=m.toLowerCase(),y.reactCompat?m=m.replace(l,f):m=m.replace(s,f),m.replace(t,c))};return vl.camelCase=d,vl}var wl,ib;function kC(){if(ib)return wl;ib=1;var e=wl&&wl.__importDefault||function(l){return l&&l.__esModule?l:{default:l}},t=e(SC()),r=_C();function s(l,u){var c={};return!l||typeof l!="string"||(0,t.default)(l,function(f,d){f&&d&&(c[(0,r.camelCase)(f,u)]=d)}),c}return s.default=s,wl=s,wl}var EC=kC();const CC=Yb(EC),Kx=Qx("end"),Jd=Qx("start");function Qx(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 AC(e){const t=Jd(e),r=Kx(e);if(t&&r)return{start:t,end:r}}function Rl(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?sb(e.position):"start"in e||"end"in e?sb(e):"line"in e||"column"in e?xd(e):""}function xd(e){return ab(e&&e.line)+":"+ab(e&&e.column)}function sb(e){return xd(e&&e.start)+"-"+xd(e&&e.end)}function ab(e){return e&&typeof e=="number"?e:1}class pn extends Error{constructor(t,r,s){super(),typeof r=="string"&&(s=r,r=void 0);let l="",u={},c=!1;if(r&&("line"in r&&"column"in r?u={place:r}:"start"in r&&"end"in r?u={place:r}:"type"in r?u={ancestors:[r],place:r.position}:u={...r}),typeof t=="string"?l=t:!u.cause&&t&&(c=!0,l=t.message,u.cause=t),!u.ruleId&&!u.source&&typeof s=="string"){const d=s.indexOf(":");d===-1?u.ruleId=s:(u.source=s.slice(0,d),u.ruleId=s.slice(d+1))}if(!u.place&&u.ancestors&&u.ancestors){const d=u.ancestors[u.ancestors.length-1];d&&(u.place=d.position)}const f=u.place&&"start"in u.place?u.place.start:u.place;this.ancestors=u.ancestors||void 0,this.cause=u.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=Rl(u.place)||"1:1",this.place=u.place||void 0,this.reason=this.message,this.ruleId=u.ruleId||void 0,this.source=u.source||void 0,this.stack=c&&u.cause&&typeof u.cause.stack=="string"?u.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}pn.prototype.file="";pn.prototype.name="";pn.prototype.reason="";pn.prototype.message="";pn.prototype.stack="";pn.prototype.column=void 0;pn.prototype.line=void 0;pn.prototype.ancestors=void 0;pn.prototype.cause=void 0;pn.prototype.fatal=void 0;pn.prototype.place=void 0;pn.prototype.ruleId=void 0;pn.prototype.source=void 0;const Xd={}.hasOwnProperty,TC=new Map,jC=/[A-Z]/g,NC=new Set(["table","tbody","thead","tfoot","tr"]),OC=new Set(["td","th"]),Zx="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function RC(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=HC(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=PC(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"?Gd:xC,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},u=Wx(l,e,void 0);return u&&typeof u!="string"?u:l.create(e,l.Fragment,{children:u||void 0},void 0)}function Wx(e,t,r){if(t.type==="element")return MC(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return DC(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zC(e,t,r);if(t.type==="mdxjsEsm")return LC(e,t);if(t.type==="root")return UC(e,t,r);if(t.type==="text")return BC(e,t)}function MC(e,t,r){const s=e.schema;let l=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(l=Gd,e.schema=l),e.ancestors.push(t);const u=t1(e,t.tagName,!1),c=qC(e,t);let f=Qd(e,t);return NC.has(t.tagName)&&(f=f.filter(function(d){return typeof d=="string"?!uC(d):!0})),e1(e,c,u,t),Kd(c,f),e.ancestors.pop(),e.schema=s,e.create(t,u,c,r)}function DC(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)}ql(e,t.position)}function LC(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);ql(e,t.position)}function zC(e,t,r){const s=e.schema;let l=s;t.name==="svg"&&s.space==="html"&&(l=Gd,e.schema=l),e.ancestors.push(t);const u=t.name===null?e.Fragment:t1(e,t.name,!0),c=IC(e,t),f=Qd(e,t);return e1(e,c,u,t),Kd(c,f),e.ancestors.pop(),e.schema=s,e.create(t,u,c,r)}function UC(e,t,r){const s={};return Kd(s,Qd(e,t)),e.create(t,e.Fragment,s,r)}function BC(e,t){return t.value}function e1(e,t,r,s){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=s)}function Kd(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function PC(e,t,r){return s;function s(l,u,c,f){const m=Array.isArray(c.children)?r:t;return f?m(u,c,f):m(u,c)}}function HC(e,t){return r;function r(s,l,u,c){const f=Array.isArray(u.children),d=Jd(s);return t(l,u,c,f,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function qC(e,t){const r={};let s,l;for(l in t.properties)if(l!=="children"&&Xd.call(t.properties,l)){const u=FC(e,l,t.properties[l]);if(u){const[c,f]=u;e.tableCellAlignToStyle&&c==="align"&&typeof f=="string"&&OC.has(t.tagName)?s=f:r[c]=f}}if(s){const u=r.style||(r.style={});u[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return r}function IC(e,t){const r={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const u=s.data.estree.body[0];u.type;const c=u.expression;c.type;const f=c.properties[0];f.type,Object.assign(r,e.evaluater.evaluateExpression(f.argument))}else ql(e,t.position);else{const l=s.name;let u;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,u=e.evaluater.evaluateExpression(f.expression)}else ql(e,t.position);else u=s.value===null?!0:s.value;r[l]=u}return r}function Qd(e,t){const r=[];let s=-1;const l=e.passKeys?new Map:TC;for(;++s<t.children.length;){const u=t.children[s];let c;if(e.passKeys){const d=u.type==="element"?u.tagName:u.type==="mdxJsxFlowElement"||u.type==="mdxJsxTextElement"?u.name:void 0;if(d){const m=l.get(d)||0;c=d+"-"+m,l.set(d,m+1)}}const f=Wx(e,u,c);f!==void 0&&r.push(f)}return r}function FC(e,t,r){const s=gC(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=s.commaSeparated?iC(r):vC(r)),s.property==="style"){let l=typeof r=="object"?r:$C(e,String(r));return e.stylePropertyNameCase==="css"&&(l=YC(l)),["style",l]}return[e.elementAttributeNameCase==="react"&&s.space?dC[s.property]||s.property:s.attribute,r]}}function $C(e,t){try{return CC(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const s=r,l=new pn("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=Zx+"#cannot-parse-style-attribute",l}}function t1(e,t,r){let s;if(!r)s={type:"Literal",value:t};else if(t.includes(".")){const l=t.split(".");let u=-1,c;for(;++u<l.length;){const f=Q0(l[u])?{type:"Identifier",name:l[u]}:{type:"Literal",value:l[u]};c=c?{type:"MemberExpression",object:c,property:f,computed:!!(u&&f.type==="Literal"),optional:!1}:f}s=c}else s=Q0(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const l=s.value;return Xd.call(e.components,l)?e.components[l]:l}if(e.evaluater)return e.evaluater.evaluateExpression(s);ql(e)}function ql(e,t){const r=new pn("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=Zx+"#cannot-handle-mdx-estrees-without-createevaluater",r}function YC(e){const t={};let r;for(r in e)Xd.call(e,r)&&(t[VC(r)]=e[r]);return t}function VC(e){let t=e.replace(jC,GC);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function GC(e){return"-"+e.toLowerCase()}const Lh={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"]},JC={};function Zd(e,t){const r=JC,s=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,l=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return n1(e,s,l)}function n1(e,t,r){if(XC(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 lb(e.children,t,r)}return Array.isArray(e)?lb(e,t,r):""}function lb(e,t,r){const s=[];let l=-1;for(;++l<e.length;)s[l]=n1(e[l],t,r);return s.join("")}function XC(e){return!!(e&&typeof e=="object")}const ob=document.createElement("i");function Wd(e){const t="&"+e+";";ob.innerHTML=t;const r=ob.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function Vn(e,t,r,s){const l=e.length;let u=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);u<s.length;)c=s.slice(u,u+1e4),c.unshift(t,0),e.splice(...c),u+=1e4,t+=1e4}function ur(e,t){return e.length>0?(Vn(e,e.length,0,t),e):t}const ub={}.hasOwnProperty;function r1(e){const t={};let r=-1;for(;++r<e.length;)KC(t,e[r]);return t}function KC(e,t){let r;for(r in t){const l=(ub.call(e,r)?e[r]:void 0)||(e[r]={}),u=t[r];let c;if(u)for(c in u){ub.call(l,c)||(l[c]=[]);const f=u[c];QC(l[c],Array.isArray(f)?f:f?[f]:[])}}}function QC(e,t){let r=-1;const s=[];for(;++r<t.length;)(t[r].add==="after"?e:s).push(t[r]);Vn(e,0,0,s)}function i1(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 wr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const _n=Fi(/[A-Za-z]/),mn=Fi(/[\dA-Za-z]/),ZC=Fi(/[#-'*+\--9=?A-Z^-~]/);function Pu(e){return e!==null&&(e<32||e===127)}const vd=Fi(/\d/),WC=Fi(/[\dA-Fa-f]/),eA=Fi(/[!-/:-@[-`{-~]/);function He(e){return e!==null&&e<-2}function jt(e){return e!==null&&(e<0||e===32)}function st(e){return e===-2||e===-1||e===32}const Zu=Fi(new RegExp("\\p{P}|\\p{S}","u")),gs=Fi(/\s/);function Fi(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function ka(e){const t=[];let r=-1,s=0,l=0;for(;++r<e.length;){const u=e.charCodeAt(r);let c="";if(u===37&&mn(e.charCodeAt(r+1))&&mn(e.charCodeAt(r+2)))l=2;else if(u<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(u))||(c=String.fromCharCode(u));else if(u>55295&&u<57344){const f=e.charCodeAt(r+1);u<56320&&f>56319&&f<57344?(c=String.fromCharCode(u,f),l=1):c="�"}else c=String.fromCharCode(u);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 ct(e,t,r,s){const l=s?s-1:Number.POSITIVE_INFINITY;let u=0;return c;function c(d){return st(d)?(e.enter(r),f(d)):t(d)}function f(d){return st(d)&&u++<l?(e.consume(d),f):(e.exit(r),t(d))}}const tA={tokenize:nA};function nA(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"),ct(e,t,"linePrefix")}function l(f){return e.enter("paragraph"),u(f)}function u(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 He(f)?(e.consume(f),e.exit("chunkText"),u):(e.consume(f),c)}}const rA={tokenize:iA},cb={tokenize:sA};function iA(e){const t=this,r=[];let s=0,l,u,c;return f;function f(F){if(s<r.length){const fe=r[s];return t.containerState=fe[1],e.attempt(fe[0].continuation,d,m)(F)}return m(F)}function d(F){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,l&&H();const fe=t.events.length;let z=fe,R;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){R=t.events[z][1].end;break}N(s);let ee=fe;for(;ee<t.events.length;)t.events[ee][1].end={...R},ee++;return Vn(t.events,z+1,0,t.events.slice(fe)),t.events.length=ee,m(F)}return f(F)}function m(F){if(s===r.length){if(!l)return x(F);if(l.currentConstruct&&l.currentConstruct.concrete)return _(F);t.interrupt=!!(l.currentConstruct&&!l._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(cb,y,g)(F)}function y(F){return l&&H(),N(s),x(F)}function g(F){return t.parser.lazy[t.now().line]=s!==r.length,c=t.now().offset,_(F)}function x(F){return t.containerState={},e.attempt(cb,w,_)(F)}function w(F){return s++,r.push([t.currentConstruct,t.containerState]),x(F)}function _(F){if(F===null){l&&H(),N(0),e.consume(F);return}return l=l||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:l,contentType:"flow",previous:u}),j(F)}function j(F){if(F===null){D(e.exit("chunkFlow"),!0),N(0),e.consume(F);return}return He(F)?(e.consume(F),D(e.exit("chunkFlow")),s=0,t.interrupt=void 0,f):(e.consume(F),j)}function D(F,fe){const z=t.sliceStream(F);if(fe&&z.push(null),F.previous=u,u&&(u.next=F),u=F,l.defineSkip(F.start),l.write(z),t.parser.lazy[F.start.line]){let R=l.events.length;for(;R--;)if(l.events[R][1].start.offset<c&&(!l.events[R][1].end||l.events[R][1].end.offset>c))return;const ee=t.events.length;let $=ee,q,L;for(;$--;)if(t.events[$][0]==="exit"&&t.events[$][1].type==="chunkFlow"){if(q){L=t.events[$][1].end;break}q=!0}for(N(s),R=ee;R<t.events.length;)t.events[R][1].end={...L},R++;Vn(t.events,$+1,0,t.events.slice(ee)),t.events.length=R}}function N(F){let fe=r.length;for(;fe-- >F;){const z=r[fe];t.containerState=z[1],z[0].exit.call(t,e)}r.length=F}function H(){l.write([null]),u=void 0,l=void 0,t.containerState._closeFlow=void 0}}function sA(e,t,r){return ct(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ba(e){if(e===null||jt(e)||gs(e))return 1;if(Zu(e))return 2}function Wu(e,t,r){const s=[];let l=-1;for(;++l<e.length;){const u=e[l].resolveAll;u&&!s.includes(u)&&(t=u(t,r),s.push(u))}return t}const wd={name:"attention",resolveAll:aA,tokenize:lA};function aA(e,t){let r=-1,s,l,u,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};fb(g,-d),fb(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},u={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=ur(m,[["enter",e[s][1],t],["exit",e[s][1],t]])),m=ur(m,[["enter",l,t],["enter",c,t],["exit",c,t],["enter",u,t]]),m=ur(m,Wu(t.parser.constructs.insideSpan.null,e.slice(s+1,r),t)),m=ur(m,[["exit",u,t],["enter",f,t],["exit",f,t],["exit",l,t]]),e[r][1].end.offset-e[r][1].start.offset?(y=2,m=ur(m,[["enter",e[r][1],t],["exit",e[r][1],t]])):y=0,Vn(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 lA(e,t){const r=this.parser.constructs.attentionMarkers.null,s=this.previous,l=ba(s);let u;return c;function c(d){return u=d,e.enter("attentionSequence"),f(d)}function f(d){if(d===u)return e.consume(d),f;const m=e.exit("attentionSequence"),y=ba(d),g=!y||y===2&&l||r.includes(d),x=!l||l===2&&y||r.includes(s);return m._open=!!(u===42?g:g&&(l||!x)),m._close=!!(u===42?x:x&&(y||!g)),t(d)}}function fb(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const oA={name:"autolink",tokenize:uA};function uA(e,t,r){let s=0;return l;function l(w){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(w),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),u}function u(w){return _n(w)?(e.consume(w),c):w===64?r(w):m(w)}function c(w){return w===43||w===45||w===46||mn(w)?(s=1,f(w)):m(w)}function f(w){return w===58?(e.consume(w),s=0,d):(w===43||w===45||w===46||mn(w))&&s++<32?(e.consume(w),f):(s=0,m(w))}function d(w){return w===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(w),e.exit("autolinkMarker"),e.exit("autolink"),t):w===null||w===32||w===60||Pu(w)?r(w):(e.consume(w),d)}function m(w){return w===64?(e.consume(w),y):ZC(w)?(e.consume(w),m):r(w)}function y(w){return mn(w)?g(w):r(w)}function g(w){return w===46?(e.consume(w),s=0,y):w===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(w),e.exit("autolinkMarker"),e.exit("autolink"),t):x(w)}function x(w){if((w===45||mn(w))&&s++<63){const _=w===45?x:g;return e.consume(w),_}return r(w)}}const Jl={partial:!0,tokenize:cA};function cA(e,t,r){return s;function s(u){return st(u)?ct(e,l,"linePrefix")(u):l(u)}function l(u){return u===null||He(u)?t(u):r(u)}}const s1={continuation:{tokenize:hA},exit:dA,name:"blockQuote",tokenize:fA};function fA(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"),u}return r(c)}function u(c){return st(c)?(e.enter("blockQuotePrefixWhitespace"),e.consume(c),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(c))}}function hA(e,t,r){const s=this;return l;function l(c){return st(c)?ct(e,u,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c):u(c)}function u(c){return e.attempt(s1,t,r)(c)}}function dA(e){e.exit("blockQuote")}const a1={name:"characterEscape",tokenize:mA};function mA(e,t,r){return s;function s(u){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(u),e.exit("escapeMarker"),l}function l(u){return eA(u)?(e.enter("characterEscapeValue"),e.consume(u),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(u)}}const l1={name:"characterReference",tokenize:pA};function pA(e,t,r){const s=this;let l=0,u,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"),u=31,c=mn,y(g))}function m(g){return g===88||g===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(g),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),u=6,c=WC,y):(e.enter("characterReferenceValue"),u=7,c=vd,y(g))}function y(g){if(g===59&&l){const x=e.exit("characterReferenceValue");return c===mn&&!Wd(s.sliceSerialize(x))?r(g):(e.enter("characterReferenceMarker"),e.consume(g),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return c(g)&&l++<u?(e.consume(g),y):r(g)}}const hb={partial:!0,tokenize:yA},db={concrete:!0,name:"codeFenced",tokenize:gA};function gA(e,t,r){const s=this,l={partial:!0,tokenize:z};let u=0,c=0,f;return d;function d(R){return m(R)}function m(R){const ee=s.events[s.events.length-1];return u=ee&&ee[1].type==="linePrefix"?ee[2].sliceSerialize(ee[1],!0).length:0,f=R,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),y(R)}function y(R){return R===f?(c++,e.consume(R),y):c<3?r(R):(e.exit("codeFencedFenceSequence"),st(R)?ct(e,g,"whitespace")(R):g(R))}function g(R){return R===null||He(R)?(e.exit("codeFencedFence"),s.interrupt?t(R):e.check(hb,j,fe)(R)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),x(R))}function x(R){return R===null||He(R)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),g(R)):st(R)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ct(e,w,"whitespace")(R)):R===96&&R===f?r(R):(e.consume(R),x)}function w(R){return R===null||He(R)?g(R):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),_(R))}function _(R){return R===null||He(R)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),g(R)):R===96&&R===f?r(R):(e.consume(R),_)}function j(R){return e.attempt(l,fe,D)(R)}function D(R){return e.enter("lineEnding"),e.consume(R),e.exit("lineEnding"),N}function N(R){return u>0&&st(R)?ct(e,H,"linePrefix",u+1)(R):H(R)}function H(R){return R===null||He(R)?e.check(hb,j,fe)(R):(e.enter("codeFlowValue"),F(R))}function F(R){return R===null||He(R)?(e.exit("codeFlowValue"),H(R)):(e.consume(R),F)}function fe(R){return e.exit("codeFenced"),t(R)}function z(R,ee,$){let q=0;return L;function L(K){return R.enter("lineEnding"),R.consume(K),R.exit("lineEnding"),G}function G(K){return R.enter("codeFencedFence"),st(K)?ct(R,J,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(K):J(K)}function J(K){return K===f?(R.enter("codeFencedFenceSequence"),oe(K)):$(K)}function oe(K){return K===f?(q++,R.consume(K),oe):q>=c?(R.exit("codeFencedFenceSequence"),st(K)?ct(R,le,"whitespace")(K):le(K)):$(K)}function le(K){return K===null||He(K)?(R.exit("codeFencedFence"),ee(K)):$(K)}}}function yA(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"),u)}function u(c){return s.parser.lazy[s.now().line]?r(c):t(c)}}const zh={name:"codeIndented",tokenize:xA},bA={partial:!0,tokenize:vA};function xA(e,t,r){const s=this;return l;function l(m){return e.enter("codeIndented"),ct(e,u,"linePrefix",5)(m)}function u(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):He(m)?e.attempt(bA,c,d)(m):(e.enter("codeFlowValue"),f(m))}function f(m){return m===null||He(m)?(e.exit("codeFlowValue"),c(m)):(e.consume(m),f)}function d(m){return e.exit("codeIndented"),t(m)}}function vA(e,t,r){const s=this;return l;function l(c){return s.parser.lazy[s.now().line]?r(c):He(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):ct(e,u,"linePrefix",5)(c)}function u(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):He(c)?l(c):r(c)}}const wA={name:"codeText",previous:_A,resolve:SA,tokenize:kA};function SA(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 _A(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function kA(e,t,r){let s=0,l,u;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?(u=e.enter("codeTextSequence"),l=0,y(g)):He(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||He(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)):(u.type="codeTextData",m(g))}}class EA{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 u=this.right.splice(this.right.length-l,Number.POSITIVE_INFINITY);return s&&Sl(this.left,s),u.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),Sl(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Sl(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);Sl(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Sl(this.left,r.reverse())}}}function Sl(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 o1(e){const t={};let r=-1,s,l,u,c,f,d,m;const y=new EA(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,u=0,u<d.length&&d[u][1].type==="lineEndingBlank"&&(u+=2),u<d.length&&d[u][1].type==="content"))for(;++u<d.length&&d[u][1].type!=="content";)d[u][1].type==="chunkText"&&(d[u][1]._isInFirstContentOfListItem=!0,u++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,CA(y,r)),r=t[r],m=!0);else if(s[1]._container){for(u=r,l=void 0;u--;)if(c=y.get(u),c[1].type==="lineEnding"||c[1].type==="lineEndingBlank")c[0]==="enter"&&(l&&(y.get(l)[1].type="lineEndingBlank"),c[1].type="lineEnding",l=u);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 Vn(e,0,Number.POSITIVE_INFINITY,y.slice(0)),!m}function CA(e,t){const r=e.get(t)[1],s=e.get(t)[2];let l=t-1;const u=[];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,w=r,_=0,j=0;const D=[j];for(;w;){for(;e.get(++l)[1]!==w;);u.push(l),w._tokenizer||(y=s.sliceStream(w),w.next||y.push(null),g&&c.defineSkip(w.start),w._isInFirstContentOfListItem&&(c._gfmTasklistFirstContentOfListItem=!0),c.write(y),w._isInFirstContentOfListItem&&(c._gfmTasklistFirstContentOfListItem=void 0)),g=w,w=w.next}for(w=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),w._tokenizer=void 0,w.previous=void 0,w=w.next);for(c.events=[],w?(w._tokenizer=void 0,w.previous=void 0):D.pop(),x=D.length;x--;){const N=f.slice(D[x],D[x+1]),H=u.pop();d.push([H,H+N.length-1]),e.splice(H,2,N)}for(d.reverse(),x=-1;++x<d.length;)m[_+d[x][0]]=_+d[x][1],_+=d[x][1]-d[x][0]-1;return m}const AA={resolve:jA,tokenize:NA},TA={partial:!0,tokenize:OA};function jA(e){return o1(e),e}function NA(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?u(f):He(f)?e.check(TA,c,u)(f):(e.consume(f),l)}function u(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 OA(e,t,r){const s=this;return l;function l(c){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),ct(e,u,"linePrefix")}function u(c){if(c===null||He(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 u1(e,t,r,s,l,u,c,f,d){const m=d||Number.POSITIVE_INFINITY;let y=0;return g;function g(N){return N===60?(e.enter(s),e.enter(l),e.enter(u),e.consume(N),e.exit(u),x):N===null||N===32||N===41||Pu(N)?r(N):(e.enter(s),e.enter(c),e.enter(f),e.enter("chunkString",{contentType:"string"}),j(N))}function x(N){return N===62?(e.enter(u),e.consume(N),e.exit(u),e.exit(l),e.exit(s),t):(e.enter(f),e.enter("chunkString",{contentType:"string"}),w(N))}function w(N){return N===62?(e.exit("chunkString"),e.exit(f),x(N)):N===null||N===60||He(N)?r(N):(e.consume(N),N===92?_:w)}function _(N){return N===60||N===62||N===92?(e.consume(N),w):w(N)}function j(N){return!y&&(N===null||N===41||jt(N))?(e.exit("chunkString"),e.exit(f),e.exit(c),e.exit(s),t(N)):y<m&&N===40?(e.consume(N),y++,j):N===41?(e.consume(N),y--,j):N===null||N===32||N===40||Pu(N)?r(N):(e.consume(N),N===92?D:j)}function D(N){return N===40||N===41||N===92?(e.consume(N),j):j(N)}}function c1(e,t,r,s,l,u){const c=this;let f=0,d;return m;function m(w){return e.enter(s),e.enter(l),e.consume(w),e.exit(l),e.enter(u),y}function y(w){return f>999||w===null||w===91||w===93&&!d||w===94&&!f&&"_hiddenFootnoteSupport"in c.parser.constructs?r(w):w===93?(e.exit(u),e.enter(l),e.consume(w),e.exit(l),e.exit(s),t):He(w)?(e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),y):(e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||w===91||w===93||He(w)||f++>999?(e.exit("chunkString"),y(w)):(e.consume(w),d||(d=!st(w)),w===92?x:g)}function x(w){return w===91||w===92||w===93?(e.consume(w),f++,g):g(w)}}function f1(e,t,r,s,l,u){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(u),m(x))}function m(x){return x===c?(e.exit(u),d(c)):x===null?r(x):He(x)?(e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),ct(e,m,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),y(x))}function y(x){return x===c||x===null||He(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 Ml(e,t){let r;return s;function s(l){return He(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r=!0,s):st(l)?ct(e,s,r?"linePrefix":"lineSuffix")(l):t(l)}}const RA={name:"definition",tokenize:DA},MA={partial:!0,tokenize:LA};function DA(e,t,r){const s=this;let l;return u;function u(w){return e.enter("definition"),c(w)}function c(w){return c1.call(s,e,f,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(w)}function f(w){return l=wr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),w===58?(e.enter("definitionMarker"),e.consume(w),e.exit("definitionMarker"),d):r(w)}function d(w){return jt(w)?Ml(e,m)(w):m(w)}function m(w){return u1(e,y,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(w)}function y(w){return e.attempt(MA,g,g)(w)}function g(w){return st(w)?ct(e,x,"whitespace")(w):x(w)}function x(w){return w===null||He(w)?(e.exit("definition"),s.parser.defined.push(l),t(w)):r(w)}}function LA(e,t,r){return s;function s(f){return jt(f)?Ml(e,l)(f):r(f)}function l(f){return f1(e,u,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(f)}function u(f){return st(f)?ct(e,c,"whitespace")(f):c(f)}function c(f){return f===null||He(f)?t(f):r(f)}}const zA={name:"hardBreakEscape",tokenize:UA};function UA(e,t,r){return s;function s(u){return e.enter("hardBreakEscape"),e.consume(u),l}function l(u){return He(u)?(e.exit("hardBreakEscape"),t(u)):r(u)}}const BA={name:"headingAtx",resolve:PA,tokenize:HA};function PA(e,t){let r=e.length-2,s=3,l,u;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},u={type:"chunkText",start:e[s][1].start,end:e[r][1].end,contentType:"text"},Vn(e,s,r-s+1,[["enter",l,t],["enter",u,t],["exit",u,t],["exit",l,t]])),e}function HA(e,t,r){let s=0;return l;function l(y){return e.enter("atxHeading"),u(y)}function u(y){return e.enter("atxHeadingSequence"),c(y)}function c(y){return y===35&&s++<6?(e.consume(y),c):y===null||jt(y)?(e.exit("atxHeadingSequence"),f(y)):r(y)}function f(y){return y===35?(e.enter("atxHeadingSequence"),d(y)):y===null||He(y)?(e.exit("atxHeading"),t(y)):st(y)?ct(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||jt(y)?(e.exit("atxHeadingText"),f(y)):(e.consume(y),m)}}const qA=["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"],mb=["pre","script","style","textarea"],IA={concrete:!0,name:"htmlFlow",resolveTo:YA,tokenize:VA},FA={partial:!0,tokenize:JA},$A={partial:!0,tokenize:GA};function YA(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 VA(e,t,r){const s=this;let l,u,c,f,d;return m;function m(S){return y(S)}function y(S){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(S),g}function g(S){return S===33?(e.consume(S),x):S===47?(e.consume(S),u=!0,j):S===63?(e.consume(S),l=3,s.interrupt?t:M):_n(S)?(e.consume(S),c=String.fromCharCode(S),D):r(S)}function x(S){return S===45?(e.consume(S),l=2,w):S===91?(e.consume(S),l=5,f=0,_):_n(S)?(e.consume(S),l=4,s.interrupt?t:M):r(S)}function w(S){return S===45?(e.consume(S),s.interrupt?t:M):r(S)}function _(S){const xe="CDATA[";return S===xe.charCodeAt(f++)?(e.consume(S),f===xe.length?s.interrupt?t:J:_):r(S)}function j(S){return _n(S)?(e.consume(S),c=String.fromCharCode(S),D):r(S)}function D(S){if(S===null||S===47||S===62||jt(S)){const xe=S===47,Ae=c.toLowerCase();return!xe&&!u&&mb.includes(Ae)?(l=1,s.interrupt?t(S):J(S)):qA.includes(c.toLowerCase())?(l=6,xe?(e.consume(S),N):s.interrupt?t(S):J(S)):(l=7,s.interrupt&&!s.parser.lazy[s.now().line]?r(S):u?H(S):F(S))}return S===45||mn(S)?(e.consume(S),c+=String.fromCharCode(S),D):r(S)}function N(S){return S===62?(e.consume(S),s.interrupt?t:J):r(S)}function H(S){return st(S)?(e.consume(S),H):L(S)}function F(S){return S===47?(e.consume(S),L):S===58||S===95||_n(S)?(e.consume(S),fe):st(S)?(e.consume(S),F):L(S)}function fe(S){return S===45||S===46||S===58||S===95||mn(S)?(e.consume(S),fe):z(S)}function z(S){return S===61?(e.consume(S),R):st(S)?(e.consume(S),z):F(S)}function R(S){return S===null||S===60||S===61||S===62||S===96?r(S):S===34||S===39?(e.consume(S),d=S,ee):st(S)?(e.consume(S),R):$(S)}function ee(S){return S===d?(e.consume(S),d=null,q):S===null||He(S)?r(S):(e.consume(S),ee)}function $(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||jt(S)?z(S):(e.consume(S),$)}function q(S){return S===47||S===62||st(S)?F(S):r(S)}function L(S){return S===62?(e.consume(S),G):r(S)}function G(S){return S===null||He(S)?J(S):st(S)?(e.consume(S),G):r(S)}function J(S){return S===45&&l===2?(e.consume(S),U):S===60&&l===1?(e.consume(S),W):S===62&&l===4?(e.consume(S),P):S===63&&l===3?(e.consume(S),M):S===93&&l===5?(e.consume(S),we):He(S)&&(l===6||l===7)?(e.exit("htmlFlowData"),e.check(FA,te,oe)(S)):S===null||He(S)?(e.exit("htmlFlowData"),oe(S)):(e.consume(S),J)}function oe(S){return e.check($A,le,te)(S)}function le(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),K}function K(S){return S===null||He(S)?oe(S):(e.enter("htmlFlowData"),J(S))}function U(S){return S===45?(e.consume(S),M):J(S)}function W(S){return S===47?(e.consume(S),c="",ue):J(S)}function ue(S){if(S===62){const xe=c.toLowerCase();return mb.includes(xe)?(e.consume(S),P):J(S)}return _n(S)&&c.length<8?(e.consume(S),c+=String.fromCharCode(S),ue):J(S)}function we(S){return S===93?(e.consume(S),M):J(S)}function M(S){return S===62?(e.consume(S),P):S===45&&l===2?(e.consume(S),M):J(S)}function P(S){return S===null||He(S)?(e.exit("htmlFlowData"),te(S)):(e.consume(S),P)}function te(S){return e.exit("htmlFlow"),t(S)}}function GA(e,t,r){const s=this;return l;function l(c){return He(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),u):r(c)}function u(c){return s.parser.lazy[s.now().line]?r(c):t(c)}}function JA(e,t,r){return s;function s(l){return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),e.attempt(Jl,t,r)}}const XA={name:"htmlText",tokenize:KA};function KA(e,t,r){const s=this;let l,u,c;return f;function f(M){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(M),d}function d(M){return M===33?(e.consume(M),m):M===47?(e.consume(M),z):M===63?(e.consume(M),F):_n(M)?(e.consume(M),$):r(M)}function m(M){return M===45?(e.consume(M),y):M===91?(e.consume(M),u=0,_):_n(M)?(e.consume(M),H):r(M)}function y(M){return M===45?(e.consume(M),w):r(M)}function g(M){return M===null?r(M):M===45?(e.consume(M),x):He(M)?(c=g,W(M)):(e.consume(M),g)}function x(M){return M===45?(e.consume(M),w):g(M)}function w(M){return M===62?U(M):M===45?x(M):g(M)}function _(M){const P="CDATA[";return M===P.charCodeAt(u++)?(e.consume(M),u===P.length?j:_):r(M)}function j(M){return M===null?r(M):M===93?(e.consume(M),D):He(M)?(c=j,W(M)):(e.consume(M),j)}function D(M){return M===93?(e.consume(M),N):j(M)}function N(M){return M===62?U(M):M===93?(e.consume(M),N):j(M)}function H(M){return M===null||M===62?U(M):He(M)?(c=H,W(M)):(e.consume(M),H)}function F(M){return M===null?r(M):M===63?(e.consume(M),fe):He(M)?(c=F,W(M)):(e.consume(M),F)}function fe(M){return M===62?U(M):F(M)}function z(M){return _n(M)?(e.consume(M),R):r(M)}function R(M){return M===45||mn(M)?(e.consume(M),R):ee(M)}function ee(M){return He(M)?(c=ee,W(M)):st(M)?(e.consume(M),ee):U(M)}function $(M){return M===45||mn(M)?(e.consume(M),$):M===47||M===62||jt(M)?q(M):r(M)}function q(M){return M===47?(e.consume(M),U):M===58||M===95||_n(M)?(e.consume(M),L):He(M)?(c=q,W(M)):st(M)?(e.consume(M),q):U(M)}function L(M){return M===45||M===46||M===58||M===95||mn(M)?(e.consume(M),L):G(M)}function G(M){return M===61?(e.consume(M),J):He(M)?(c=G,W(M)):st(M)?(e.consume(M),G):q(M)}function J(M){return M===null||M===60||M===61||M===62||M===96?r(M):M===34||M===39?(e.consume(M),l=M,oe):He(M)?(c=J,W(M)):st(M)?(e.consume(M),J):(e.consume(M),le)}function oe(M){return M===l?(e.consume(M),l=void 0,K):M===null?r(M):He(M)?(c=oe,W(M)):(e.consume(M),oe)}function le(M){return M===null||M===34||M===39||M===60||M===61||M===96?r(M):M===47||M===62||jt(M)?q(M):(e.consume(M),le)}function K(M){return M===47||M===62||jt(M)?q(M):r(M)}function U(M){return M===62?(e.consume(M),e.exit("htmlTextData"),e.exit("htmlText"),t):r(M)}function W(M){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),ue}function ue(M){return st(M)?ct(e,we,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):we(M)}function we(M){return e.enter("htmlTextData"),c(M)}}const em={name:"labelEnd",resolveAll:eT,resolveTo:tT,tokenize:nT},QA={tokenize:rT},ZA={tokenize:iT},WA={tokenize:sT};function eT(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&&Vn(e,0,e.length,r),e}function tT(e,t){let r=e.length,s=0,l,u,c,f;for(;r--;)if(l=e[r][1],u){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&&(u=r,l.type!=="labelLink")){s=2;break}}else l.type==="labelEnd"&&(c=r);const d={type:e[u][1].type==="labelLink"?"link":"image",start:{...e[u][1].start},end:{...e[e.length-1][1].end}},m={type:"label",start:{...e[u][1].start},end:{...e[c][1].end}},y={type:"labelText",start:{...e[u+s+2][1].end},end:{...e[c-2][1].start}};return f=[["enter",d,t],["enter",m,t]],f=ur(f,e.slice(u+1,u+s+3)),f=ur(f,[["enter",y,t]]),f=ur(f,Wu(t.parser.constructs.insideSpan.null,e.slice(u+s+4,c-3),t)),f=ur(f,[["exit",y,t],e[c-2],e[c-1],["exit",m,t]]),f=ur(f,e.slice(c+1)),f=ur(f,[["exit",d,t]]),Vn(e,u,e.length,f),e}function nT(e,t,r){const s=this;let l=s.events.length,u,c;for(;l--;)if((s.events[l][1].type==="labelImage"||s.events[l][1].type==="labelLink")&&!s.events[l][1]._balanced){u=s.events[l][1];break}return f;function f(x){return u?u._inactive?g(x):(c=s.parser.defined.includes(wr(s.sliceSerialize({start:u.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(QA,y,c?y:g)(x):x===91?e.attempt(ZA,y,c?m:g)(x):c?y(x):g(x)}function m(x){return e.attempt(WA,y,g)(x)}function y(x){return t(x)}function g(x){return u._balanced=!0,r(x)}}function rT(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 jt(g)?Ml(e,u)(g):u(g)}function u(g){return g===41?y(g):u1(e,c,f,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(g)}function c(g){return jt(g)?Ml(e,d)(g):y(g)}function f(g){return r(g)}function d(g){return g===34||g===39||g===40?f1(e,m,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(g):y(g)}function m(g){return jt(g)?Ml(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 iT(e,t,r){const s=this;return l;function l(f){return c1.call(s,e,u,c,"reference","referenceMarker","referenceString")(f)}function u(f){return s.parser.defined.includes(wr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(f):r(f)}function c(f){return r(f)}}function sT(e,t,r){return s;function s(u){return e.enter("reference"),e.enter("referenceMarker"),e.consume(u),e.exit("referenceMarker"),l}function l(u){return u===93?(e.enter("referenceMarker"),e.consume(u),e.exit("referenceMarker"),e.exit("reference"),t):r(u)}}const aT={name:"labelStartImage",resolveAll:em.resolveAll,tokenize:lT};function lT(e,t,r){const s=this;return l;function l(f){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(f),e.exit("labelImageMarker"),u}function u(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 oT={name:"labelStartLink",resolveAll:em.resolveAll,tokenize:uT};function uT(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"),u}function u(c){return c===94&&"_hiddenFootnoteSupport"in s.parser.constructs?r(c):t(c)}}const Uh={name:"lineEnding",tokenize:cT};function cT(e,t){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ct(e,t,"linePrefix")}}const Cu={name:"thematicBreak",tokenize:fT};function fT(e,t,r){let s=0,l;return u;function u(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||He(m))?(e.exit("thematicBreak"),t(m)):r(m)}function d(m){return m===l?(e.consume(m),s++,d):(e.exit("thematicBreakSequence"),st(m)?ct(e,f,"whitespace")(m):f(m))}}const On={continuation:{tokenize:pT},exit:yT,name:"list",tokenize:mT},hT={partial:!0,tokenize:bT},dT={partial:!0,tokenize:gT};function mT(e,t,r){const s=this,l=s.events[s.events.length-1];let u=l&&l[1].type==="linePrefix"?l[2].sliceSerialize(l[1],!0).length:0,c=0;return f;function f(w){const _=s.containerState.type||(w===42||w===43||w===45?"listUnordered":"listOrdered");if(_==="listUnordered"?!s.containerState.marker||w===s.containerState.marker:vd(w)){if(s.containerState.type||(s.containerState.type=_,e.enter(_,{_container:!0})),_==="listUnordered")return e.enter("listItemPrefix"),w===42||w===45?e.check(Cu,r,m)(w):m(w);if(!s.interrupt||w===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(w)}return r(w)}function d(w){return vd(w)&&++c<10?(e.consume(w),d):(!s.interrupt||c<2)&&(s.containerState.marker?w===s.containerState.marker:w===41||w===46)?(e.exit("listItemValue"),m(w)):r(w)}function m(w){return e.enter("listItemMarker"),e.consume(w),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||w,e.check(Jl,s.interrupt?r:y,e.attempt(hT,x,g))}function y(w){return s.containerState.initialBlankLine=!0,u++,x(w)}function g(w){return st(w)?(e.enter("listItemPrefixWhitespace"),e.consume(w),e.exit("listItemPrefixWhitespace"),x):r(w)}function x(w){return s.containerState.size=u+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(w)}}function pT(e,t,r){const s=this;return s.containerState._closeFlow=void 0,e.check(Jl,l,u);function l(f){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,ct(e,t,"listItemIndent",s.containerState.size+1)(f)}function u(f){return s.containerState.furtherBlankLines||!st(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(dT,t,c)(f))}function c(f){return s.containerState._closeFlow=!0,s.interrupt=void 0,ct(e,e.attempt(On,t,r),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(f)}}function gT(e,t,r){const s=this;return ct(e,l,"listItemIndent",s.containerState.size+1);function l(u){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(u):r(u)}}function yT(e){e.exit(this.containerState.type)}function bT(e,t,r){const s=this;return ct(e,l,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function l(u){const c=s.events[s.events.length-1];return!st(u)&&c&&c[1].type==="listItemPrefixWhitespace"?t(u):r(u)}}const pb={name:"setextUnderline",resolveTo:xT,tokenize:vT};function xT(e,t){let r=e.length,s,l,u;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),!u&&e[r][1].type==="definition"&&(u=r);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[l][1].type="setextHeadingText",u?(e.splice(l,0,["enter",c,t]),e.splice(u+1,0,["exit",e[s][1],t]),e[s][1].end={...e[u][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function vT(e,t,r){const s=this;let l;return u;function u(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"),st(m)?ct(e,d,"lineSuffix")(m):d(m))}function d(m){return m===null||He(m)?(e.exit("setextHeadingLine"),t(m)):r(m)}}const wT={tokenize:ST};function ST(e){const t=this,r=e.attempt(Jl,s,e.attempt(this.parser.constructs.flowInitial,l,ct(e,e.attempt(this.parser.constructs.flow,l,e.attempt(AA,l)),"linePrefix")));return r;function s(u){if(u===null){e.consume(u);return}return e.enter("lineEndingBlank"),e.consume(u),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function l(u){if(u===null){e.consume(u);return}return e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const _T={resolveAll:d1()},kT=h1("string"),ET=h1("text");function h1(e){return{resolveAll:d1(e==="text"?CT:void 0),tokenize:t};function t(r){const s=this,l=this.parser.constructs[e],u=r.attempt(l,c,f);return c;function c(y){return m(y)?u(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"),u(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 w=g[x];if(!w.previous||w.previous.call(s,s.previous))return!0}return!1}}}function d1(e){return t;function t(r,s){let l=-1,u;for(;++l<=r.length;)u===void 0?r[l]&&r[l][1].type==="data"&&(u=l,l++):(!r[l]||r[l][1].type!=="data")&&(l!==u+2&&(r[u][1].end=r[l-1][1].end,r.splice(u+2,l-u-2),l=u+2),u=void 0);return e?e(r,s):r}}function CT(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 u=l.length,c=-1,f=0,d;for(;u--;){const m=l[u];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){u++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(f=0),f){const m={type:r===e.length||d||f<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:u?c:s.start._bufferIndex+c,_index:s.start._index+u,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 AT={42:On,43:On,45:On,48:On,49:On,50:On,51:On,52:On,53:On,54:On,55:On,56:On,57:On,62:s1},TT={91:RA},jT={[-2]:zh,[-1]:zh,32:zh},NT={35:BA,42:Cu,45:[pb,Cu],60:IA,61:pb,95:Cu,96:db,126:db},OT={38:l1,92:a1},RT={[-5]:Uh,[-4]:Uh,[-3]:Uh,33:aT,38:l1,42:wd,60:[oA,XA],91:oT,92:[zA,a1],93:em,95:wd,96:wA},MT={null:[wd,_T]},DT={null:[42,95]},LT={null:[]},zT=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:DT,contentInitial:TT,disable:LT,document:AT,flow:NT,flowInitial:jT,insideSpan:MT,string:OT,text:RT},Symbol.toStringTag,{value:"Module"}));function UT(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={},u=[];let c=[],f=[];const d={attempt:ee(z),check:ee(R),consume:H,enter:F,exit:fe,interrupt:ee(R,{interrupt:!0})},m={code:null,containerState:{},defineSkip:j,events:[],now:_,parser:e,previous:null,sliceSerialize:x,sliceStream:w,write:g};let y=t.tokenize.call(m,d);return t.resolveAll&&u.push(t),m;function g(G){return c=ur(c,G),D(),c[c.length-1]!==null?[]:($(t,0),m.events=Wu(u,m.events,m),m.events)}function x(G,J){return PT(w(G),J)}function w(G){return BT(c,G)}function _(){const{_bufferIndex:G,_index:J,line:oe,column:le,offset:K}=s;return{_bufferIndex:G,_index:J,line:oe,column:le,offset:K}}function j(G){l[G.line]=G.column,L()}function D(){let G;for(;s._index<c.length;){const J=c[s._index];if(typeof J=="string")for(G=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===G&&s._bufferIndex<J.length;)N(J.charCodeAt(s._bufferIndex));else N(J)}}function N(G){y=y(G)}function H(G){He(G)?(s.line++,s.column=1,s.offset+=G===-3?2:1,L()):G!==-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=G}function F(G,J){const oe=J||{};return oe.type=G,oe.start=_(),m.events.push(["enter",oe,m]),f.push(oe),oe}function fe(G){const J=f.pop();return J.end=_(),m.events.push(["exit",J,m]),J}function z(G,J){$(G,J.from)}function R(G,J){J.restore()}function ee(G,J){return oe;function oe(le,K,U){let W,ue,we,M;return Array.isArray(le)?te(le):"tokenize"in le?te([le]):P(le);function P(ve){return Ue;function Ue(Ve){const Te=Ve!==null&&ve[Ve],et=Ve!==null&&ve.null,Pt=[...Array.isArray(Te)?Te:Te?[Te]:[],...Array.isArray(et)?et:et?[et]:[]];return te(Pt)(Ve)}}function te(ve){return W=ve,ue=0,ve.length===0?U:S(ve[ue])}function S(ve){return Ue;function Ue(Ve){return M=q(),we=ve,ve.partial||(m.currentConstruct=ve),ve.name&&m.parser.constructs.disable.null.includes(ve.name)?Ae():ve.tokenize.call(J?Object.assign(Object.create(m),J):m,d,xe,Ae)(Ve)}}function xe(ve){return G(we,M),K}function Ae(ve){return M.restore(),++ue<W.length?S(W[ue]):U}}}function $(G,J){G.resolveAll&&!u.includes(G)&&u.push(G),G.resolve&&Vn(m.events,J,m.events.length-J,G.resolve(m.events.slice(J),m)),G.resolveTo&&(m.events=G.resolveTo(m.events,m))}function q(){const G=_(),J=m.previous,oe=m.currentConstruct,le=m.events.length,K=Array.from(f);return{from:le,restore:U};function U(){s=G,m.previous=J,m.currentConstruct=oe,m.events.length=le,f=K,L()}}function L(){s.line in l&&s.column<2&&(s.column=l[s.line],s.offset+=l[s.line]-1)}}function BT(e,t){const r=t.start._index,s=t.start._bufferIndex,l=t.end._index,u=t.end._bufferIndex;let c;if(r===l)c=[e[r].slice(s,u)];else{if(c=e.slice(r,l),s>-1){const f=c[0];typeof f=="string"?c[0]=f.slice(s):c.shift()}u>0&&c.push(e[l].slice(0,u))}return c}function PT(e,t){let r=-1;const s=[];let l;for(;++r<e.length;){const u=e[r];let c;if(typeof u=="string")c=u;else switch(u){case-5:{c="\r";break}case-4:{c=`
@@ -117,4 +117,4 @@ Are you sure you want to continue?`):!0}async function fe(){if(!(!H||!F())){w(!0
117
117
  `))+1))}const c="#".repeat(l),f=r.enter("headingAtx"),d=r.enter("phrasing");u.move(c+" ");let m=r.containerPhrasing(e,{before:"# ",after:`
118
118
  `,...u.current()});return/^[\t ]/.test(m)&&(m=Il(m.charCodeAt(0))+m.slice(1)),m=m?c+" "+m:c,r.options.closeAtx&&(m+=" "+c),d(),f(),m}N1.peek=m3;function N1(e){return e.value||""}function m3(){return"<"}O1.peek=p3;function O1(e,t,r,s){const l=lm(r),u=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${u}`),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 p3(){return"!"}R1.peek=g3;function R1(e,t,r,s){const l=e.referenceType,u=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,u(),l==="full"||!m||m!==g?d+=f.move(g+"]"):l==="shortcut"?d=d.slice(0,-1):d+=f.move("]"),d}function g3(){return"!"}M1.peek=y3;function M1(e,t,r){let s=e.value||"",l="`",u=-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+" ");++u<r.unsafe.length;){const c=r.unsafe[u],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 y3(){return"`"}function D1(e,t){const r=Zd(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))}L1.peek=b3;function L1(e,t,r,s){const l=lm(r),u=l==='"'?"Quote":"Apostrophe",c=r.createTracker(s);let f,d;if(D1(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${u}`),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 b3(e,t,r){return D1(e,r)?"<":"["}z1.peek=x3;function z1(e,t,r,s){const l=e.referenceType,u=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,u(),l==="full"||!m||m!==g?d+=f.move(g+"]"):l==="shortcut"?d=d.slice(0,-1):d+=f.move("]"),d}function x3(){return"["}function om(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 v3(e){const t=om(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 w3(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 U1(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 S3(e,t,r,s){const l=r.enter("list"),u=r.bulletCurrent;let c=e.ordered?w3(r):om(r);const f=e.ordered?c==="."?")":".":v3(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),U1(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=u,l(),m}function _3(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 k3(e,t,r,s){const l=_3(r);let u=r.bulletCurrent||om(r);t&&t.type==="list"&&t.ordered&&(u=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+u);let c=u.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(u+" ".repeat(c-u.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,w){return x?(w?"":" ".repeat(c))+g:(w?u:u+" ".repeat(c-u.length))+g}}function E3(e,t,r,s){const l=r.enter("paragraph"),u=r.enter("phrasing"),c=r.containerPhrasing(e,s);return u(),l(),c}const C3=tc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function A3(e,t,r,s){return(e.children.some(function(c){return C3(c)})?r.containerPhrasing:r.containerFlow).call(r,e,s)}function T3(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}B1.peek=j3;function B1(e,t,r,s){const l=T3(r),u=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=Iu(s.before.charCodeAt(s.before.length-1),m,l);y.inside&&(d=Il(m)+d.slice(1));const g=d.charCodeAt(d.length-1),x=Iu(s.after.charCodeAt(0),g,l);x.inside&&(d=d.slice(0,-1)+Il(g));const w=c.move(l+l);return u(),r.attentionEncodeSurroundingInfo={after:x.outside,before:y.outside},f+d+w}function j3(e,t,r){return r.options.strong||"*"}function N3(e,t,r,s){return r.safe(e.value,s)}function O3(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 R3(e,t,r){const s=(U1(r)+(r.options.ruleSpaces?" ":"")).repeat(O3(r));return r.options.ruleSpaces?s.slice(0,-1):s}const P1={blockquote:t3,break:Ub,code:l3,definition:u3,emphasis:j1,hardBreak:Ub,heading:d3,html:N1,image:O1,imageReference:R1,inlineCode:M1,link:L1,linkReference:z1,list:S3,listItem:k3,paragraph:E3,root:A3,strong:B1,text:N3,thematicBreak:R3};function M3(){return{enter:{table:D3,tableData:Bb,tableHeader:Bb,tableRow:z3},exit:{codeText:U3,table:L3,tableData:Xh,tableHeader:Xh,tableRow:Xh}}}function D3(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 L3(e){this.exit(e),this.data.inTable=void 0}function z3(e){this.enter({type:"tableRow",children:[]},e)}function Xh(e){this.exit(e)}function Bb(e){this.enter({type:"tableCell",children:[]},e)}function U3(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,B3));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function B3(e,t){return t==="|"?t:e}function P3(e){const t=e||{},r=t.tableCellPadding,s=t.tablePipeAlign,l=t.stringLength,u=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
119
119
  `,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(w,_,j,D){return m(y(w,j,D),w.align)}function f(w,_,j,D){const N=g(w,j,D),H=m([N]);return H.slice(0,H.indexOf(`
120
- `))}function d(w,_,j,D){const N=j.enter("tableCell"),H=j.enter("phrasing"),F=j.containerPhrasing(w,{...D,before:u,after:u});return H(),N(),F}function m(w,_){return WN(w,{align:_,alignDelimiters:s,padding:r,stringLength:l})}function y(w,_,j){const D=w.children;let N=-1;const H=[],F=_.enter("table");for(;++N<D.length;)H[N]=g(D[N],_,j);return F(),H}function g(w,_,j){const D=w.children;let N=-1;const H=[],F=_.enter("tableRow");for(;++N<D.length;)H[N]=d(D[N],w,_,j);return F(),H}function x(w,_,j){let D=P1.inlineCode(w,_,j);return j.stack.includes("tableCell")&&(D=D.replace(/\|/g,"\\$&")),D}}function H3(){return{exit:{taskListCheckValueChecked:Pb,taskListCheckValueUnchecked:Pb,paragraph:I3}}}function q3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:F3}}}function Pb(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function I3(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 u=-1,c;for(;++u<l.length;){const f=l[u];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 F3(e,t,r,s){const l=e.children[0],u=typeof e.checked=="boolean"&&l&&l.type==="paragraph",c="["+(e.checked?"x":" ")+"] ",f=r.createTracker(s);u&&f.move(c);let d=P1.listItem(e,t,r,{...s,...f.current()});return u&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),d;function m(y){return y+c}}function $3(){return[SN(),FN(),GN(),M3(),H3()]}function Y3(e){return{extensions:[_N(),$N(e),JN(),P3(e),q3()]}}const V3={tokenize:Z3,partial:!0},H1={tokenize:W3,partial:!0},q1={tokenize:eO,partial:!0},I1={tokenize:tO,partial:!0},G3={tokenize:nO,partial:!0},F1={name:"wwwAutolink",tokenize:K3,previous:Y1},$1={name:"protocolAutolink",tokenize:Q3,previous:V1},ai={name:"emailAutolink",tokenize:X3,previous:G1},Dr={};function J3(){return{text:Dr}}let hs=48;for(;hs<123;)Dr[hs]=ai,hs++,hs===58?hs=65:hs===91&&(hs=97);Dr[43]=ai;Dr[45]=ai;Dr[46]=ai;Dr[95]=ai;Dr[72]=[ai,$1];Dr[104]=[ai,$1];Dr[87]=[ai,F1];Dr[119]=[ai,F1];function X3(e,t,r){const s=this;let l,u;return c;function c(g){return!Cd(g)||!G1.call(s,s.previous)||um(s.events)?r(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return Cd(g)?(e.consume(g),f):g===64?(e.consume(g),d):r(g)}function d(g){return g===46?e.check(G3,y,m)(g):g===45||g===95||mn(g)?(u=!0,e.consume(g),d):y(g)}function m(g){return e.consume(g),l=!0,d}function y(g){return u&&l&&_n(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):r(g)}}function K3(e,t,r){const s=this;return l;function l(c){return c!==87&&c!==119||!Y1.call(s,s.previous)||um(s.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(V3,e.attempt(H1,e.attempt(q1,u),r),r)(c))}function u(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function Q3(e,t,r){const s=this;let l="",u=!1;return c;function c(g){return(g===72||g===104)&&V1.call(s,s.previous)&&!um(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),l+=String.fromCodePoint(g),e.consume(g),f):r(g)}function f(g){if(_n(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),u?m:(u=!0,d)):r(g)}function m(g){return g===null||Pu(g)||jt(g)||gs(g)||Zu(g)?r(g):e.attempt(H1,e.attempt(q1,y),r)(g)}function y(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function Z3(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),u):r(c)}function u(c){return c===null?r(c):t(c)}}function W3(e,t,r){let s,l,u;return c;function c(m){return m===46||m===95?e.check(I1,d,f)(m):m===null||jt(m)||gs(m)||m!==45&&Zu(m)?d(m):(u=!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||!u?r(m):t(m)}}function eO(e,t){let r=0,s=0;return l;function l(c){return c===40?(r++,e.consume(c),l):c===41&&s<r?u(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(I1,t,u)(c):c===null||jt(c)||gs(c)?t(c):(e.consume(c),l)}function u(c){return c===41&&s++,e.consume(c),l}}function tO(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),u):f===93?(e.consume(f),l):f===60||f===null||jt(f)||gs(f)?t(f):r(f)}function l(f){return f===null||f===40||f===91||jt(f)||gs(f)?t(f):s(f)}function u(f){return _n(f)?c(f):r(f)}function c(f){return f===59?(e.consume(f),s):_n(f)?(e.consume(f),c):r(f)}}function nO(e,t,r){return s;function s(u){return e.consume(u),l}function l(u){return mn(u)?r(u):t(u)}}function Y1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||jt(e)}function V1(e){return!_n(e)}function G1(e){return!(e===47||Cd(e))}function Cd(e){return e===43||e===45||e===46||e===95||mn(e)}function um(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 rO={tokenize:fO,partial:!0};function iO(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:oO,continuation:{tokenize:uO},exit:cO}},text:{91:{name:"gfmFootnoteCall",tokenize:lO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:sO,resolveTo:aO}}}}function sO(e,t,r){const s=this;let l=s.events.length;const u=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=wr(s.sliceSerialize({start:c.end,end:s.now()}));return m.codePointAt(0)!==94||!u.includes(m.slice(1))?r(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),t(d))}}function aO(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 u={type:"gfmFootnoteCallString",start:Object.assign({},l.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},u.start),end:Object.assign({},u.end)},f=[e[r+1],e[r+2],["enter",s,t],e[r+3],e[r+4],["enter",l,t],["exit",l,t],["enter",u,t],["enter",c,t],["exit",c,t],["exit",u,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(r,e.length-r+1,...f),e}function lO(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u=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(u>999||g===93&&!c||g===null||g===91||jt(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return l.includes(wr(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(g)}return jt(g)||(c=!0),u++,e.consume(g),g===92?y:m}function y(g){return g===91||g===92||g===93?(e.consume(g),u++,m):m(g)}}function oO(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u,c=0,f;return d;function d(_){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionLabelMarker"),m}function m(_){return _===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",y):r(_)}function y(_){if(c>999||_===93&&!f||_===null||_===91||jt(_))return r(_);if(_===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return u=wr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return jt(_)||(f=!0),c++,e.consume(_),_===92?g:y}function g(_){return _===91||_===92||_===93?(e.consume(_),c++,y):y(_)}function x(_){return _===58?(e.enter("definitionMarker"),e.consume(_),e.exit("definitionMarker"),l.includes(u)||l.push(u),ct(e,w,"gfmFootnoteDefinitionWhitespace")):r(_)}function w(_){return t(_)}}function uO(e,t,r){return e.check(Jl,t,e.attempt(rO,t,r))}function cO(e){e.exit("gfmFootnoteDefinition")}function fO(e,t,r){const s=this;return ct(e,l,"gfmFootnoteDefinitionIndent",5);function l(u){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(u):r(u)}}function hO(e){let r=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:u,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]],w=f.parser.constructs.insideSpan.null;w&&Vn(x,x.length,0,Wu(w,c.slice(m+1,d),f)),Vn(x,x.length,0,[["exit",g,f],["enter",c[d][1],f],["exit",c[d][1],f],["exit",y,f]]),Vn(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 u(c,f,d){const m=this.previous,y=this.events;let g=0;return x;function x(_){return m===126&&y[y.length-1][1].type!=="characterEscape"?d(_):(c.enter("strikethroughSequenceTemporary"),w(_))}function w(_){const j=ba(m);if(_===126)return g>1?d(_):(c.consume(_),g++,w);if(g<2&&!r)return d(_);const D=c.exit("strikethroughSequenceTemporary"),N=ba(_);return D._open=!N||N===2&&!!j,D._close=!j||j===2&&!!N,f(_)}}}class dO{constructor(){this.map=[]}add(t,r,s){mO(this,t,r,s)}consume(t){if(this.map.sort(function(u,c){return u[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 u of l)t.push(u);l=s.pop()}this.map.length=0}}function mO(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 pO(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 u=s.length-1;s[u]=s[u]==="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 gO(){return{flow:{null:{name:"table",tokenize:yO,resolveAll:bO}}}}function yO(e,t,r){const s=this;let l=0,u=0,c;return f;function f(L){let G=s.events.length-1;for(;G>-1;){const le=s.events[G][1].type;if(le==="lineEnding"||le==="linePrefix")G--;else break}const J=G>-1?s.events[G][1].type:null,oe=J==="tableHead"||J==="tableRow"?R:d;return oe===R&&s.parser.lazy[s.now().line]?r(L):oe(L)}function d(L){return e.enter("tableHead"),e.enter("tableRow"),m(L)}function m(L){return L===124||(c=!0,u+=1),y(L)}function y(L){return L===null?r(L):He(L)?u>1?(u=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(L),e.exit("lineEnding"),w):r(L):st(L)?ct(e,y,"whitespace")(L):(u+=1,c&&(c=!1,l+=1),L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),c=!0,y):(e.enter("data"),g(L)))}function g(L){return L===null||L===124||jt(L)?(e.exit("data"),y(L)):(e.consume(L),L===92?x:g)}function x(L){return L===92||L===124?(e.consume(L),g):g(L)}function w(L){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(L):(e.enter("tableDelimiterRow"),c=!1,st(L)?ct(e,_,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(L):_(L))}function _(L){return L===45||L===58?D(L):L===124?(c=!0,e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),j):z(L)}function j(L){return st(L)?ct(e,D,"whitespace")(L):D(L)}function D(L){return L===58?(u+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),N):L===45?(u+=1,N(L)):L===null||He(L)?fe(L):z(L)}function N(L){return L===45?(e.enter("tableDelimiterFiller"),H(L)):z(L)}function H(L){return L===45?(e.consume(L),H):L===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),F):(e.exit("tableDelimiterFiller"),F(L))}function F(L){return st(L)?ct(e,fe,"whitespace")(L):fe(L)}function fe(L){return L===124?_(L):L===null||He(L)?!c||l!==u?z(L):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(L)):z(L)}function z(L){return r(L)}function R(L){return e.enter("tableRow"),ee(L)}function ee(L){return L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),ee):L===null||He(L)?(e.exit("tableRow"),t(L)):st(L)?ct(e,ee,"whitespace")(L):(e.enter("data"),$(L))}function $(L){return L===null||L===124||jt(L)?(e.exit("data"),ee(L)):(e.consume(L),L===92?q:$)}function q(L){return L===92||L===124?(e.consume(L),$):$(L)}}function bO(e,t){let r=-1,s=!0,l=0,u=[0,0,0,0],c=[0,0,0,0],f=!1,d=0,m,y,g;const x=new dO;for(;++r<e.length;){const w=e[r],_=w[1];w[0]==="enter"?_.type==="tableHead"?(f=!1,d!==0&&(Hb(x,t,d,m,y),y=void 0,d=0),m={type:"table",start:Object.assign({},_.start),end:Object.assign({},_.end)},x.add(r,0,[["enter",m,t]])):_.type==="tableRow"||_.type==="tableDelimiterRow"?(s=!0,g=void 0,u=[0,0,0,0],c=[0,r+1,0,0],f&&(f=!1,y={type:"tableBody",start:Object.assign({},_.start),end:Object.assign({},_.end)},x.add(r,0,[["enter",y,t]])),l=_.type==="tableDelimiterRow"?2:y?3:1):l&&(_.type==="data"||_.type==="tableDelimiterMarker"||_.type==="tableDelimiterFiller")?(s=!1,c[2]===0&&(u[1]!==0&&(c[0]=c[1],g=xu(x,t,u,l,void 0,g),u=[0,0,0,0]),c[2]=r)):_.type==="tableCellDivider"&&(s?s=!1:(u[1]!==0&&(c[0]=c[1],g=xu(x,t,u,l,void 0,g)),u=c,c=[u[1],r,0,0])):_.type==="tableHead"?(f=!0,d=r):_.type==="tableRow"||_.type==="tableDelimiterRow"?(d=r,u[1]!==0?(c[0]=c[1],g=xu(x,t,u,l,r,g)):c[1]!==0&&(g=xu(x,t,c,l,r,g)),l=0):l&&(_.type==="data"||_.type==="tableDelimiterMarker"||_.type==="tableDelimiterFiller")&&(c[3]=r)}for(d!==0&&Hb(x,t,d,m,y),x.consume(t.events),r=-1;++r<t.events.length;){const w=t.events[r];w[0]==="enter"&&w[1].type==="table"&&(w[1]._align=pO(t.events,r))}return e}function xu(e,t,r,s,l,u){const c=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";r[0]!==0&&(u.end=Object.assign({},ia(t.events,r[0])),e.add(r[0],0,[["exit",u,t]]));const d=ia(t.events,r[1]);if(u={type:c,start:Object.assign({},d),end:Object.assign({},d)},e.add(r[1],0,[["enter",u,t]]),r[2]!==0){const m=ia(t.events,r[2]),y=ia(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]],w=t.events[r[3]];if(x[1].end=Object.assign({},w[1].end),x[1].type="chunkText",x[1].contentType="text",r[3]>r[2]+1){const _=r[2]+1,j=r[3]-r[2]-1;e.add(_,j,[])}}e.add(r[3]+1,0,[["exit",g,t]])}return l!==void 0&&(u.end=Object.assign({},ia(t.events,l)),e.add(l,0,[["exit",u,t]]),u=void 0),u}function Hb(e,t,r,s,l){const u=[],c=ia(t.events,r);l&&(l.end=Object.assign({},c),u.push(["exit",l,t])),s.end=Object.assign({},c),u.push(["exit",s,t]),e.add(r+1,0,u)}function ia(e,t){const r=e[t],s=r[0]==="enter"?"start":"end";return r[1][s]}const xO={name:"tasklistCheck",tokenize:wO};function vO(){return{text:{91:xO}}}function wO(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"),u)}function u(d){return jt(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 He(d)?t(d):st(d)?e.check({tokenize:SO},t,r)(d):r(d)}}function SO(e,t,r){return ct(e,s,"whitespace");function s(l){return l===null?r(l):t(l)}}function _O(e){return r1([J3(),iO(),hO(e),gO(),vO()])}const kO={};function qb(e){const t=this,r=e||kO,s=t.data(),l=s.micromarkExtensions||(s.micromarkExtensions=[]),u=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);l.push(_O(r)),u.push($3()),c.push(Y3(r))}function EO(e){k1(e,[/\r?\n|\r/g,CO])}function CO(){return{type:"break"}}function Ib(){return function(e){EO(e)}}function AO({connected:e,hostId:t,request:r,subscribeEvents:s,taskId:l,runId:u}){const c=Mr(),f=$d(),[d,m]=A.useState(!0),[y,g]=A.useState([]),[x,w]=A.useState(),[_,j]=A.useState(),[D,N]=A.useState(),H=x==="started"||x==="monitoring",F=x==="followup",fe=x==="started"||x==="followup",[z,R]=A.useState(null);pd(z!==null,()=>R(null));const[ee,$]=A.useState(!1),[q,L]=A.useState(""),[G,J]=A.useState(!1),oe=A.useRef(null),le=A.useRef(null),K=A.useRef(null),[U,W]=A.useState(u==="latest"?void 0:u),ue=u==="latest"&&U===null;A.useEffect(()=>{if(u!=="latest"){W(u);return}e&&(W(void 0),r("taskrun.list",{task_id:l,limit:1}).then(S=>{var xe,Ae;return W(((Ae=(xe=S.entries)==null?void 0:xe[0])==null?void 0:Ae.run_id)??null)}).catch(()=>W(null)))},[u,l,e,r]);async function we(){if(U)try{const S=await r("task.result",{id:l,run_id:U});if(S.error){console.error("No result:",S.error),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0});return}g(S.messages??[]),w(S.running_state),j(S.agent),N(S.agent_version)}catch(S){console.error("Failed to load result:",S),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0})}finally{m(!1)}}async function M(S){var xe;if(U)try{const ve=(xe=(await r("task.reports",{id:l,run_id:U,report_files:[S]})).reports)==null?void 0:xe[0];ve!=null&&ve.data_url?R({file:S,data_url:ve.data_url}):R({file:S,content:(ve==null?void 0:ve.content)??"Report not found."})}catch{R({file:S,content:"Failed to load report."})}}A.useEffect(()=>{!e||!U||(m(!0),we())},[e,l,U]),A.useEffect(()=>!e||!t||!U?void 0:s(t,async xe=>{try{const Ae=JSON.parse(new TextDecoder().decode(xe.data));if(Ae.event_type!=="running-state"&&Ae.event_type!=="result-updated"||xe.subject.split(".").pop()!==l||Ae.event_type==="result-updated"&&Ae.run_id&&Ae.run_id!==U)return;we()}catch{}}),[e,t,l,U,s,r]),A.useEffect(()=>{oe.current&&(oe.current.scrollTop=oe.current.scrollHeight)},[y]),A.useEffect(()=>{d||ue||!U||K.current!==U&&(K.current=U,requestAnimationFrame(()=>{oe.current&&(oe.current.scrollTop=oe.current.scrollHeight),window.scrollTo({top:document.documentElement.scrollHeight,behavior:"auto"})}))},[d,ue,U]);function P(S){if(S==="input")return"User Input";if(S==="permission")return"Permission";if(S==="confirmation")return"Confirmation"}function te(S){return S==="started"?"Task started":S==="finished"?"Task finished":S==="failed"?"Task failed":S==="error"?"Command failed":S==="aborted"?"Task aborted":S==="confirmation"?"Task confirmed":S==="stopped"?"Follow-up stopped":S??""}return b.jsxs("div",{className:"run-detail",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"]}),ue?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:oe,children:[y.map((S,xe)=>{const Ae=fe&&S.role==="assistant"&&!y.slice(xe+1).some(ve=>ve.role==="assistant"||ve.role==="user");return S.role==="status"&&S.type==="monitoring"?null:S.role==="status"?b.jsxs("div",{className:`chat-status${S.type==="error"?" chat-status--error":""}`,children:[b.jsxs("div",{children:[te(S.type),S.time>0&&b.jsx("span",{className:"chat-status-time",children:f(S.time)})]}),S.content&&b.jsx("pre",{className:"chat-status-detail",children:S.content})]},xe):b.jsxs("div",{className:`chat-message chat-message--${S.role}${S.role==="assistant"&&S.stream==="stderr"?" chat-message--stderr":""}`,children:[S.role==="assistant"&&_&&b.jsxs("div",{className:"chat-message-agent",children:[md(_),D&&b.jsxs("span",{className:"chat-message-agent-version",children:[" v",D]})]}),b.jsxs("div",{className:"chat-message-content",children:[b.jsx(Mb,{remarkPlugins:[qb,Ib],components:{a:({...ve})=>b.jsx("a",{...ve,target:"_blank",rel:"noopener noreferrer"})},children:S.content}),Ae&&b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),S.attachments&&S.attachments.length>0&&b.jsx("div",{className:"chat-message-attachments",children:S.attachments.map(ve=>b.jsx("button",{className:"chat-attachment-chip",onClick:()=>M(ve),children:ve},ve))}),b.jsxs("div",{className:"chat-message-meta",children:[P(S.type)&&b.jsx("span",{className:"chat-message-type",children:P(S.type)}),S.time>0&&b.jsx("span",{children:f(S.time)})]})]},xe)}),fe&&(()=>{const S=y.filter(xe=>xe.role!=="status");return S.length===0||S[S.length-1].role!=="assistant"})()&&b.jsxs("div",{className:"chat-message chat-message--assistant",children:[_&&b.jsxs("div",{className:"chat-message-agent",children:[md(_),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",{})]})]}),x==="monitoring"&&b.jsxs("div",{className:"chat-monitoring-indicator",children:[b.jsx("span",{className:"chat-monitoring-dot"}),"Monitoring command output"]})]}),H?b.jsx("div",{className:"chat-abort-bar",children:b.jsx("button",{className:"btn btn-secondary chat-abort-btn",disabled:ee,onClick:async()=>{if(confirm("Abort this task?")){$(!0);try{await r("task.abort",{id:l})}catch(S){console.error("Abort failed:",S)}finally{$(!1)}}},children:ee?"Aborting...":"Abort Task"})}):F?b.jsx("div",{className:"chat-input-bar",children:b.jsx("button",{className:"btn btn-secondary chat-stop-btn",disabled:ee,onClick:async()=>{$(!0);try{await r("task.stop_followup",{id:l,run_id:U})}catch(S){console.error("Stop failed:",S)}finally{$(!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"})})})}):b.jsxs("form",{className:"chat-input-bar",onSubmit:async S=>{S.preventDefault();const xe=q.trim();if(!(!xe||G)){J(!0);try{await r("task.followup",{id:l,run_id:U,message:xe}),L("")}catch(Ae){console.error("Follow-up failed:",Ae)}finally{J(!1)}}},children:[b.jsx("input",{ref:le,className:"chat-input",type:"text",placeholder:"Follow-up message",value:q,onChange:S=>L(S.target.value),disabled:G}),b.jsx("button",{className:"btn btn-primary chat-send-btn",type:"submit",disabled:!q.trim()||G,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"})]})})]})]}),z&&b.jsx("div",{className:"report-dialog-overlay",onClick:()=>R(null),children:b.jsxs("div",{className:"report-dialog",onClick:S=>S.stopPropagation(),children:[b.jsxs("div",{className:"report-dialog-header",children:[b.jsx("span",{className:"report-dialog-title",children:z.file}),b.jsx("button",{className:"report-dialog-close",onClick:()=>R(null),"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",children:z.data_url?b.jsx("img",{src:z.data_url,alt:z.file,style:{maxWidth:"100%",height:"auto"}}):b.jsx(Mb,{remarkPlugins:[qb,Ib],components:{a:({...S})=>b.jsx("a",{...S,target:"_blank",rel:"noopener noreferrer"})},children:z.content??""})})]})})]})}function Fb({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 TO(){const{activeHost:e}=si(),t=A.useRef(null);A.useEffect(()=>{if(Jn.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 u=await l.pushManager.getSubscription();if(!u){const{publicKey:f}=await gE("/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}u=await l.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:f})}const c=u.toJSON();await pE("/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 jO="0.9.9";function Kh(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 vu(){const{removePairedHost:e,setHostLanUrl:t,setHostTimezone:r}=qi(),{connected:s,request:l,subscribeEvents:u,unauthorized:c,activeHost:f}=si(),d=f.hostId,m=f.clientToken||null,y=Mr(),g=cr(),x=Yu(),w=qx("(min-width: 768px)"),_=g.pathname.endsWith("/tasks"),j=x.runId?void 0:x.taskId,D=!!(x.taskId&&x.runId),[N,H]=A.useState(!1),[F,fe]=A.useState(!1),[z,R]=A.useState(null),[ee,$]=A.useState(null),[q,L]=A.useState(null),[G,J]=A.useState(()=>localStorage.getItem(`palmier.${d}.dismissedUpdateVersion`)),[oe,le]=A.useState({}),[K,U]=A.useState({}),[W,ue]=A.useState(null),[we,M]=A.useState(new Set),[P,te]=A.useState([]),[S,xe]=A.useState(),Ae=!!m&&W===m,[ve,Ue]=A.useState(new Map),[Ve,Te]=A.useState(new Map),[et,Pt]=A.useState(new Map),[Gt,Ft]=A.useState(new Map);TO(),A.useEffect(()=>{window.scrollTo(0,0)},[d]),A.useEffect(()=>{let je=!1;return JE().then(Q=>{je||M(Q)}),()=>{je=!0}},[]),A.useEffect(()=>{s&&l("host.info").then(je=>{var Ke,Fe,Ge,$e,Qe,Je;te(je.agents??[]),xe(je.host_platform),ue(je.linked_client_token??null),NE(je.agents??[]);const Q=je.version??null;$(Q),H(!!Q&&Kh(Q,jO)),t(d,je.lan_url??void 0),r(d,je.host_timezone);const he=new Map,_e=new Map,Oe=new Map,Ie=new Map;for(const pe of je.pending_prompts??[])if(pe.type==="confirmation")he.set(pe.key,{description:((Ke=pe.meta)==null?void 0:Ke.description)??"",sessionName:(Fe=pe.meta)==null?void 0:Fe.session_name});else if(pe.type==="permission")_e.set(pe.key,{permissions:pe.params??[],sessionName:(Ge=pe.meta)==null?void 0:Ge.session_name});else if(pe.type==="input"){const Pe=pe.params??(($e=pe.meta)==null?void 0:$e.input_questions)??[];Oe.set(pe.key,{questions:Pe,description:(Qe=pe.meta)==null?void 0:Qe.description,sessionName:(Je=pe.meta)==null?void 0:Je.session_name}),Ie.set(pe.key,new Array(Pe.length).fill(""))}Ue(he),Te(_e),Pt(Oe),Ft(Ie)}).catch(()=>{})},[s,d,l,t,r]),A.useEffect(()=>s?u(d,Q=>{const he=Q.subject.split(".");if(he.length<3)return;const _e=he.slice(2).join(".");let Oe={};try{Oe=JSON.parse(new TextDecoder().decode(Q.data))}catch{return}const Ie=Oe.event_type,Ke=Oe.session_id;if(Ie==="input-request"&&Ke){const Fe=Oe.input_questions,Ge=Oe.session_name,$e=Oe.description;Fe!=null&&Fe.length&&(Pt(Qe=>{if(Qe.has(Ke))return Qe;const Je=new Map(Qe);return Je.set(Ke,{questions:Fe,description:$e,sessionName:Ge}),Je}),Ft(Qe=>{if(Qe.has(Ke))return Qe;const Je=new Map(Qe);return Je.set(Ke,new Array(Fe.length).fill("")),Je}));return}if(Ie==="input-resolved"&&Ke){Pt(Fe=>{if(!Fe.has(Ke))return Fe;const Ge=new Map(Fe);return Ge.delete(Ke),Ge}),Ft(Fe=>{const Ge=new Map(Fe);return Ge.delete(Ke),Ge});return}if(Ie==="confirm-request"&&Ke){const Fe=Oe.description,Ge=Oe.session_name;Fe&&Ue($e=>{if($e.has(Ke))return $e;const Qe=new Map($e);return Qe.set(Ke,{description:Fe,sessionName:Ge}),Qe});return}if(Ie==="confirm-resolved"&&Ke){Ue(Fe=>{if(!Fe.has(Ke))return Fe;const Ge=new Map(Fe);return Ge.delete(Ke),Ge});return}if(Ie==="permission-request"){const Fe=Oe.required_permissions,Ge=Oe.session_name;Fe!=null&&Fe.length&&Te($e=>{if($e.has(_e))return $e;const Qe=new Map($e);return Qe.set(_e,{permissions:Fe,sessionName:Ge}),Qe});return}if(Ie==="permission-resolved"){Te(Fe=>{if(!Fe.has(_e))return Fe;const Ge=new Map(Fe);return Ge.delete(_e),Ge});return}}):void 0,[s,d,u]);async function De(je,Q){try{await l("task.user_input",{id:je,value:[Q]})}catch(he){console.error("[Dashboard] Failed to respond to confirmation:",he)}}async function ot(je,Q){try{await l("task.user_input",{id:je,value:[Q]})}catch(he){console.error("[Dashboard] Failed to respond to permission request:",he)}}async function tt(je,Q){try{await l("task.user_input",{id:je,value:Q})}catch(he){console.error("[Dashboard] Failed to respond to input request:",he)}}function vt(je,Q){if(!ps())return;const he=`/hosts/${encodeURIComponent(d)}/runs/${encodeURIComponent(je)}`;y(Q?`${he}/${encodeURIComponent(Q)}`:he)}A.useEffect(()=>{if(!ee)return;let je=!1;return fetch("https://registry.npmjs.org/palmier/latest").then(Q=>Q.ok?Q.json():null).then(Q=>{!je&&(Q!=null&&Q.version)&&L(Q.version)}).catch(()=>{}),()=>{je=!0}},[ee]),A.useEffect(()=>{let je=!1;const Q={};for(const he of P){if(!he.version)continue;const _e=localStorage.getItem(`palmier.${d}.dismissedAgentUpdate.${he.key}`);_e&&(Q[he.key]=_e)}U(Q);for(const he of P)!he.version||!he.npmPackage||fetch(`https://registry.npmjs.org/${he.npmPackage}/latest`).then(_e=>_e.ok?_e.json():null).then(_e=>{je||!(_e!=null&&_e.version)||le(Oe=>Oe[he.key]===_e.version?Oe:{...Oe,[he.key]:_e.version})}).catch(()=>{});return()=>{je=!0}},[P]);const ft=P.find(je=>{if(!je.version)return!1;const Q=oe[je.key];return!Q||!Kh(je.version,Q)?!1:K[je.key]!==Q});function gn(je,Q){localStorage.setItem(`palmier.${d}.dismissedAgentUpdate.${je}`,Q),U(he=>({...he,[je]:Q}))}async function an(je){fe(!0),R(null);try{const Q=await l("host.updateAgent",{key:je});if(Q.error){R(Q.error),fe(!1);return}const he=await l("host.info");he.agents&&te(he.agents)}catch(Q){R(Q instanceof Error?Q.message:String(Q))}finally{fe(!1)}}const Wt=!N&&!!ee&&!!q&&Kh(ee,q)&&G!==q;function yn(){q&&(localStorage.setItem(`palmier.${d}.dismissedUpdateVersion`,q),J(q))}async function Kn(){fe(!0),R(null);try{const je=await l("host.update");if(je.error){R(je.error),fe(!1);return}}catch{}setTimeout(()=>window.location.reload(),15e3)}const pt=s&&!c;return b.jsxs("div",{className:"dashboard",children:[w&&b.jsx(G0,{daemonVersion:ee,agents:P,linkedClientToken:W,request:l,onEnabledCapabilitiesChange:M,onLinkedClientTokenChange:ue}),b.jsxs("div",{className:"dashboard-content",children:[b.jsxs("header",{className:"app-header",children:[b.jsxs("div",{className:"app-title-bar",children:[!w&&b.jsx(G0,{daemonVersion:ee,agents:P,linkedClientToken:W,request:l,onEnabledCapabilitiesChange:M,onLinkedClientTokenChange:ue}),b.jsx("h1",{className:"app-title",children:"Palmier"}),b.jsx(WE,{})]}),b.jsx("div",{className:"tab-bar",children:b.jsx(YE,{})})]}),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:()=>{ps()&&y("/pair")},children:"Re-pair Device"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{e(d),y("/",{replace:!0})},children:"Remove Host"})]})]}):pt?b.jsxs(b.Fragment,{children:[_&&!D&&b.jsx($E,{connected:s,hostId:d,request:l,subscribeEvents:u,agents:P,hostPlatform:S,isNotificationListener:Ae&&we.has("notifications"),onViewRun:vt}),D?b.jsx(AO,{connected:s,hostId:d,request:l,subscribeEvents:u,taskId:x.taskId,runId:decodeURIComponent(x.runId)}):_?null:b.jsx(rC,{connected:s,hostId:d,request:l,subscribeEvents:u,agents:P,hostPlatform:S,filterTaskId:j,onClearFilter:()=>{ps()&&y(`/hosts/${encodeURIComponent(d)}`)}})]}):b.jsx("div",{className:"empty-state",children:b.jsx("p",{children:"Connecting to host..."})})}),(N||Wt)&&!F&&!z&&b.jsx(Fb,{title:N?"Update Required":"Update Available",message:N?`Your Palmier host${ee?` (v${ee})`:""} is too old for this version of the app. Please update to continue.`:`A new version of Palmier (v${q}) is available. You're running v${ee}.`,onUpdate:Kn,onDismiss:N?void 0:yn}),!N&&!Wt&&ft&&!F&&!z&&b.jsx(Fb,{title:"Agent Update Available",message:`A new version of ${ft.label} (v${oe[ft.key]}) is available. You're running v${ft.version}.`,onUpdate:()=>an(ft.key),onDismiss:()=>gn(ft.key,oe[ft.key])}),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:"Installing update and restarting daemon. Please wait..."})]})}),z&&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:z}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>{R(null)},children:"Retry"})})]})})]}),ds.createPortal(b.jsxs(b.Fragment,{children:[[...ve.entries()].map(([je,{description:Q,sessionName:he}])=>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"}),he&&b.jsx("p",{className:"confirm-modal-subtitle",children:he}),b.jsx("p",{className:"confirm-modal-message",children:Q}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>De(je,"confirmed"),children:"Confirm"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>De(je,"aborted"),children:"Abort"})]})]})},je)),[...Ve.entries()].map(([je,{permissions:Q,sessionName:he}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal permission-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Permission Required"}),b.jsx("p",{className:"confirm-modal-message",children:b.jsx("strong",{children:he||je})}),b.jsx("div",{className:"permission-list",children:Q.map((_e,Oe)=>b.jsxs("div",{className:"permission-item",children:[b.jsx("span",{className:"permission-name",children:_e.name}),_e.description&&b.jsx("span",{className:"permission-desc",children:_e.description})]},Oe))}),b.jsxs("div",{className:"permission-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>ot(je,"granted"),children:"Allow Once"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>ot(je,"granted_all"),children:"Allow Always"})]}),b.jsx("button",{className:"permission-abort-link",onClick:()=>ot(je,"aborted"),children:"Deny & Abort Task"})]})},je)),[...et.entries()].map(([je,{questions:Q,description:he,sessionName:_e}])=>{const Oe=Gt.get(je)??new Array(Q.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:"Input Required"}),_e&&b.jsx("p",{className:"confirm-modal-subtitle",children:_e}),he&&b.jsx("p",{className:"confirm-modal-message",children:he}),b.jsx("div",{className:"input-list",children:Q.map((Ie,Ke)=>b.jsxs("div",{className:"input-item",children:[b.jsx("label",{className:"input-label",children:Ie}),b.jsx("input",{type:"text",className:"input-field",value:Oe[Ke]??"",onChange:Fe=>{Ft(Ge=>{const $e=new Map(Ge),Qe=[...$e.get(je)??[]];return Qe[Ke]=Fe.target.value,$e.set(je,Qe),$e})},autoFocus:Ke===0})]},Ke))}),b.jsx("div",{className:"input-actions",children:b.jsx("button",{className:"btn btn-primary",disabled:Oe.some(Ie=>!Ie.trim()),onClick:()=>tt(je,Oe),children:"Submit"})}),b.jsx("button",{className:"permission-abort-link",onClick:()=>tt(je,["aborted"]),children:"Cancel"})]})},je)})]}),document.body)]})}const NO=ys("Preferences",{web:()=>Fd(()=>import("./web-okZXRyxh.js"),[]).then(e=>new e.PreferencesWeb)}),kl=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),$b=Jn.isNativePlatform();function OO(){const[e,t]=A.useState(""),[r,s]=A.useState(!0),[l,u]=A.useState(!1),[c,f]=A.useState(null),{addPairedHost:d,pairedHosts:m}=qi(),y=Mr();async function g(){const x=e.trim().toUpperCase();if(!x){f("Enter a pairing code.");return}u(!0),f(null);try{let w;if(kl){const D=await fetch("/pair",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:x,label:navigator.userAgent})});if(!D.ok){const N=await D.json().catch(()=>({error:"Connection failed"}));throw new Error(N.error||`HTTP ${D.status}`)}w=await D.json()}else{const D=await fetch(`${Bu}/api/config`);if(!D.ok)throw new Error("Failed to fetch server config");const N=await D.json();if(!N.natsWsUrl)throw new Error("Server has no NATS WebSocket URL configured");const H=await Dx({servers:N.natsWsUrl,authenticator:Ex(N.natsJwt,new TextEncoder().encode(N.natsNkeySeed))}),F=Ou(),fe=`pair.${x}`,z=await H.request(fe,F.encode(JSON.stringify({label:navigator.userAgent})),{timeout:1e4});w=JSON.parse(F.decode(z.data)),await H.close()}const _={hostId:w.hostId,clientToken:w.clientToken,directUrl:kl?window.location.origin:void 0,...w.hostName?{name:w.hostName}:{}};if(d(_),Jn.isNativePlatform()&&dn){await NO.set({key:"hostId",value:w.hostId});try{const{token:D}=await dn.getFcmToken();await fetch(`${Bu}/api/fcm/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostId:w.hostId,fcmToken:D})})}catch(D){console.warn("FCM token registration failed:",D)}}const j=`/hosts/${encodeURIComponent(w.hostId)}`;y($b&&r?`${j}/pair/setup`:j)}catch(w){const _=w instanceof Error?w.message:String(w);_.includes("timeout")||_.includes("TIMEOUT")||_.includes("503")||_.toLowerCase().includes("no responders")?f("Code not found or expired. Check the code and try again."):f(_)}finally{u(!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:kl?"Pair":"Pair with Host"}),b.jsx("p",{className:"pair-subtitle",children:kl?"Enter the pairing code shown in your terminal.":"Connect this device to a Palmier host"})]}),!kl&&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 at least one agent CLI (e.g., ",b.jsx("a",{href:"https://www.palmier.me/agents",target:"_blank",rel:"noopener noreferrer",children:"Claude Code, Gemini CLI, Codex CLI"}),")"]}),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 RO(){const e=Mr(),{connected:t,request:r,activeHost:s}=si(),{setHostLanUrl:l,pairedHosts:u}=qi(),c=u.length<=1,[f,d]=A.useState("loading"),[m,y]=A.useState(null),[g,x]=A.useState(null);function w(){e(`/hosts/${encodeURIComponent(s.hostId)}`,{replace:!0})}A.useEffect(()=>{if(!t||f!=="loading")return;let H=!1;return r("host.info").catch(()=>({})).then(F=>{if(H)return;l(s.hostId,F.lan_url??void 0);const fe=F.linked_client_token??null;y(fe);const z=!!fe&&fe!==s.clientToken;d(z?"confirming":"linking")}),()=>{H=!0}},[t,f,s,r,l]),A.useEffect(()=>{if(f!=="linking")return;let H=!1;return(async()=>{try{if(dn){const{token:F}=await dn.getFcmToken();if(!F)throw new Error("Could not read FCM token");await r("device.link",{fcmToken:F})}if(H)return;c?d("wizard"):w()}catch(F){if(H)return;x(F instanceof Error?F.message:String(F)),d("linkError")}})(),()=>{H=!0}},[f]);function _(){d("linking")}function j(){w()}function D(){x(null),d("linking")}const N=f==="confirming"&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:j,children:b.jsxs("div",{className:"confirm-modal",onClick:H=>H.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:_,children:"Link"})]})]})}),document.body);if(f==="loading"||f==="confirming"||f==="linking"||f==="linkError"){const H=c,F=f==="loading"||f==="confirming"||f==="linking";return b.jsxs("div",{className:"pair-setup",children:[b.jsxs("div",{className:"pair-setup-inner",children:[H&&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:w,children:"Skip linking"})]})]})]}),N]})}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(Ix,{}),b.jsx("div",{className:"pair-setup-actions",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:w,children:"Finish"})})]})})}function MO(){const e=Mr();return A.useEffect(()=>{if(!dn)return;const t=dn.addListener("deepLink",({path:r})=>e(r));return()=>{t.then(r=>r.remove())}},[e]),null}function DO(){const{pairedHosts:e}=qi();return e.length===0?b.jsx(zl,{to:"/pair",replace:!0}):b.jsx(zl,{to:`/hosts/${encodeURIComponent(e[0].hostId)}`,replace:!0})}function LO(){const{hostId:e}=Yu(),{pairedHosts:t}=qi(),r=t.find(s=>s.hostId===e)??null;return r?b.jsx(vE,{activeHost:r,children:b.jsxs(ax,{children:[b.jsx(br,{index:!0,element:b.jsx(vu,{})}),b.jsx(br,{path:"tasks",element:b.jsx(vu,{})}),b.jsx(br,{path:"runs/:taskId",element:b.jsx(vu,{})}),b.jsx(br,{path:"runs/:taskId/:runId",element:b.jsx(vu,{})}),b.jsx(br,{path:"pair/setup",element:b.jsx(RO,{})}),b.jsx(br,{path:"*",element:b.jsx(zl,{to:".",replace:!0})})]})}):b.jsx(zl,{to:"/",replace:!0})}function zO(){return b.jsxs($_,{children:[b.jsx(MO,{}),b.jsxs(ax,{children:[b.jsx(br,{path:"/",element:b.jsx(DO,{})}),b.jsx(br,{path:"/pair",element:b.jsx(OO,{})}),b.jsx(br,{path:"/hosts/:hostId/*",element:b.jsx(LO,{})}),b.jsx(br,{path:"*",element:b.jsx(zl,{to:"/",replace:!0})})]})]})}fS.createRoot(document.getElementById("root")).render(b.jsx(A.StrictMode,{children:b.jsx(O_,{children:b.jsx(zO,{})})}));export{Id as W};
120
+ `))}function d(w,_,j,D){const N=j.enter("tableCell"),H=j.enter("phrasing"),F=j.containerPhrasing(w,{...D,before:u,after:u});return H(),N(),F}function m(w,_){return WN(w,{align:_,alignDelimiters:s,padding:r,stringLength:l})}function y(w,_,j){const D=w.children;let N=-1;const H=[],F=_.enter("table");for(;++N<D.length;)H[N]=g(D[N],_,j);return F(),H}function g(w,_,j){const D=w.children;let N=-1;const H=[],F=_.enter("tableRow");for(;++N<D.length;)H[N]=d(D[N],w,_,j);return F(),H}function x(w,_,j){let D=P1.inlineCode(w,_,j);return j.stack.includes("tableCell")&&(D=D.replace(/\|/g,"\\$&")),D}}function H3(){return{exit:{taskListCheckValueChecked:Pb,taskListCheckValueUnchecked:Pb,paragraph:I3}}}function q3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:F3}}}function Pb(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function I3(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 u=-1,c;for(;++u<l.length;){const f=l[u];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 F3(e,t,r,s){const l=e.children[0],u=typeof e.checked=="boolean"&&l&&l.type==="paragraph",c="["+(e.checked?"x":" ")+"] ",f=r.createTracker(s);u&&f.move(c);let d=P1.listItem(e,t,r,{...s,...f.current()});return u&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),d;function m(y){return y+c}}function $3(){return[SN(),FN(),GN(),M3(),H3()]}function Y3(e){return{extensions:[_N(),$N(e),JN(),P3(e),q3()]}}const V3={tokenize:Z3,partial:!0},H1={tokenize:W3,partial:!0},q1={tokenize:eO,partial:!0},I1={tokenize:tO,partial:!0},G3={tokenize:nO,partial:!0},F1={name:"wwwAutolink",tokenize:K3,previous:Y1},$1={name:"protocolAutolink",tokenize:Q3,previous:V1},ai={name:"emailAutolink",tokenize:X3,previous:G1},Dr={};function J3(){return{text:Dr}}let hs=48;for(;hs<123;)Dr[hs]=ai,hs++,hs===58?hs=65:hs===91&&(hs=97);Dr[43]=ai;Dr[45]=ai;Dr[46]=ai;Dr[95]=ai;Dr[72]=[ai,$1];Dr[104]=[ai,$1];Dr[87]=[ai,F1];Dr[119]=[ai,F1];function X3(e,t,r){const s=this;let l,u;return c;function c(g){return!Cd(g)||!G1.call(s,s.previous)||um(s.events)?r(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return Cd(g)?(e.consume(g),f):g===64?(e.consume(g),d):r(g)}function d(g){return g===46?e.check(G3,y,m)(g):g===45||g===95||mn(g)?(u=!0,e.consume(g),d):y(g)}function m(g){return e.consume(g),l=!0,d}function y(g){return u&&l&&_n(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):r(g)}}function K3(e,t,r){const s=this;return l;function l(c){return c!==87&&c!==119||!Y1.call(s,s.previous)||um(s.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(V3,e.attempt(H1,e.attempt(q1,u),r),r)(c))}function u(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function Q3(e,t,r){const s=this;let l="",u=!1;return c;function c(g){return(g===72||g===104)&&V1.call(s,s.previous)&&!um(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),l+=String.fromCodePoint(g),e.consume(g),f):r(g)}function f(g){if(_n(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),u?m:(u=!0,d)):r(g)}function m(g){return g===null||Pu(g)||jt(g)||gs(g)||Zu(g)?r(g):e.attempt(H1,e.attempt(q1,y),r)(g)}function y(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function Z3(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),u):r(c)}function u(c){return c===null?r(c):t(c)}}function W3(e,t,r){let s,l,u;return c;function c(m){return m===46||m===95?e.check(I1,d,f)(m):m===null||jt(m)||gs(m)||m!==45&&Zu(m)?d(m):(u=!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||!u?r(m):t(m)}}function eO(e,t){let r=0,s=0;return l;function l(c){return c===40?(r++,e.consume(c),l):c===41&&s<r?u(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(I1,t,u)(c):c===null||jt(c)||gs(c)?t(c):(e.consume(c),l)}function u(c){return c===41&&s++,e.consume(c),l}}function tO(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),u):f===93?(e.consume(f),l):f===60||f===null||jt(f)||gs(f)?t(f):r(f)}function l(f){return f===null||f===40||f===91||jt(f)||gs(f)?t(f):s(f)}function u(f){return _n(f)?c(f):r(f)}function c(f){return f===59?(e.consume(f),s):_n(f)?(e.consume(f),c):r(f)}}function nO(e,t,r){return s;function s(u){return e.consume(u),l}function l(u){return mn(u)?r(u):t(u)}}function Y1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||jt(e)}function V1(e){return!_n(e)}function G1(e){return!(e===47||Cd(e))}function Cd(e){return e===43||e===45||e===46||e===95||mn(e)}function um(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 rO={tokenize:fO,partial:!0};function iO(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:oO,continuation:{tokenize:uO},exit:cO}},text:{91:{name:"gfmFootnoteCall",tokenize:lO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:sO,resolveTo:aO}}}}function sO(e,t,r){const s=this;let l=s.events.length;const u=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=wr(s.sliceSerialize({start:c.end,end:s.now()}));return m.codePointAt(0)!==94||!u.includes(m.slice(1))?r(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),t(d))}}function aO(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 u={type:"gfmFootnoteCallString",start:Object.assign({},l.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},u.start),end:Object.assign({},u.end)},f=[e[r+1],e[r+2],["enter",s,t],e[r+3],e[r+4],["enter",l,t],["exit",l,t],["enter",u,t],["enter",c,t],["exit",c,t],["exit",u,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(r,e.length-r+1,...f),e}function lO(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u=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(u>999||g===93&&!c||g===null||g===91||jt(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return l.includes(wr(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(g)}return jt(g)||(c=!0),u++,e.consume(g),g===92?y:m}function y(g){return g===91||g===92||g===93?(e.consume(g),u++,m):m(g)}}function oO(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u,c=0,f;return d;function d(_){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionLabelMarker"),m}function m(_){return _===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",y):r(_)}function y(_){if(c>999||_===93&&!f||_===null||_===91||jt(_))return r(_);if(_===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return u=wr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(_),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return jt(_)||(f=!0),c++,e.consume(_),_===92?g:y}function g(_){return _===91||_===92||_===93?(e.consume(_),c++,y):y(_)}function x(_){return _===58?(e.enter("definitionMarker"),e.consume(_),e.exit("definitionMarker"),l.includes(u)||l.push(u),ct(e,w,"gfmFootnoteDefinitionWhitespace")):r(_)}function w(_){return t(_)}}function uO(e,t,r){return e.check(Jl,t,e.attempt(rO,t,r))}function cO(e){e.exit("gfmFootnoteDefinition")}function fO(e,t,r){const s=this;return ct(e,l,"gfmFootnoteDefinitionIndent",5);function l(u){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(u):r(u)}}function hO(e){let r=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:u,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]],w=f.parser.constructs.insideSpan.null;w&&Vn(x,x.length,0,Wu(w,c.slice(m+1,d),f)),Vn(x,x.length,0,[["exit",g,f],["enter",c[d][1],f],["exit",c[d][1],f],["exit",y,f]]),Vn(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 u(c,f,d){const m=this.previous,y=this.events;let g=0;return x;function x(_){return m===126&&y[y.length-1][1].type!=="characterEscape"?d(_):(c.enter("strikethroughSequenceTemporary"),w(_))}function w(_){const j=ba(m);if(_===126)return g>1?d(_):(c.consume(_),g++,w);if(g<2&&!r)return d(_);const D=c.exit("strikethroughSequenceTemporary"),N=ba(_);return D._open=!N||N===2&&!!j,D._close=!j||j===2&&!!N,f(_)}}}class dO{constructor(){this.map=[]}add(t,r,s){mO(this,t,r,s)}consume(t){if(this.map.sort(function(u,c){return u[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 u of l)t.push(u);l=s.pop()}this.map.length=0}}function mO(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 pO(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 u=s.length-1;s[u]=s[u]==="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 gO(){return{flow:{null:{name:"table",tokenize:yO,resolveAll:bO}}}}function yO(e,t,r){const s=this;let l=0,u=0,c;return f;function f(L){let G=s.events.length-1;for(;G>-1;){const le=s.events[G][1].type;if(le==="lineEnding"||le==="linePrefix")G--;else break}const J=G>-1?s.events[G][1].type:null,oe=J==="tableHead"||J==="tableRow"?R:d;return oe===R&&s.parser.lazy[s.now().line]?r(L):oe(L)}function d(L){return e.enter("tableHead"),e.enter("tableRow"),m(L)}function m(L){return L===124||(c=!0,u+=1),y(L)}function y(L){return L===null?r(L):He(L)?u>1?(u=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(L),e.exit("lineEnding"),w):r(L):st(L)?ct(e,y,"whitespace")(L):(u+=1,c&&(c=!1,l+=1),L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),c=!0,y):(e.enter("data"),g(L)))}function g(L){return L===null||L===124||jt(L)?(e.exit("data"),y(L)):(e.consume(L),L===92?x:g)}function x(L){return L===92||L===124?(e.consume(L),g):g(L)}function w(L){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(L):(e.enter("tableDelimiterRow"),c=!1,st(L)?ct(e,_,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(L):_(L))}function _(L){return L===45||L===58?D(L):L===124?(c=!0,e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),j):z(L)}function j(L){return st(L)?ct(e,D,"whitespace")(L):D(L)}function D(L){return L===58?(u+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),N):L===45?(u+=1,N(L)):L===null||He(L)?fe(L):z(L)}function N(L){return L===45?(e.enter("tableDelimiterFiller"),H(L)):z(L)}function H(L){return L===45?(e.consume(L),H):L===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),F):(e.exit("tableDelimiterFiller"),F(L))}function F(L){return st(L)?ct(e,fe,"whitespace")(L):fe(L)}function fe(L){return L===124?_(L):L===null||He(L)?!c||l!==u?z(L):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(L)):z(L)}function z(L){return r(L)}function R(L){return e.enter("tableRow"),ee(L)}function ee(L){return L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),ee):L===null||He(L)?(e.exit("tableRow"),t(L)):st(L)?ct(e,ee,"whitespace")(L):(e.enter("data"),$(L))}function $(L){return L===null||L===124||jt(L)?(e.exit("data"),ee(L)):(e.consume(L),L===92?q:$)}function q(L){return L===92||L===124?(e.consume(L),$):$(L)}}function bO(e,t){let r=-1,s=!0,l=0,u=[0,0,0,0],c=[0,0,0,0],f=!1,d=0,m,y,g;const x=new dO;for(;++r<e.length;){const w=e[r],_=w[1];w[0]==="enter"?_.type==="tableHead"?(f=!1,d!==0&&(Hb(x,t,d,m,y),y=void 0,d=0),m={type:"table",start:Object.assign({},_.start),end:Object.assign({},_.end)},x.add(r,0,[["enter",m,t]])):_.type==="tableRow"||_.type==="tableDelimiterRow"?(s=!0,g=void 0,u=[0,0,0,0],c=[0,r+1,0,0],f&&(f=!1,y={type:"tableBody",start:Object.assign({},_.start),end:Object.assign({},_.end)},x.add(r,0,[["enter",y,t]])),l=_.type==="tableDelimiterRow"?2:y?3:1):l&&(_.type==="data"||_.type==="tableDelimiterMarker"||_.type==="tableDelimiterFiller")?(s=!1,c[2]===0&&(u[1]!==0&&(c[0]=c[1],g=xu(x,t,u,l,void 0,g),u=[0,0,0,0]),c[2]=r)):_.type==="tableCellDivider"&&(s?s=!1:(u[1]!==0&&(c[0]=c[1],g=xu(x,t,u,l,void 0,g)),u=c,c=[u[1],r,0,0])):_.type==="tableHead"?(f=!0,d=r):_.type==="tableRow"||_.type==="tableDelimiterRow"?(d=r,u[1]!==0?(c[0]=c[1],g=xu(x,t,u,l,r,g)):c[1]!==0&&(g=xu(x,t,c,l,r,g)),l=0):l&&(_.type==="data"||_.type==="tableDelimiterMarker"||_.type==="tableDelimiterFiller")&&(c[3]=r)}for(d!==0&&Hb(x,t,d,m,y),x.consume(t.events),r=-1;++r<t.events.length;){const w=t.events[r];w[0]==="enter"&&w[1].type==="table"&&(w[1]._align=pO(t.events,r))}return e}function xu(e,t,r,s,l,u){const c=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";r[0]!==0&&(u.end=Object.assign({},ia(t.events,r[0])),e.add(r[0],0,[["exit",u,t]]));const d=ia(t.events,r[1]);if(u={type:c,start:Object.assign({},d),end:Object.assign({},d)},e.add(r[1],0,[["enter",u,t]]),r[2]!==0){const m=ia(t.events,r[2]),y=ia(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]],w=t.events[r[3]];if(x[1].end=Object.assign({},w[1].end),x[1].type="chunkText",x[1].contentType="text",r[3]>r[2]+1){const _=r[2]+1,j=r[3]-r[2]-1;e.add(_,j,[])}}e.add(r[3]+1,0,[["exit",g,t]])}return l!==void 0&&(u.end=Object.assign({},ia(t.events,l)),e.add(l,0,[["exit",u,t]]),u=void 0),u}function Hb(e,t,r,s,l){const u=[],c=ia(t.events,r);l&&(l.end=Object.assign({},c),u.push(["exit",l,t])),s.end=Object.assign({},c),u.push(["exit",s,t]),e.add(r+1,0,u)}function ia(e,t){const r=e[t],s=r[0]==="enter"?"start":"end";return r[1][s]}const xO={name:"tasklistCheck",tokenize:wO};function vO(){return{text:{91:xO}}}function wO(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"),u)}function u(d){return jt(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 He(d)?t(d):st(d)?e.check({tokenize:SO},t,r)(d):r(d)}}function SO(e,t,r){return ct(e,s,"whitespace");function s(l){return l===null?r(l):t(l)}}function _O(e){return r1([J3(),iO(),hO(e),gO(),vO()])}const kO={};function qb(e){const t=this,r=e||kO,s=t.data(),l=s.micromarkExtensions||(s.micromarkExtensions=[]),u=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);l.push(_O(r)),u.push($3()),c.push(Y3(r))}function EO(e){k1(e,[/\r?\n|\r/g,CO])}function CO(){return{type:"break"}}function Ib(){return function(e){EO(e)}}function AO({connected:e,hostId:t,request:r,subscribeEvents:s,taskId:l,runId:u}){const c=Mr(),f=$d(),[d,m]=A.useState(!0),[y,g]=A.useState([]),[x,w]=A.useState(),[_,j]=A.useState(),[D,N]=A.useState(),H=x==="started"||x==="monitoring",F=x==="followup",fe=x==="started"||x==="followup",[z,R]=A.useState(null);pd(z!==null,()=>R(null));const[ee,$]=A.useState(!1),[q,L]=A.useState(""),[G,J]=A.useState(!1),oe=A.useRef(null),le=A.useRef(null),K=A.useRef(null),[U,W]=A.useState(u==="latest"?void 0:u),ue=u==="latest"&&U===null;A.useEffect(()=>{if(u!=="latest"){W(u);return}e&&(W(void 0),r("taskrun.list",{task_id:l,limit:1}).then(S=>{var xe,Ae;return W(((Ae=(xe=S.entries)==null?void 0:xe[0])==null?void 0:Ae.run_id)??null)}).catch(()=>W(null)))},[u,l,e,r]);async function we(){if(U)try{const S=await r("task.result",{id:l,run_id:U});if(S.error){console.error("No result:",S.error),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0});return}g(S.messages??[]),w(S.running_state),j(S.agent),N(S.agent_version)}catch(S){console.error("Failed to load result:",S),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0})}finally{m(!1)}}async function M(S){var xe;if(U)try{const ve=(xe=(await r("task.reports",{id:l,run_id:U,report_files:[S]})).reports)==null?void 0:xe[0];ve!=null&&ve.data_url?R({file:S,data_url:ve.data_url}):R({file:S,content:(ve==null?void 0:ve.content)??"Report not found."})}catch{R({file:S,content:"Failed to load report."})}}A.useEffect(()=>{!e||!U||(m(!0),we())},[e,l,U]),A.useEffect(()=>!e||!t||!U?void 0:s(t,async xe=>{try{const Ae=JSON.parse(new TextDecoder().decode(xe.data));if(Ae.event_type!=="running-state"&&Ae.event_type!=="result-updated"||xe.subject.split(".").pop()!==l||Ae.event_type==="result-updated"&&Ae.run_id&&Ae.run_id!==U)return;we()}catch{}}),[e,t,l,U,s,r]),A.useEffect(()=>{oe.current&&(oe.current.scrollTop=oe.current.scrollHeight)},[y]),A.useEffect(()=>{d||ue||!U||K.current!==U&&(K.current=U,requestAnimationFrame(()=>{oe.current&&(oe.current.scrollTop=oe.current.scrollHeight),window.scrollTo({top:document.documentElement.scrollHeight,behavior:"auto"})}))},[d,ue,U]);function P(S){if(S==="input")return"User Input";if(S==="permission")return"Permission";if(S==="confirmation")return"Confirmation"}function te(S){return S==="started"?"Task started":S==="finished"?"Task finished":S==="failed"?"Task failed":S==="error"?"Command failed":S==="aborted"?"Task aborted":S==="confirmation"?"Task confirmed":S==="stopped"?"Follow-up stopped":S??""}return b.jsxs("div",{className:"run-detail",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"]}),ue?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:oe,children:[y.map((S,xe)=>{const Ae=fe&&S.role==="assistant"&&!y.slice(xe+1).some(ve=>ve.role==="assistant"||ve.role==="user");return S.role==="status"&&S.type==="monitoring"?null:S.role==="status"?b.jsxs("div",{className:`chat-status${S.type==="error"?" chat-status--error":""}`,children:[b.jsxs("div",{children:[te(S.type),S.time>0&&b.jsx("span",{className:"chat-status-time",children:f(S.time)})]}),S.content&&b.jsx("pre",{className:"chat-status-detail",children:S.content})]},xe):b.jsxs("div",{className:`chat-message chat-message--${S.role}${S.role==="assistant"&&S.stream==="stderr"?" chat-message--stderr":""}`,children:[S.role==="assistant"&&_&&b.jsxs("div",{className:"chat-message-agent",children:[md(_),D&&b.jsxs("span",{className:"chat-message-agent-version",children:[" v",D]})]}),b.jsxs("div",{className:"chat-message-content",children:[b.jsx(Mb,{remarkPlugins:[qb,Ib],components:{a:({...ve})=>b.jsx("a",{...ve,target:"_blank",rel:"noopener noreferrer"})},children:S.content}),Ae&&b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),S.attachments&&S.attachments.length>0&&b.jsx("div",{className:"chat-message-attachments",children:S.attachments.map(ve=>b.jsx("button",{className:"chat-attachment-chip",onClick:()=>M(ve),children:ve},ve))}),b.jsxs("div",{className:"chat-message-meta",children:[P(S.type)&&b.jsx("span",{className:"chat-message-type",children:P(S.type)}),S.time>0&&b.jsx("span",{children:f(S.time)})]})]},xe)}),fe&&(()=>{const S=y.filter(xe=>xe.role!=="status");return S.length===0||S[S.length-1].role!=="assistant"})()&&b.jsxs("div",{className:"chat-message chat-message--assistant",children:[_&&b.jsxs("div",{className:"chat-message-agent",children:[md(_),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",{})]})]}),x==="monitoring"&&b.jsxs("div",{className:"chat-monitoring-indicator",children:[b.jsx("span",{className:"chat-monitoring-dot"}),"Monitoring command output"]})]}),H?b.jsx("div",{className:"chat-abort-bar",children:b.jsx("button",{className:"btn btn-secondary chat-abort-btn",disabled:ee,onClick:async()=>{if(confirm("Abort this task?")){$(!0);try{await r("task.abort",{id:l})}catch(S){console.error("Abort failed:",S)}finally{$(!1)}}},children:ee?"Aborting...":"Abort Task"})}):F?b.jsx("div",{className:"chat-input-bar",children:b.jsx("button",{className:"btn btn-secondary chat-stop-btn",disabled:ee,onClick:async()=>{$(!0);try{await r("task.stop_followup",{id:l,run_id:U})}catch(S){console.error("Stop failed:",S)}finally{$(!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"})})})}):b.jsxs("form",{className:"chat-input-bar",onSubmit:async S=>{S.preventDefault();const xe=q.trim();if(!(!xe||G)){J(!0);try{await r("task.followup",{id:l,run_id:U,message:xe}),L("")}catch(Ae){console.error("Follow-up failed:",Ae)}finally{J(!1)}}},children:[b.jsx("input",{ref:le,className:"chat-input",type:"text",placeholder:"Follow-up message",value:q,onChange:S=>L(S.target.value),disabled:G}),b.jsx("button",{className:"btn btn-primary chat-send-btn",type:"submit",disabled:!q.trim()||G,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"})]})})]})]}),z&&b.jsx("div",{className:"report-dialog-overlay",onClick:()=>R(null),children:b.jsxs("div",{className:"report-dialog",onClick:S=>S.stopPropagation(),children:[b.jsxs("div",{className:"report-dialog-header",children:[b.jsx("span",{className:"report-dialog-title",children:z.file}),b.jsx("button",{className:"report-dialog-close",onClick:()=>R(null),"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",children:z.data_url?b.jsx("img",{src:z.data_url,alt:z.file,style:{maxWidth:"100%",height:"auto"}}):b.jsx(Mb,{remarkPlugins:[qb,Ib],components:{a:({...S})=>b.jsx("a",{...S,target:"_blank",rel:"noopener noreferrer"})},children:z.content??""})})]})})]})}function Fb({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 TO(){const{activeHost:e}=si(),t=A.useRef(null);A.useEffect(()=>{if(Jn.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 u=await l.pushManager.getSubscription();if(!u){const{publicKey:f}=await gE("/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}u=await l.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:f})}const c=u.toJSON();await pE("/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 jO="0.9.9";function Kh(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 vu(){const{removePairedHost:e,setHostLanUrl:t,setHostTimezone:r}=qi(),{connected:s,request:l,subscribeEvents:u,unauthorized:c,activeHost:f}=si(),d=f.hostId,m=f.clientToken||null,y=Mr(),g=cr(),x=Yu(),w=qx("(min-width: 768px)"),_=g.pathname.endsWith("/tasks"),j=x.runId?void 0:x.taskId,D=!!(x.taskId&&x.runId),[N,H]=A.useState(!1),[F,fe]=A.useState(!1),[z,R]=A.useState(null),[ee,$]=A.useState(null),[q,L]=A.useState(null),[G,J]=A.useState(()=>localStorage.getItem(`palmier.${d}.dismissedUpdateVersion`)),[oe,le]=A.useState({}),[K,U]=A.useState({}),[W,ue]=A.useState(null),[we,M]=A.useState(new Set),[P,te]=A.useState([]),[S,xe]=A.useState(),Ae=!!m&&W===m,[ve,Ue]=A.useState(new Map),[Ve,Te]=A.useState(new Map),[et,Pt]=A.useState(new Map),[Gt,Ft]=A.useState(new Map);TO(),A.useEffect(()=>{window.scrollTo(0,0)},[d]),A.useEffect(()=>{let je=!1;return JE().then(Q=>{je||M(Q)}),()=>{je=!0}},[]),A.useEffect(()=>{s&&l("host.info").then(je=>{var Ke,Fe,Ge,$e,Qe,Je;te(je.agents??[]),xe(je.host_platform),ue(je.linked_client_token??null),NE(je.agents??[]);const Q=je.version??null;$(Q),H(!!Q&&Kh(Q,jO)),t(d,je.lan_url??void 0),r(d,je.host_timezone);const he=new Map,_e=new Map,Oe=new Map,Ie=new Map;for(const pe of je.pending_prompts??[])if(pe.type==="confirmation")he.set(pe.key,{description:((Ke=pe.meta)==null?void 0:Ke.description)??"",sessionName:(Fe=pe.meta)==null?void 0:Fe.session_name});else if(pe.type==="permission")_e.set(pe.key,{permissions:pe.params??[],sessionName:(Ge=pe.meta)==null?void 0:Ge.session_name});else if(pe.type==="input"){const Pe=pe.params??(($e=pe.meta)==null?void 0:$e.input_questions)??[];Oe.set(pe.key,{questions:Pe,description:(Qe=pe.meta)==null?void 0:Qe.description,sessionName:(Je=pe.meta)==null?void 0:Je.session_name}),Ie.set(pe.key,new Array(Pe.length).fill(""))}Ue(he),Te(_e),Pt(Oe),Ft(Ie)}).catch(()=>{})},[s,d,l,t,r]),A.useEffect(()=>s?u(d,Q=>{const he=Q.subject.split(".");if(he.length<3)return;const _e=he.slice(2).join(".");let Oe={};try{Oe=JSON.parse(new TextDecoder().decode(Q.data))}catch{return}const Ie=Oe.event_type,Ke=Oe.session_id;if(Ie==="input-request"&&Ke){const Fe=Oe.input_questions,Ge=Oe.session_name,$e=Oe.description;Fe!=null&&Fe.length&&(Pt(Qe=>{if(Qe.has(Ke))return Qe;const Je=new Map(Qe);return Je.set(Ke,{questions:Fe,description:$e,sessionName:Ge}),Je}),Ft(Qe=>{if(Qe.has(Ke))return Qe;const Je=new Map(Qe);return Je.set(Ke,new Array(Fe.length).fill("")),Je}));return}if(Ie==="input-resolved"&&Ke){Pt(Fe=>{if(!Fe.has(Ke))return Fe;const Ge=new Map(Fe);return Ge.delete(Ke),Ge}),Ft(Fe=>{const Ge=new Map(Fe);return Ge.delete(Ke),Ge});return}if(Ie==="confirm-request"&&Ke){const Fe=Oe.description,Ge=Oe.session_name;Fe&&Ue($e=>{if($e.has(Ke))return $e;const Qe=new Map($e);return Qe.set(Ke,{description:Fe,sessionName:Ge}),Qe});return}if(Ie==="confirm-resolved"&&Ke){Ue(Fe=>{if(!Fe.has(Ke))return Fe;const Ge=new Map(Fe);return Ge.delete(Ke),Ge});return}if(Ie==="permission-request"){const Fe=Oe.required_permissions,Ge=Oe.session_name;Fe!=null&&Fe.length&&Te($e=>{if($e.has(_e))return $e;const Qe=new Map($e);return Qe.set(_e,{permissions:Fe,sessionName:Ge}),Qe});return}if(Ie==="permission-resolved"){Te(Fe=>{if(!Fe.has(_e))return Fe;const Ge=new Map(Fe);return Ge.delete(_e),Ge});return}}):void 0,[s,d,u]);async function De(je,Q){try{await l("task.user_input",{id:je,value:[Q]})}catch(he){console.error("[Dashboard] Failed to respond to confirmation:",he)}}async function ot(je,Q){try{await l("task.user_input",{id:je,value:[Q]})}catch(he){console.error("[Dashboard] Failed to respond to permission request:",he)}}async function tt(je,Q){try{await l("task.user_input",{id:je,value:Q})}catch(he){console.error("[Dashboard] Failed to respond to input request:",he)}}function vt(je,Q){if(!ps())return;const he=`/hosts/${encodeURIComponent(d)}/runs/${encodeURIComponent(je)}`;y(Q?`${he}/${encodeURIComponent(Q)}`:he)}A.useEffect(()=>{if(!ee)return;let je=!1;return fetch("https://registry.npmjs.org/palmier/latest").then(Q=>Q.ok?Q.json():null).then(Q=>{!je&&(Q!=null&&Q.version)&&L(Q.version)}).catch(()=>{}),()=>{je=!0}},[ee]),A.useEffect(()=>{let je=!1;const Q={};for(const he of P){if(!he.version)continue;const _e=localStorage.getItem(`palmier.${d}.dismissedAgentUpdate.${he.key}`);_e&&(Q[he.key]=_e)}U(Q);for(const he of P)!he.version||!he.npmPackage||fetch(`https://registry.npmjs.org/${he.npmPackage}/latest`).then(_e=>_e.ok?_e.json():null).then(_e=>{je||!(_e!=null&&_e.version)||le(Oe=>Oe[he.key]===_e.version?Oe:{...Oe,[he.key]:_e.version})}).catch(()=>{});return()=>{je=!0}},[P]);const ft=P.find(je=>{if(!je.version)return!1;const Q=oe[je.key];return!Q||!Kh(je.version,Q)?!1:K[je.key]!==Q});function gn(je,Q){localStorage.setItem(`palmier.${d}.dismissedAgentUpdate.${je}`,Q),U(he=>({...he,[je]:Q}))}async function an(je){fe(!0),R(null);try{const Q=await l("host.updateAgent",{key:je});if(Q.error){R(Q.error),fe(!1);return}const he=await l("host.info");he.agents&&te(he.agents)}catch(Q){R(Q instanceof Error?Q.message:String(Q))}finally{fe(!1)}}const Wt=!N&&!!ee&&!!q&&Kh(ee,q)&&G!==q;function yn(){q&&(localStorage.setItem(`palmier.${d}.dismissedUpdateVersion`,q),J(q))}async function Kn(){fe(!0),R(null);try{const je=await l("host.update");if(je.error){R(je.error),fe(!1);return}}catch{}setTimeout(()=>window.location.reload(),15e3)}const pt=s&&!c;return b.jsxs("div",{className:"dashboard",children:[w&&b.jsx(G0,{daemonVersion:ee,agents:P,linkedClientToken:W,request:l,onEnabledCapabilitiesChange:M,onLinkedClientTokenChange:ue}),b.jsxs("div",{className:"dashboard-content",children:[b.jsxs("header",{className:"app-header",children:[b.jsxs("div",{className:"app-title-bar",children:[!w&&b.jsx(G0,{daemonVersion:ee,agents:P,linkedClientToken:W,request:l,onEnabledCapabilitiesChange:M,onLinkedClientTokenChange:ue}),b.jsx("h1",{className:"app-title",children:"Palmier"}),b.jsx(WE,{})]}),b.jsx("div",{className:"tab-bar",children:b.jsx(YE,{})})]}),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:()=>{ps()&&y("/pair")},children:"Re-pair Device"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{e(d),y("/",{replace:!0})},children:"Remove Host"})]})]}):pt?b.jsxs(b.Fragment,{children:[_&&!D&&b.jsx($E,{connected:s,hostId:d,request:l,subscribeEvents:u,agents:P,hostPlatform:S,isNotificationListener:Ae&&we.has("notifications"),onViewRun:vt}),D?b.jsx(AO,{connected:s,hostId:d,request:l,subscribeEvents:u,taskId:x.taskId,runId:decodeURIComponent(x.runId)}):_?null:b.jsx(rC,{connected:s,hostId:d,request:l,subscribeEvents:u,agents:P,hostPlatform:S,filterTaskId:j,onClearFilter:()=>{ps()&&y(`/hosts/${encodeURIComponent(d)}`)}})]}):b.jsx("div",{className:"empty-state",children:b.jsx("p",{children:"Connecting to host..."})})}),(N||Wt)&&!F&&!z&&b.jsx(Fb,{title:N?"Update Required":"Update Available",message:N?`Your Palmier host${ee?` (v${ee})`:""} is too old for this version of the app. Please update to continue.`:`A new version of Palmier (v${q}) is available. You're running v${ee}.`,onUpdate:Kn,onDismiss:N?void 0:yn}),!N&&!Wt&&ft&&!F&&!z&&b.jsx(Fb,{title:"Agent Update Available",message:`A new version of ${ft.label} (v${oe[ft.key]}) is available. You're running v${ft.version}.`,onUpdate:()=>an(ft.key),onDismiss:()=>gn(ft.key,oe[ft.key])}),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:"Installing update and restarting daemon. Please wait..."})]})}),z&&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:z}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>{R(null)},children:"Retry"})})]})})]}),ds.createPortal(b.jsxs(b.Fragment,{children:[[...ve.entries()].map(([je,{description:Q,sessionName:he}])=>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"}),he&&b.jsx("p",{className:"confirm-modal-subtitle",children:he}),b.jsx("p",{className:"confirm-modal-message",children:Q}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>De(je,"confirmed"),children:"Confirm"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>De(je,"aborted"),children:"Abort"})]})]})},je)),[...Ve.entries()].map(([je,{permissions:Q,sessionName:he}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal permission-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Permission Required"}),b.jsx("p",{className:"confirm-modal-message",children:b.jsx("strong",{children:he||je})}),b.jsx("div",{className:"permission-list",children:Q.map((_e,Oe)=>b.jsxs("div",{className:"permission-item",children:[b.jsx("span",{className:"permission-name",children:_e.name}),_e.description&&b.jsx("span",{className:"permission-desc",children:_e.description})]},Oe))}),b.jsxs("div",{className:"permission-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>ot(je,"granted"),children:"Allow Once"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>ot(je,"granted_all"),children:"Allow Always"})]}),b.jsx("button",{className:"permission-abort-link",onClick:()=>ot(je,"aborted"),children:"Deny & Abort Task"})]})},je)),[...et.entries()].map(([je,{questions:Q,description:he,sessionName:_e}])=>{const Oe=Gt.get(je)??new Array(Q.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:"Input Required"}),_e&&b.jsx("p",{className:"confirm-modal-subtitle",children:_e}),he&&b.jsx("p",{className:"confirm-modal-message",children:he}),b.jsx("div",{className:"input-list",children:Q.map((Ie,Ke)=>b.jsxs("div",{className:"input-item",children:[b.jsx("label",{className:"input-label",children:Ie}),b.jsx("input",{type:"text",className:"input-field",value:Oe[Ke]??"",onChange:Fe=>{Ft(Ge=>{const $e=new Map(Ge),Qe=[...$e.get(je)??[]];return Qe[Ke]=Fe.target.value,$e.set(je,Qe),$e})},autoFocus:Ke===0})]},Ke))}),b.jsx("div",{className:"input-actions",children:b.jsx("button",{className:"btn btn-primary",disabled:Oe.some(Ie=>!Ie.trim()),onClick:()=>tt(je,Oe),children:"Submit"})}),b.jsx("button",{className:"permission-abort-link",onClick:()=>tt(je,["aborted"]),children:"Cancel"})]})},je)})]}),document.body)]})}const NO=ys("Preferences",{web:()=>Fd(()=>import("./web-ZSYmpLle.js"),[]).then(e=>new e.PreferencesWeb)}),kl=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),$b=Jn.isNativePlatform();function OO(){const[e,t]=A.useState(""),[r,s]=A.useState(!0),[l,u]=A.useState(!1),[c,f]=A.useState(null),{addPairedHost:d,pairedHosts:m}=qi(),y=Mr();async function g(){const x=e.trim().toUpperCase();if(!x){f("Enter a pairing code.");return}u(!0),f(null);try{let w;if(kl){const D=await fetch("/pair",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:x,label:navigator.userAgent})});if(!D.ok){const N=await D.json().catch(()=>({error:"Connection failed"}));throw new Error(N.error||`HTTP ${D.status}`)}w=await D.json()}else{const D=await fetch(`${Bu}/api/config`);if(!D.ok)throw new Error("Failed to fetch server config");const N=await D.json();if(!N.natsWsUrl)throw new Error("Server has no NATS WebSocket URL configured");const H=await Dx({servers:N.natsWsUrl,authenticator:Ex(N.natsJwt,new TextEncoder().encode(N.natsNkeySeed))}),F=Ou(),fe=`pair.${x}`,z=await H.request(fe,F.encode(JSON.stringify({label:navigator.userAgent})),{timeout:1e4});w=JSON.parse(F.decode(z.data)),await H.close()}const _={hostId:w.hostId,clientToken:w.clientToken,directUrl:kl?window.location.origin:void 0,...w.hostName?{name:w.hostName}:{}};if(d(_),Jn.isNativePlatform()&&dn){await NO.set({key:"hostId",value:w.hostId});try{const{token:D}=await dn.getFcmToken();await fetch(`${Bu}/api/fcm/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostId:w.hostId,fcmToken:D})})}catch(D){console.warn("FCM token registration failed:",D)}}const j=`/hosts/${encodeURIComponent(w.hostId)}`;y($b&&r?`${j}/pair/setup`:j)}catch(w){const _=w instanceof Error?w.message:String(w);_.includes("timeout")||_.includes("TIMEOUT")||_.includes("503")||_.toLowerCase().includes("no responders")?f("Code not found or expired. Check the code and try again."):f(_)}finally{u(!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:kl?"Pair":"Pair with Host"}),b.jsx("p",{className:"pair-subtitle",children:kl?"Enter the pairing code shown in your terminal.":"Connect this device to a Palmier host"})]}),!kl&&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 at least one agent CLI (e.g., ",b.jsx("a",{href:"https://www.palmier.me/agents",target:"_blank",rel:"noopener noreferrer",children:"Claude Code, Gemini CLI, Codex CLI"}),")"]}),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 RO(){const e=Mr(),{connected:t,request:r,activeHost:s}=si(),{setHostLanUrl:l,pairedHosts:u}=qi(),c=u.length<=1,[f,d]=A.useState("loading"),[m,y]=A.useState(null),[g,x]=A.useState(null);function w(){e(`/hosts/${encodeURIComponent(s.hostId)}`,{replace:!0})}A.useEffect(()=>{if(!t||f!=="loading")return;let H=!1;return r("host.info").catch(()=>({})).then(F=>{if(H)return;l(s.hostId,F.lan_url??void 0);const fe=F.linked_client_token??null;y(fe);const z=!!fe&&fe!==s.clientToken;d(z?"confirming":"linking")}),()=>{H=!0}},[t,f,s,r,l]),A.useEffect(()=>{if(f!=="linking")return;let H=!1;return(async()=>{try{if(dn){const{token:F}=await dn.getFcmToken();if(!F)throw new Error("Could not read FCM token");await r("device.link",{fcmToken:F})}if(H)return;c?d("wizard"):w()}catch(F){if(H)return;x(F instanceof Error?F.message:String(F)),d("linkError")}})(),()=>{H=!0}},[f]);function _(){d("linking")}function j(){w()}function D(){x(null),d("linking")}const N=f==="confirming"&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:j,children:b.jsxs("div",{className:"confirm-modal",onClick:H=>H.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:_,children:"Link"})]})]})}),document.body);if(f==="loading"||f==="confirming"||f==="linking"||f==="linkError"){const H=c,F=f==="loading"||f==="confirming"||f==="linking";return b.jsxs("div",{className:"pair-setup",children:[b.jsxs("div",{className:"pair-setup-inner",children:[H&&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:w,children:"Skip linking"})]})]})]}),N]})}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(Ix,{}),b.jsx("div",{className:"pair-setup-actions",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:w,children:"Finish"})})]})})}function MO(){const e=Mr();return A.useEffect(()=>{if(!dn)return;const t=dn.addListener("deepLink",({path:r})=>e(r));return()=>{t.then(r=>r.remove())}},[e]),null}function DO(){const{pairedHosts:e}=qi();return e.length===0?b.jsx(zl,{to:"/pair",replace:!0}):b.jsx(zl,{to:`/hosts/${encodeURIComponent(e[0].hostId)}`,replace:!0})}function LO(){const{hostId:e}=Yu(),{pairedHosts:t}=qi(),r=t.find(s=>s.hostId===e)??null;return r?b.jsx(vE,{activeHost:r,children:b.jsxs(ax,{children:[b.jsx(br,{index:!0,element:b.jsx(vu,{})}),b.jsx(br,{path:"tasks",element:b.jsx(vu,{})}),b.jsx(br,{path:"runs/:taskId",element:b.jsx(vu,{})}),b.jsx(br,{path:"runs/:taskId/:runId",element:b.jsx(vu,{})}),b.jsx(br,{path:"pair/setup",element:b.jsx(RO,{})}),b.jsx(br,{path:"*",element:b.jsx(zl,{to:".",replace:!0})})]})}):b.jsx(zl,{to:"/",replace:!0})}function zO(){return b.jsxs($_,{children:[b.jsx(MO,{}),b.jsxs(ax,{children:[b.jsx(br,{path:"/",element:b.jsx(DO,{})}),b.jsx(br,{path:"/pair",element:b.jsx(OO,{})}),b.jsx(br,{path:"/hosts/:hostId/*",element:b.jsx(LO,{})}),b.jsx(br,{path:"*",element:b.jsx(zl,{to:"/",replace:!0})})]})]})}fS.createRoot(document.getElementById("root")).render(b.jsx(A.StrictMode,{children:b.jsx(O_,{children:b.jsx(zO,{})})}));export{Id as W};