@appetize/cli 0.28.0 → 0.29.1

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.
@@ -0,0 +1,4 @@
1
+ import Ze from"debug";import{JSONRPCServerAndClient as zr,JSONRPCServer as Dr,JSONRPCClient as Br,JSONRPC as jr}from"json-rpc-2.0";import*as m from"zod/mini";import{writeFileSync as Fr,renameSync as $r,mkdirSync as Lt,readFileSync as Vr,rmSync as qr,readdirSync as Kr}from"node:fs";import{sep as Wr,join as oe}from"node:path";import{homedir as Pt}from"node:os";import{Transform as Jr}from"stream";import{createRequire as Gr}from"module";import{connect as Hr}from"node:net";class Zr extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function Yr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:Zr;return new r(t,e)}class Qr{#e=new EventTarget;addEventListener(e,r,s){return this.#e.addEventListener(e,r,s),()=>{this.#e.removeEventListener(e,r,s)}}removeEventListener(e,r,s){this.#e.removeEventListener(e,r,s)}dispatchEvent(e){return this.#e.dispatchEvent(e)}}const U=Symbol.for("@appetizeio/rpc:rpcMethods");class Xr extends Qr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(Yr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}const es="@appetizeio/rpc:playwrightAdapter";class xe{closed=!1;[U];#e;constructor(e,{signal:r}={}){this[U]=new Xr(e),this.#e=r,this.#e?.addEventListener("abort",this.#r)}close(e={}){this.closed||(this.closed=!0,this.handleClose(e))}handleClose(e){this.#e?.removeEventListener("abort",this.#r),this[U].dispatchClose(e)}#r=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const Ce=Symbol.for(es);function ts(t){window[Ce]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[U].send(r)},subscribe(r){return t[U].addEventListener("message",s=>{r(s.detail)})}};return window[Ce]=e,()=>{window[Ce]===e&&delete window[Ce]}}const Ct=Ze("appetize.io:error:rpc");function Ye(t,e){const r=new zr(new Dr({errorListener:Ct}),rs(t),{errorListener:Ct}),s=t[U].addEventListener("message",({detail:i})=>{r.receiveAndSend(i)}),n=t[U].addEventListener("close",()=>{s(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const i in e){const a=e[i];a&&r.addMethod(i,a.bind(e))}return{rpc:r,unsub:()=>{s(),n()}}}function _t(t,e){const{rpc:r,unsub:s}=Ye(t,e);return{client:r.client,unsub:s}}function _e(t,e){const r=t[U].addEventListener("message",({detail:n})=>{if("method"in n)try{e({method:n.method,param:n.params})}catch{}}),s=t[U].addEventListener("close",r,{once:!0});return()=>{r(),s()}}function rs(t){return new Br(t[U].send.bind(t[U]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function Qe(t,e,{leftEffects:r=()=>({}),notifiesLeft:s,notifiesRight:n,rightEffects:i=()=>({})}={}){const a=Ye(t,{}),y=Ye(e,{}),p=[()=>{a.unsub(),y.unsub()}],A=()=>{for(const _ of p)try{_()}catch{}},E=y.rpc.client,R=a.rpc.client;p.push(t[U].addEventListener("close",()=>{A()},{once:!0}),e[U].addEventListener("close",()=>{A()},{once:!0}));const M=r(E,R);for(const _ in M){const L=M[_];L&&a.rpc.addMethod(_,L)}const N=i(R,E);for(const _ in N){const L=N[_];L&&y.rpc.addMethod(_,L)}return Nt(a.rpc,y.rpc,{notifies:s}),Nt(y.rpc,a.rpc,{notifies:n}),A}function Nt(t,e,{notifies:r}={}){t.applyServerMiddleware(async(s,n)=>{const i=r?.();if(i){const{id:y,...p}=n;i[U].send(p)}if(t.hasMethod(n.method))return await s(n);if(!n.id)return e.notify(n.method,n.params),null;const a=await e.request(n.method,n.params);return{id:n.id,jsonrpc:jr,result:a}})}function re(t,...e){t.notify(e[0],e[1],e[2])}const ss=(...t)=>_t(...t),ns=["h264","jpeg"],Xe=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],zt=["landscapeLeft","landscapeRight","portrait","upsideDown"],is=["dark","light"],os=["xs","s","m","l","xl","xxl","xxxl"];function et(){const t=new xe(async r=>{e[U].dispatchMessage(r)}),e=new xe(async r=>{t[U].dispatchMessage(r)});return t[U].addEventListener("close",()=>{e.close()},{once:!0}),e[U].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function Dt(t,e){const r=[],s=()=>{for(const n of r)n()};r.push(t[U].addEventListener("message",n=>e[U].send(n.detail))),r.push(t[U].addEventListener("close",s,{once:!0})),r.push(e[U].addEventListener("message",n=>t[U].send(n.detail))),r.push(e[U].addEventListener("close",s,{once:!0}))}function tt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}const ae=Ze("appetize.io:trace:transport:iframe");class Bt extends xe{onmessage;#e;#r;constructor(e,{origin:r="*",signal:s}={}){super(async n=>{e.postMessage(n,this.#e)},{signal:s}),this.#r=e,this.#e=r,window.addEventListener("message",this.#t)}postMessage(e,r,s){ae("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#r.postMessage(e,r??this.#e,s)}handleClose(e){ae("close()"),window.removeEventListener("message",this.#t),super.handleClose(e)}#t=async e=>{if(ae("handleMessage()",e),e.source!==this.#r||(ae("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ae("handleMessage() -> origin ok");const r=e.data;if(!tt(r)){ae("handleMessage() -> legacy"),this.onmessage?.(e);return}ae("handleMessage() -> jsonrpc"),this[U].dispatchMessage(r)}}function as(t){return{clearState:async e=>{await t.request("appetizeio.device.server.app.clearState",{appId:e})},launch:async(e,r)=>{await t.request("appetizeio.device.server.app.launch",jt(e,r))},reinstall:async e=>{await t.request("appetizeio.device.server.app.reinstall",{appId:e})},restart:async(e,r)=>{await t.request("appetizeio.device.server.app.restart",jt(e,r))},terminate:async e=>{await t.request("appetizeio.device.server.app.terminate",{appId:e})}}}function jt(t,e){return typeof t=="object"?{...t}:{appId:t,...e}}function Ne(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const cs=2*1024*1024,Ft=Ze("appetize:client:acked-writable-stream");class ls{unacked=0;#e;#r;#t;#s;#n=[];#o;constructor(e){this.#t=e,this.#o=e.window??cs}abort(e){this.#i(e),this.#t.onAbort?.(e)}async close(){await this.#c(()=>this.unacked===0),this.#t.onClose?.()}fail(e){this.#i(e)&&this.#t.onError?.(e)}start(e){this.#e=e}write(e){const r=e.byteLength;return this.unacked+=r,this.#t.send(e).then(()=>{this.unacked-=r,this.#s&&(this.#s.acked+=r),this.#a()},s=>{this.fail(s)}),this.unacked>=this.#o&&!this.#s&&(this.#s={acked:0,at:performance.now()},Ft("window full: %d bytes unacked, writes stalled",this.unacked)),this.#c(()=>this.unacked<this.#o)}#a(){if(this.#s&&this.unacked<=this.#o/2){const e=performance.now()-this.#s.at;Ft("pressure relieved after %dms: %d bytes acked, %s MB/s",Math.round(e),this.#s.acked,(this.#s.acked/Math.max(e,1)/1e3).toFixed(2)),this.#s=void 0}this.#n=this.#n.filter(e=>e.until()?(e.resolve(void 0),!1):!0)}#i(e){if(this.#r)return!1;this.#r={reason:e},this.#e.error(e);const r=this.#n;this.#n=[];for(const s of r)s.reject(e);return!0}#c(e){if(e())return Promise.resolve();const r={...Ne(),until:e};return this.#n.push(r),r.promise}}class fs extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new ls(e);super({abort:s=>{r.abort(s)},close:()=>r.close(),start:s=>{r.start(s)},write:s=>r.write(s)}),this.#e=r}fail(e){this.#e.fail(e)}}const us=1024*1024;class ds{#e;#r=!1;#t;#s;constructor(e){this.#t=e}cancel(e){this.#n(),this.#t?.(e)}close(){this.#n()&&this.#e.close()}error(e){this.#n()&&this.#e.error(e)}pull(){const e=this.#s;this.#s=void 0,e?.resolve(void 0)}async push(e){if(this.#r)return;this.#s??=Ne();const{promise:r}=this.#s;this.#e.enqueue(e),await r}start(e){this.#e=e}#n(){return this.#r?!1:(this.#r=!0,this.pull(),!0)}}class hs extends ReadableStream{#e;constructor({highWaterMark:e=us,onCancel:r}={}){const s=new ds(r);super({cancel:n=>{s.cancel(n)},pull:()=>{s.pull()},start:n=>{s.start(n)}},new ByteLengthQueuingStrategy({highWaterMark:e})),this.#e=s}close(){this.#e.close()}error(e){this.#e.error(e)}push(e){return this.#e.push(e)}}class ps{closed;readable;writable;#e=[];#r;#t;#s;#n;#o;#a="starting";constructor(e,{onClose:r,receiveBuffer:s,sendWindow:n,signal:i}){if(this.#o=e,this.#r=Ne(),this.closed=this.#r.promise,this.closed.catch(ys),this.#s=new hs({highWaterMark:s,onCancel:()=>{this.#i(void 0)}}),this.readable=this.#s,this.#n=new fs({onAbort:()=>{this.#i(void 0)},onClose:()=>{this.#i(void 0)},onError:a=>{this.#i(a)},send:a=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:a}),window:n}),this.writable=this.#n,i){const a=()=>{this.#i(i.reason)};i.addEventListener("abort",a,{once:!0}),this.#e.push(()=>{i.removeEventListener("abort",a)})}this.#e.push(()=>{r(this)})}close=()=>{this.#i(void 0)};detach(){this.#i(void 0,{notifyServer:!1})}async handleData(e){this.#a==="open"&&await this.#s.push(e)}handleStopped({error:e}){this.#a==="open"&&this.#i(e?new Error(e):void 0)}async start(){try{await this.#o.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#i(e),e}if(this.#a==="closed")throw this.#t?this.#t:new Error("The adb tunnel closed before it started");this.#a="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#i(e,{notifyServer:r=!0}={}){if(this.#a!=="closed"){this.#a="closed",this.#t=e,r&&re(this.#o,"appetizeio.device.server.debug.adbTunnel.stop",void 0),e?(this.#s.error(e),this.#n.fail(e)):(this.#s.close(),this.#n.fail(new Error("The adb tunnel has stopped")));for(const s of this.#e)s();e?this.#r.reject(e):this.#r.resolve(void 0)}}}function ys(){}class ws{readable;ready;#e=[];#r=!1;#t;#s;#n;constructor({label:e,onClose:r,signal:s}){this.#s=e,this.ready=new Promise((i,a)=>{this.#n={reject:a,resolve:i}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:i=>{n=i}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#t=n,s){const i=()=>{this.fail(s.reason)};s.addEventListener("abort",i,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",i)})}this.#e.push(()=>{r(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleItem(e){this.#t.enqueue(e)}markReady(){if(!this.#n)return;const{resolve:e}=this.#n;this.#n=void 0,e(this)}async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#o(e){this.#r||(this.#t.close(),this.#a(e))}#a(e){this.#r=!0;for(const r of this.#e)r();this.#n?.reject(e??new Error(`${this.#s} closed before it started`)),this.#n=void 0}}class gs{get subscribers(){return this.#t}#e;#r;#t=new Set;constructor(e){this.#e=e}close(){this.#r=void 0;for(const e of[...this.#t])e.close();this.#t.clear()}add(e){this.#t.add(e)}ensureStarted(){return this.#r||(this.#r=(async()=>{try{return await this.#e.start()}catch(e){throw this.#r=void 0,e}})()),this.#r}release(e){this.#t.delete(e),!(this.#t.size>0||!this.#r)&&(this.#r=void 0,this.#e.stop())}}class $t extends gs{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new ws({label:this.#e,onClose:s=>{this.release(s)},signal:e});this.add(r);try{await this.ensureStarted(),r.markReady()}catch(s){r.fail(s)}return await r.ready}handleNotification(e){for(const r of this.subscribers)r.handleItem(e)}}class ms{#e;#r;#t;#s;constructor(e){this.#s=e,this.#r=new $t({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{re(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#t=new $t({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{re(e,"appetizeio.device.server.debug.proxyIntercept.stop",void 0)}})}close(){this.#e?.detach(),this.#r.close(),this.#t.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new ps(this.#s,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#r.createStream(e)}async createProxyInterceptStream(e){return await this.#t.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#r.handleNotification(e)}handleProxyInterceptEvent(e){this.#t.handleNotification(e)}}function ze(t){return{...bs(t),index:t.index,within:t.within?ze(t.within):void 0}}function bs(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:Es(t.text)}}}function Es(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}const Ss=400,Vt=["byTestId","byText","duration","index","x","y"],vs=new Set(Vt),As=/^-?(?:\d+(?:\.\d*)?|\.\d+)$/u,xs=/^[a-z]$/u,rt=/^\s$/u;class z extends SyntaxError{constructor(e,r,s){super(`${e} at position ${String(r)}`,{cause:s})}}class ks{#e=0;#r;constructor(e){this.#r=e}parse(){const e=[];for(;this.#e<this.#r.length;){const r=this.#i();if(rt.test(r))this.#e++;else if(r===">"){if(this.#r.charAt(this.#e+1)===">")throw new z('Force press ">>" is not supported',this.#e);this.#e++,e.push({kind:"down"})}else if(r==="/")this.#e++,e.push({kind:"up"});else if(r==="{")e.push(this.#o());else{const[s]=this.#r.slice(this.#e,this.#e+2);throw new z(`Unexpected ${JSON.stringify(s)}; write selectors as {...}`,this.#e)}}return e}#t(){const e=this.#e,r=this.#c(s=>s!=="="&&!st(s));if(this.#i()!=="=")return{kind:"bare",name:r,offset:e};if(r.length===0)throw new z('Expected an attribute name before "="',e);return this.#e++,{kind:"attribute",name:r,offset:e,value:this.#a()}}#s(){const e=this.#e;this.#e++;let r="";for(;;){const s=this.#i();if(this.#e++,s==='"')return r;if(s==="\\"){const n=this.#i();if(n!=='"'&&n!=="\\"&&n!=="")throw new z('Only \\" and \\\\ escapes are supported',this.#e-1);this.#e++,r+=n}else{if(s==="")throw new z("Unclosed string",e);r+=s}}}#n(){const e=this.#e;this.#e++;let r="",s=!1;for(;;){const i=this.#i();if(i==="")throw new z("Unclosed regex",e);if(this.#e++,i==="/"&&!s)break;r+=i,i==="\\"?(r+=this.#i(),this.#e++):i==="["?s=!0:i==="]"&&(s=!1)}const n=this.#c(i=>xs.test(i));try{return new RegExp(r,n)}catch(i){throw new z(`Invalid regex /${r}/${n}`,e,i)}}#o(){const e=this.#e;this.#e++;let r;const s={offsets:{}};for(let n=0;;n++){this.#l();const i=this.#i();if(i==="")throw new z('Unclosed "{"',e);if(i==="}"){if(this.#e++,n===0)throw new z('Expected a selector or wait in "{}"',e);return r===void 0?Ts(s,e):{duration:r,kind:"wait"}}const a=this.#t();if(n===0&&a.name==="wait")r=a.kind==="attribute"?Kt(a.value,"wait"):Ss;else{if(r!==void 0)throw new z('"wait" takes no other attributes',a.offset);Is(s,a,n)}}}#a(){const e=this.#e,r=this.#i();let s;if(r==='"')s={kind:"quoted",offset:e,text:this.#s()};else if(r==="/")s={kind:"regex",offset:e,regex:this.#n()};else{const n=this.#c(i=>!st(i));if(n.length===0)throw new z('Expected a value after "="',e);return{kind:"raw",offset:e,text:n}}if(!st(this.#i()))throw new z('Expected a space or "}" after the value',this.#e);return s}#i(){return this.#r.charAt(this.#e)}#c(e){const r=this.#e;for(;this.#e<this.#r.length&&e(this.#i());)this.#e++;return this.#r.slice(r,this.#e)}#l(){this.#c(e=>rt.test(e))}}function qt(t){return new ks(t).parse()}function Is(t,e,r){const{name:s,offset:n}=e;if(e.kind==="attribute"){nt(t,s,n,e.value);return}if(!s.includes(","))throw new z(`Expected key=value, got ${JSON.stringify(s)}`,n);if(r>0)throw new z("Write the x,y position first",n);const[i,a,...y]=s.split(",");if(y.length>0)throw new z("Expected a screen position as x,y",n);const p=n+i.length+1;nt(t,"x",n,{kind:"raw",offset:n,text:i}),nt(t,"y",p,{kind:"raw",offset:p,text:a})}function Os(t){return vs.has(t)}function st(t){return t===""||t==="}"||rt.test(t)}function nt(t,e,r,s){if(!Os(e))throw new z(`Unknown attribute ${JSON.stringify(e)}; expected one of ${Vt.join(", ")}`,r);if(t.offsets[e]!==void 0)throw new z(`Duplicate attribute ${JSON.stringify(e)}`,r);switch(t.offsets[e]=r,e){case"byTestId":case"byText":if(t.byText!==void 0||t.byTestId!==void 0)throw new z("Only one of byText and byTestId may be given",r);e==="byText"?t.byText=Us(s):t.byTestId=Ms(s);return;default:t[e]=Kt(s,e)}}function Ts(t,e){return{duration:t.duration,kind:"move",to:Rs(t,e)}}function Kt(t,e){if(t.kind!=="raw"||!As.test(t.text))throw new z(`"${e}" takes a number`,t.offset);return Number(t.text)}function Rs(t,e){const{byTestId:r,byText:s,index:n,offsets:i,x:a,y}=t;if(s!==void 0)return{by:"text",index:n,text:s,x:a,y};if(r!==void 0)return{by:"testId",index:n,testId:r,x:a,y};if(i.index!==void 0)throw new z('"index" needs byText or byTestId',i.index);if(a===void 0||y===void 0)throw new z("A screen position needs x and y",e);return{by:"position",x:a,y}}function Ms(t){if(t.kind==="regex")throw new z('"byTestId" takes a string',t.offset);return t.text}function Us(t){return t.kind==="regex"?t.regex:t.text}function ke(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...ze(t),x:t.x,y:t.y}}function Ls(t){return t.map(e=>e.kind==="move"?{duration:e.duration,kind:"move",to:ke(e.to)}:e)}function Ps(t){return{press:e=>{re(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function Cs({onRequest:t,parent:e,proxyInlet:r,signal:s}){const n=new Bt(e,{signal:s}),i=[()=>{n.close()}];return Dt(n,r),t&&i.push(_e(n,a=>{t(a,{source:"parent"})})),{cleanup:()=>{for(const a of i)a()},notifies:()=>e===globalThis.window?void 0:n}}function _s({onRequest:t,proxyInlet:e}){const[r,s]=et(),i=[ts(s),()=>{r.close()}];return Dt(r,e),t&&i.push(_e(r,a=>{t(a,{source:"parent"})})),{cleanup:()=>{for(const a of i)a()},notifies:()=>r}}function Ns(t){return{clearKeychain:async()=>{await t.request("appetizeio.device.server.settings.clearKeychain")},setAppearance:async e=>{await t.request("appetizeio.device.server.settings.setAppearance",{appearance:e})},setBiometryEnrolled:async e=>{await t.request("appetizeio.device.server.settings.setBiometryEnrolled",{enrolled:e})},setFontSize:async e=>{await t.request("appetizeio.device.server.settings.setFontSize",{fontSize:e})},setLocation:async({latitude:e,longitude:r})=>{await t.request("appetizeio.device.server.settings.setLocation",{latitude:e,longitude:r})}}}function zs(t){return t.to!==void 0?{from:ke(t.from),kind:"path",to:ke(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?ke(t.from):void 0,kind:"direction"}}function Ds(t){return{down:(e,r)=>{re(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{re(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{re(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const Bs=new Set(Xe),js=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,Fs=/(\{\{|\{[^{}]*\})/u;function $s(t){const e=[];let r="";function s(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[n,i]of t.split(Fs).entries())if(n%2===0){if(i.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=i}else i==="{{"?r+="{":(s(),e.push(qs(i.slice(1,-1))));return s(),e}function Vs(t,e){if(!Bs.has(t))throw e.endsWith(">")?new Error(`Holding a key is not supported: {${e}}`):e.startsWith("/")?new Error(`Releasing a key is not supported: {${e}}`):new Error(`{${e}} does not name a supported key. Supported: ${Xe.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function qs(t){const e=js.exec(t)?.groups,r=e?.key??t;if(Vs(r,t),!e)return{key:r,kind:"press"};const s=Number(e.repeat);if(s<1)throw new Error(`Repeat for {${t}} must be at least 1`);return{key:r,kind:"press",repeat:s}}const Ks=Symbol("@appetizeio/client:v1Compat");function Wt(t){return t?.[Ks]}class Ws{readable;ready;get dimensions(){return this.#s}#e=[];#r=!1;#t;#s;#n;#o;constructor({onClose:e,requestKeyFrame:r,signal:s}){this.#n=r,this.ready=new Promise((i,a)=>{this.#o={reject:a,resolve:i}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#i()},start:i=>{n=i}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#t=n,s){const i=()=>{this.fail(s.reason)};s.addEventListener("abort",i,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",i)})}this.#e.push(()=>{e(this)})}close=()=>{this.#a()};fail(e){this.#a(e)}handleChunk(e){if(this.#o){if(e.type!=="key")return;const{resolve:r}=this.#o;this.#o=void 0,this.#s={height:e.height,width:e.width},r(this)}else e.type==="key"&&(this.#s={height:e.height,width:e.width});this.#t.enqueue(e)}requestKeyFrame=()=>{this.#r||this.#n()};async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#a(e){this.#r||(this.#t.close(),this.#i(e))}#i(e){this.#r=!0;for(const r of this.#e)r();this.#o?.reject(e??new Error("Video stream closed before the first key chunk")),this.#o=void 0}}class Js{#e=!1;#r;#t;#s=new Set;constructor(e){this.#r=e}close(){this.#t=void 0;for(const e of[...this.#s])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Ws({onClose:s=>{this.#o(s)},requestKeyFrame:()=>{this.#a()},signal:e});this.#s.add(r);try{await this.#n()}catch(s){r.fail(s)}return await r.ready}handleChunk(e){e.type==="key"&&(this.#e=!1);for(const r of this.#s)r.handleChunk(e)}#n(){return this.#t?(this.#a(),this.#t):(this.#e=!0,this.#t=(async()=>{try{await this.#r.request("appetizeio.device.server.video.start")}catch(e){throw this.#t=void 0,e}})(),this.#t)}#o(e){this.#s.delete(e),!(this.#s.size>0||!this.#t)&&(this.#t=void 0,re(this.#r,"appetizeio.device.server.video.stop",void 0))}#a(){this.#e||(this.#e=!0,re(this.#r,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class Gs{app;debug;keyboard;settings;touch;video;#e;#r=[];#t;constructor(e,r={}){const s=Wt(r)??{},{baseUrl:n,onClose:i,signal:a}=r;this.#e=n?Hs(n):void 0;const{onRequest:y,parent:p,proxyRequest:A}=s,E=Ys(y);a?.addEventListener("abort",this.close);const[R,M]=et(),[N,_]=et();this.#r.push(()=>{R.close(),M.close(),N.close(),_.close()}),this.#r.push(Qe(_,e,{leftEffects:A}));const L=p==="playwright"?_s({onRequest:E,proxyInlet:N}):p?Cs({onRequest:E,parent:p,proxyInlet:N,signal:a}):void 0;L&&this.#r.push(L.cleanup),this.#r.push(Qe(M,N,{notifiesLeft:L?.notifies}));const{client:Y,unsub:ve}=ss(R,{"appetizeio.device.client.debug.adbTunnel.data":q=>Q.handleAdbTunnelData(q),"appetizeio.device.client.debug.adbTunnel.stopped":async q=>{Q.handleAdbTunnelStopped(q)},"appetizeio.device.client.debug.log.entry":async q=>{Q.handleLogEntry(q)},"appetizeio.device.client.debug.proxyIntercept.event":async q=>{Q.handleProxyInterceptEvent(q)},"appetizeio.device.client.video.chunk":async q=>{k.handleChunk(q)}});this.#t=Y,this.#r.push(ve);const Q=new ms(this.#t);this.#r.push(()=>{Q.close()});const k=new Js(this.#t);this.#r.push(()=>{k.close()}),this.app=as(this.#t),this.debug=Q,this.keyboard=Ps(this.#t),this.settings=Ns(this.#t),this.touch=Ds(this.#t),this.video=k,E&&(this.#r.push(_e(M,q=>{E(q,{source:"self"})})),e instanceof Bt&&this.#r.push(_e(e,q=>{E(q,{source:"iframe"})}))),this.#r.push(()=>i?.())}async addMedia(e,r={}){const{url:s}=await this.#t.request("appetizeio.device.server.media.requestUrl"),n=this.#e?new URL(s,this.#e).href:s,i=await fetch(n,{body:e,headers:{"Content-Type":e.type},method:"POST"});if(!i.ok){const p=await i.text();throw new Error(`Media upload failed: ${String(i.status)} ${p}`.trim())}const a=await i.json(),y=r.name??("name"in e?String(e.name):"");await this.#t.request("appetizeio.device.server.addMedia",{name:y||void 0,url:Zs(a)})}async authenticateBiometry({match:e=!0}={}){await this.#t.request("appetizeio.device.server.authenticateBiometry",{match:e})}close=()=>{for(const e of this.#r)try{e()}catch(r){console.error("Device cleanup error:",r)}};async fold(e){await this.#t.request("appetizeio.device.server.fold",{hinge:e})}async gesture(e,r){await this.#t.request("appetizeio.device.server.gesture",{options:r,steps:Ls(typeof e=="string"?qt(e):e)})}async inspect(e,r){return await this.#t.request("appetizeio.device.server.inspect",{options:r,selector:e?ze(e):void 0})}async open(e){new URL(e),await this.#t.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#t.request("appetizeio.device.server.press",{action:e})}async rotate(e){await this.#t.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(e,r){const s=await this.#t.request("appetizeio.device.server.screenshot",{options:r,selector:e?ze(e):void 0}),n=this.#e?new URL(s.url,this.#e).href:s.url,i=await fetch(n);if(!i.ok)throw new Error(`Screenshot download failed: ${String(i.status)} ${i.statusText}`);const a=i.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await i.arrayBuffer()),mimeType:a}}async shake(){await this.#t.request("appetizeio.device.server.shake")}async swipe(e,r){await this.#t.request("appetizeio.device.server.swipe",{gesture:zs(e),options:r})}async tap(e,r){await this.#t.request("appetizeio.device.server.tap",{options:r,selector:ke(e)})}async type(e,r){await this.#t.request("appetizeio.device.server.type",{options:r,steps:$s(e)})}}function Hs(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}function Zs(t){if(typeof t=="object"&&t!==null&&"url"in t&&typeof t.url=="string")return t.url;throw new Error("Media upload returned no URL")}const Ys=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};let it;try{it=new TextDecoder}catch{}let w,D,f=0;const ot=[],Qs=105,Xs=57342,en=57343,Jt=57337,Gt=6,pe={};let De=11281e4,ye=1681e4,tn=1671e4,we=tn,ce=ot,Ie=0,I={},B,Oe,Te=0,le=0,j,H,F=[],at=[],W,K,X,Ht={useRecords:!1,mapsAsObjects:!0},Re=!1,Zt=2;try{new Function("")}catch{Zt=1/0}class Se{constructor(e){if(e&&((e.keyMap||e._keyMap)&&!e.useRecords&&(e.useRecords=!1,e.mapsAsObjects=!0),e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.getStructures&&(e.getShared=e.getStructures),e.getShared&&!e.structures&&((e.structures=[]).uninitialized=!0),e.keyMap)){this.mapKey=new Map;for(let[r,s]of Object.entries(e.keyMap))this.mapKey.set(s,r)}Object.assign(this,e)}decodeKey(e){return this.keyMap&&this.mapKey.get(e)||e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(e){if(!this._keyMap)return e;let r=new Map;for(let[s,n]of Object.entries(e))r.set(this._keyMap.hasOwnProperty(s)?this._keyMap[s]:s,n);return r}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[s,n]of Object.entries(this._keyMap))this._mapKey.set(n,s)}let r={};return e.forEach((s,n)=>r[Z(this._mapKey.has(n)?this._mapKey.get(n):n)]=s),r}mapDecode(e,r){let s=this.decode(e);return this._keyMap&&s.constructor.name==="Array"?s.map(n=>this.decodeKeys(n)):s}decode(e,r){if(w)return nr(()=>{ut();try{return this?this.decode(e,r):Se.prototype.decode.call(Ht,e,r)}catch(s){throw s&&typeof s=="object"&&Yt.add(s),s}});D=r>-1?r:e.length,f=0,Ie=0,le=0,Oe=null,ce=ot,j=null,w=e;try{K=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(s){throw w=null,e instanceof Uint8Array?s:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof Se){if(I=this,W=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return B=this.structures,je();(!B||B.length>0)&&(B=[])}else I=Ht,(!B||B.length>0)&&(B=[]),W=null;return je()}decodeMultiple(e,r){let s,n=0;try{let i=e.length;Re=!0;let a=this?this.decode(e,i):ht.decode(e,i);if(r){if(r(a)===!1)return;for(;f<i;)if(n=f,r(je())===!1)return}else{for(s=[a];f<i;)n=f,s.push(je());return s}}catch(i){throw i.lastPosition=n,i.values=s,i}finally{Re=!1,ut()}}}const Yt=new WeakSet;let Be;function je(){try{Be=D-f;let t=O();if(j){if(f>=j.postBundlePosition)throw new Error("Unexpected bundle position");f=j.postBundlePosition,j=null}if(f==D)B=null,w=null,H&&(H=null);else if(f>D){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Re)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw ut(),Yt.has(t)?t.incomplete&&(t.incomplete=!1):(t instanceof RangeError&&f+8>D||t&&typeof t.message=="string"&&t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function J(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function O(){if(!(f<D))throw J();let t=w[f++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(f>=D)throw J();t=w[f++];break;case 25:if(e==7)return on();t=K.getUint16(f),f+=2;break;case 26:if(e==7){let r=K.getFloat32(f);if(I.useFloat32>2){let s=dt[(w[f]&127)<<1|w[f+1]>>7];return f+=4,(s*r+(r>0?.5:-.5)>>0)/s}return f+=4,r}if(t=K.getUint32(f),f+=4,e===1)return-1-t;break;case 27:if(e==7){let r=K.getFloat64(f);return f+=8,r}if(e>1){if(K.getUint32(f)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=K.getUint32(f+4)}else I.int64AsNumber?(t=K.getUint32(f)*4294967296,t+=K.getUint32(f+4)):t=K.getBigUint64(f);f+=8;break;case 31:switch(e){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let r=[],s,n=0;for(;(s=O())!=pe;){if(n>=De)throw new Error(`Array length exceeds ${De}`);r[n++]=s}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let i;if(I.mapsAsObjects){let a={},y=0;if(I.keyMap)for(;(i=O())!=pe;){if(y++>=we)throw new Error(`Property count exceeds ${we}`);a[Z(I.decodeKey(i))]=O()}else for(;(i=O())!=pe;){if(y++>=we)throw new Error(`Property count exceeds ${we}`);a[Z(i)]=O()}return a}else{X&&(I.mapsAsObjects=!0,X=!1);let a=new Map;if(I.keyMap){let y=0;for(;(i=O())!=pe;){if(y++>=ye)throw new Error(`Map size exceeds ${ye}`);a.set(I.decodeKey(i),O())}}else{let y=0;for(;(i=O())!=pe;){if(y++>=ye)throw new Error(`Map size exceeds ${ye}`);a.set(i,O())}}return a}case 7:return pe;default:throw new Error("Invalid major type for indefinite length "+e)}default:throw new Error("Unknown token "+t)}switch(e){case 0:return t;case 1:return~t;case 2:if(t>D-f)throw J();return nn(t);case 3:if(le>=f)return Oe.slice(f-Te,(f+=t)-Te);if(t>D-f)throw J();if(le==0&&D<140&&t<32){let n=t<16?er(t):sn(t);if(n!=null)return n}return Xt(t);case 4:if(t>De)throw new Error(`Array length exceeds ${De}`);if(t>D-f||(Be-=t)<0)throw J();let r=new Array(t);for(let n=0;n<t;n++)r[n]=O();return r;case 5:if(I.mapsAsObjects){if(t>we)throw new Error(`Property count exceeds ${we}`);if(t>(D-f)/2)throw J();let n={};if(I.keyMap)for(let i=0;i<t;i++)n[Z(I.decodeKey(O()))]=O();else for(let i=0;i<t;i++)n[Z(O())]=O();return n}else{if(X&&(I.mapsAsObjects=!0,X=!1),t>ye)throw new Error(`Map size exceeds ${ye}`);if(t>(D-f)/2)throw J();let n=new Map;if(I.keyMap)for(let i=0;i<t;i++)n.set(I.decodeKey(O()),O());else for(let i=0;i<t;i++)n.set(O(),O());return n}case 6:if(t>=Jt){let n=B[t&8191];if(n)return n.read||(n.read=ct(n)),n.read();if(t<65536){if(t==en){let i=me(),a=O(),y=O();lt(a,y);let p={};if(I.keyMap)for(let A=2;A<i;A++){let E=I.decodeKey(y[A-2]);p[Z(E)]=O()}else for(let A=2;A<i;A++){let E=y[A-2];p[Z(E)]=O()}return p}else if(t==Xs){let i=me(),a=O();for(let y=2;y<i;y++)lt(a++,O());return O()}else if(t==Jt)return dn();if(I.getShared&&(ft(),n=B[t&8191],n))return n.read||(n.read=ct(n)),n.read()}}let s=F[t];if(s)return s.handlesRead?s(O):s(O());{let n=O();for(let i=0;i<at.length;i++){let a=at[i](t,n);if(a!==void 0)return a}return new fe(n,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let n=(W||ue())[t];if(n!==void 0)return n;throw new Error("Unknown token "+t)}default:throw isNaN(t)?J():new Error("Unknown CBOR token "+t)}}const Qt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ct(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=w[f++];if(r=r&31,r>23)switch(r){case 24:r=w[f++];break;case 25:r=K.getUint16(f),f+=2;break;case 26:r=K.getUint32(f),f+=4;break;default:throw new Error("Expected array header, but got "+w[f-1])}let s=this.compiledReader;for(;s;){if(s.propertyCount===r)return s(O);s=s.next}if(this.slowReads++>=Zt){let i=this.length==r?this:this.slice(0,r);return s=I.keyMap?new Function("r","return {"+i.map(a=>I.decodeKey(a)).map(a=>Qt.test(a)?Z(a)+":r()":"["+JSON.stringify(a)+"]:r()").join(",")+"}"):new Function("r","return {"+i.map(a=>Qt.test(a)?Z(a)+":r()":"["+JSON.stringify(a)+"]:r()").join(",")+"}"),this.compiledReader&&(s.next=this.compiledReader),s.propertyCount=r,this.compiledReader=s,s(O)}let n={};if(I.keyMap)for(let i=0;i<r;i++)n[Z(I.decodeKey(this[i]))]=O();else for(let i=0;i<r;i++)n[Z(this[i])]=O();return n}return t.slowReads=0,e}function Z(t){if(typeof t=="string")return t==="__proto__"?"__proto_":t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";throw new Error("Invalid property name type "+typeof t)}let Xt=Fe;function rn(t){Xt=e();function e(r){return function(n){let i=ce[Ie++];if(i==null){if(j)return Fe(n);let y=t(f,D,n,w);if(typeof y=="string")i=y,ce=ot;else if(ce=y,Ie=1,le=1,i=ce[0],i===void 0)throw new Error("Unexpected end of buffer")}let a=i.length;return a<=n?(f+=n,i):(Oe=i,Te=f,le=f+a,f+=n,i.slice(0,n))}}}function Fe(t){let e;if(t<16&&(e=er(t)))return e;if(t>64&&it)return it.decode(w.subarray(f,f+=t));const r=f+t,s=[];for(e="";f<r;){const n=w[f++];if((n&128)===0)s.push(n);else if((n&224)===192)if(n<194||f>=r||(w[f]&192)!==128)s.push(65533);else{const i=w[f++]&63;s.push((n&31)<<6|i)}else if((n&240)===224){const i=f<r?w[f]:0;if(f>=r||(i&192)!==128||n===224&&i<160||n===237&&i>=160)s.push(65533);else if(f++,f>=r||(w[f]&192)!==128)s.push(65533);else{const a=w[f++]&63;s.push((n&31)<<12|(i&63)<<6|a)}}else if((n&248)===240){const i=f<r?w[f]:0;if(n>244||f>=r||(i&192)!==128||n===240&&i<144||n===244&&i>=144)s.push(65533);else if(f++,f>=r||(w[f]&192)!==128)s.push(65533);else{const a=w[f++]&63;if(f>=r||(w[f]&192)!==128)s.push(65533);else{const y=w[f++]&63;let p=(n&7)<<18|(i&63)<<12|a<<6|y;p-=65536,s.push(p>>>10&1023|55296),s.push(56320|p&1023)}}}else s.push(65533);s.length>=4096&&(e+=V.apply(String,s),s.length=0)}return s.length>0&&(e+=V.apply(String,s)),e}let V=String.fromCharCode;function sn(t){let e=f,r=new Array(t);for(let s=0;s<t;s++){const n=w[f++];if((n&128)>0){f=e;return}r[s]=n}return V.apply(String,r)}function er(t){if(t<4)if(t<2){if(t===0)return"";{let e=w[f++];if((e&128)>1){f-=1;return}return V(e)}}else{let e=w[f++],r=w[f++];if((e&128)>0||(r&128)>0){f-=2;return}if(t<3)return V(e,r);let s=w[f++];if((s&128)>0){f-=3;return}return V(e,r,s)}else{let e=w[f++],r=w[f++],s=w[f++],n=w[f++];if((e&128)>0||(r&128)>0||(s&128)>0||(n&128)>0){f-=4;return}if(t<6){if(t===4)return V(e,r,s,n);{let i=w[f++];if((i&128)>0){f-=5;return}return V(e,r,s,n,i)}}else if(t<8){let i=w[f++],a=w[f++];if((i&128)>0||(a&128)>0){f-=6;return}if(t<7)return V(e,r,s,n,i,a);let y=w[f++];if((y&128)>0){f-=7;return}return V(e,r,s,n,i,a,y)}else{let i=w[f++],a=w[f++],y=w[f++],p=w[f++];if((i&128)>0||(a&128)>0||(y&128)>0||(p&128)>0){f-=8;return}if(t<10){if(t===8)return V(e,r,s,n,i,a,y,p);{let A=w[f++];if((A&128)>0){f-=9;return}return V(e,r,s,n,i,a,y,p,A)}}else if(t<12){let A=w[f++],E=w[f++];if((A&128)>0||(E&128)>0){f-=10;return}if(t<11)return V(e,r,s,n,i,a,y,p,A,E);let R=w[f++];if((R&128)>0){f-=11;return}return V(e,r,s,n,i,a,y,p,A,E,R)}else{let A=w[f++],E=w[f++],R=w[f++],M=w[f++];if((A&128)>0||(E&128)>0||(R&128)>0||(M&128)>0){f-=12;return}if(t<14){if(t===12)return V(e,r,s,n,i,a,y,p,A,E,R,M);{let N=w[f++];if((N&128)>0){f-=13;return}return V(e,r,s,n,i,a,y,p,A,E,R,M,N)}}else{let N=w[f++],_=w[f++];if((N&128)>0||(_&128)>0){f-=14;return}if(t<15)return V(e,r,s,n,i,a,y,p,A,E,R,M,N,_);let L=w[f++];if((L&128)>0){f-=15;return}return V(e,r,s,n,i,a,y,p,A,E,R,M,N,_,L)}}}}}function nn(t){return I.copyBuffers?Uint8Array.prototype.slice.call(w,f,f+=t):w.subarray(f,f+=t)}let tr=new Float32Array(1),$e=new Uint8Array(tr.buffer,0,4);function on(){let t=w[f++],e=w[f++],r=(t&127)>>2;if(r===31)return e||t&3?NaN:t&128?-1/0:1/0;if(r===0){let s=((t&3)<<8|e)/16777216;return t&128?-s:s}return $e[3]=t&128|(r>>1)+56,$e[2]=(t&7)<<5|e>>3,$e[1]=e<<5,$e[0]=0,tr[0]}new Array(4096);class fe{constructor(e,r){this.value=e,this.tag=r}}F[0]=t=>new Date(t),F[1]=t=>new Date(Math.round(t*1e3)),F[2]=t=>{let e=BigInt(0);for(let r=0,s=t.byteLength;r<s;r++)e=BigInt(t[r])+(e<<BigInt(8));return e},F[3]=t=>BigInt(-1)-F[2](t),F[4]=t=>+(t[1]+"e"+t[0]),F[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const lt=(t,e)=>{t=t-57344;let r=B[t];r&&r.isShared&&((B.restoreStructures||(B.restoreStructures=[]))[t]=r),B[t]=e,e.read=ct(e)};F[Qs]=t=>{let e=t.length,r=t[1];lt(t[0],r);let s={};for(let n=2;n<e;n++){let i=r[n-2];s[Z(i)]=t[n]}return s},F[14]=t=>j?j[0].slice(j.position0,j.position0+=t):new fe(t,14),F[15]=t=>j?j[1].slice(j.position1,j.position1+=t):new fe(t,15);let an={Error,RegExp};F[27]=t=>(an[t[0]]||Error)(t[1],t[2]);const rr=t=>{if(!(f<D))throw J();if(w[f++]!=132)throw new Error("Packed values structure must be followed by a 4 element array");let e=t();if(!Array.isArray(e)||!e.length)throw new Error("Packed values structure must be followed by a 4 element array");return W=W?e.concat(W.slice(e.length)):e,W.prefixes=t(),W.suffixes=t(),t()};rr.handlesRead=!0,F[51]=rr,F[Gt]=t=>{if(!W)if(I.getShared)ft();else return new fe(t,Gt);if(typeof t=="number")return W[16+(t>=0?2*t:-2*t-1)];throw new Error("No support for non-integer packed references yet")},F[28]=t=>{H||(H=new Map,H.id=0);let e=H.id++,r=f,s=w[f],n;s>>5==4?n=[]:n={};let i={target:n};H.set(e,i);let a=t();return i.used?(Object.getPrototypeOf(n)!==Object.getPrototypeOf(a)&&(f=r,n=a,H.set(e,{target:n}),a=t()),Object.assign(n,a)):(i.target=a,a)},F[28].handlesRead=!0,F[29]=t=>{let e=H.get(t);return e.used=!0,e.target},F[258]=t=>new Set(t),(F[259]=t=>{let e=I;if(e.mapsAsObjects){e.mapsAsObjects=!1,X=!0;try{return t()}finally{X&&(e.mapsAsObjects=!0,X=!1)}}return t()}).handlesRead=!0;function ge(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function ue(){if(!W)if(I.getShared)ft();else throw new Error("No packed values available");return W}const cn=1399353956;at.push((t,e)=>{if(t>=225&&t<=255)return ge(ue().prefixes[t-224],e);if(t>=28704&&t<=32767)return ge(ue().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return ge(ue().prefixes[t-1879048192],e);if(t>=216&&t<=223)return ge(e,ue().suffixes[t-216]);if(t>=27647&&t<=28671)return ge(e,ue().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return ge(e,ue().suffixes[t-1811939328]);if(t==cn)return{packedValues:W,structures:B.slice(0),version:e};if(t==55799)return e});const ln=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,sr=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],fn=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<sr.length;t++)un(sr[t],fn[t]);function un(t,e){let r="get"+t.name.slice(0,-5),s;typeof t=="function"?s=t.BYTES_PER_ELEMENT:t=null;for(let n=0;n<2;n++){if(!n&&s==1)continue;let i=s==2?1:s==4?2:s==8?3:0;F[n?e:e-4]=s==1||n==ln?a=>{if(!t)throw new Error("Could not find typed array for code "+e);return!I.copyBuffers&&(s===1||s===2&&!(a.byteOffset&1)||s===4&&!(a.byteOffset&3)||s===8&&!(a.byteOffset&7))?new t(a.buffer,a.byteOffset,a.byteLength>>i):new t(Uint8Array.prototype.slice.call(a,0).buffer)}:a=>{if(!t)throw new Error("Could not find typed array for code "+e);let y=new DataView(a.buffer,a.byteOffset,a.byteLength),p=a.length>>i,A=new t(p),E=y[r];for(let R=0;R<p;R++)A[R]=E.call(y,R<<i,n);return A}}}function dn(){let t=me(),e=f+O();for(let s=2;s<t;s++){let n=me();f+=n}let r=f;return f=e,j=[Fe(me()),Fe(me())],j.position0=0,j.position1=0,j.postBundlePosition=f,f=r,O()}function me(){if(!(f<D))throw J();let t=w[f++]&31;if(t>23)switch(t){case 24:if(f>=D)throw J();t=w[f++];break;case 25:if(f+2>D)throw J();t=K.getUint16(f),f+=2;break;case 26:if(f+4>D)throw J();t=K.getUint32(f),f+=4;break}return t}function ft(){if(I.getShared){let t=nr(()=>(w=null,I.getShared()))||{},e=t.structures||[];I.sharedVersion=t.version,W=I.sharedValues=t.packedValues,B===!0?I.structures=B=e:B.splice.apply(B,[0,e.length].concat(e))}}function nr(t){let e=D,r=f,s=Ie,n=Te,i=le,a=Oe,y=ce,p=H,A=j,E=new Uint8Array(w.slice(0,D)),R=B,M=I,N=Re,_=X,L=Be;X=!1;try{return t()}finally{D=e,f=r,Ie=s,Te=n,le=i,Oe=a,ce=y,H=p,j=A,w=E,Re=N,B=R,I=M,X=_,Be=L,K=new DataView(w.buffer,w.byteOffset,w.byteLength)}}function ut(){w=null,H=null,B=null}const dt=new Array(147);for(let t=0;t<256;t++)dt[t]=+("1e"+Math.floor(45.15-t*.30103));let ht=new Se({useRecords:!1});const hn=ht.decode;ht.decodeMultiple;let Ve;try{Ve=new TextEncoder}catch{}let pt,ir;const qe=typeof globalThis=="object"&&globalThis.Buffer,Me=typeof qe<"u",yt=Me?qe.allocUnsafeSlow:Uint8Array,or=Me?qe:Uint8Array,ar=256,cr=Me?4294967296:2144337920;let wt,l,P,o=0,se,$=null;const pn=61440,yn=/[\u0080-\uFFFF]/,G=Symbol("record-id");class lr extends Se{constructor(e){super(e),this.offset=0;let r,s,n,i,a;e=e||{};let y=or.prototype.utf8Write?function(c,g){return l.utf8Write(c,g,l.byteLength-g)}:Ve&&Ve.encodeInto?function(c,g){return Ve.encodeInto(c,l.subarray(g)).written}:!1,p=this,A=e.structures||e.saveStructures,E=e.maxSharedStructures;if(E==null&&(E=A?128:0),E>8190)throw new Error("Maximum maxSharedStructure is 8190");let R=e.sequential;R&&(E=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let M,N,_=e.sharedValues,L;if(_){L=Object.create(null);for(let c=0,g=_.length;c<g;c++)L[_[c]]=c}let Y=[],ve=0,Q=0;this.mapEncode=function(c,g){return this._keyMap&&!this._mapped&&c.constructor.name==="Array"&&(c=c.map(d=>this.encodeKeys(d))),this.encode(c,g)},this.encode=function(c,g){if(l||(l=new yt(8192),P=new DataView(l.buffer,0,8192),o=0),se=l.length-10,se-o<2048?(l=new yt(l.length),P=new DataView(l.buffer,0,l.length),se=l.length-10,o=0):g===hr&&(o=o+7&2147483640),r=o,p.useSelfDescribedHeader&&(P.setUint32(o,3654940416),o+=3),a=p.structuredClone?new Map:null,p.bundleStrings&&typeof c!="string"?($=[],$.size=1/0):$=null,s=p.structures,s){if(s.uninitialized){let h=p.getShared()||{};p.structures=s=h.structures||[],p.sharedVersion=h.version;let u=p.sharedValues=h.packedValues;if(u){L={};for(let b=0,S=u.length;b<S;b++)L[u[b]]=b}}let d=s.length;if(d>E&&!R&&(d=E),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let b,S=s.transitions;for(let v=0,x=u.length;v<x;v++){S[G]===void 0&&(S[G]=h);let T=u[v];b=S[T],b||(b=S[T]=Object.create(null)),S=b}S[G]=h|1048576}}R||(s.nextId=d)}if(n&&(n=!1),i=s||[],N=L,e.pack){let d=new Map;if(d.values=[],d.encoder=p,d.maxValues=e.maxPrivatePackedValues||(L?16:1/0),d.objectMap=L||!1,d.samplingPackedValues=M,Ke(c,d),d.values.length>0){l[o++]=216,l[o++]=51,ee(4);let h=d.values;k(h),ee(0),ee(0),N=Object.create(L||null);for(let u=0,b=h.length;u<b;u++)N[h[u]]=u}}wt=g&Et;try{if(wt)return;if(k(c),$&&$.position&&dr(r,k),p.offset=o,a&&a.idsToInsert){o+=a.idsToInsert.length*2,o>se&&de(o),p.offset=o;let d=mn(l.subarray(r,o),a.idsToInsert);return a=null,d}return g&hr?(l.start=r,l.end=o,l):l.subarray(r,o)}finally{if(s){if(Q<10&&Q++,s.length>E&&(s.length=E),ve>1e4)s.transitions=null,Q=0,ve=0,Y.length>0&&(Y=[]);else if(Y.length>0&&!R){for(let d=0,h=Y.length;d<h;d++)Y[d][G]=void 0;Y=[]}}if(n&&p.saveShared){p.structures.length>E&&(p.structures=p.structures.slice(0,E));let d=l.subarray(r,o);return p.updateSharedData()===!1?p.encode(c):d}g&En&&(o=r)}},this.findCommonStringsToPack=()=>(M=new Map,L||(L=Object.create(null)),c=>{let g=c&&c.threshold||4,d=this.pack?c.maxPrivatePackedValues||16:0;_||(_=this.sharedValues=[]);for(let[h,u]of M)u.count>g&&(L[h]=d++,_.push(h),n=!0);for(;this.saveShared&&this.updateSharedData()===!1;);M=null});const k=c=>{o>se&&(l=de(o));var g=typeof c,d;if(g==="string"){if(N){let S=N[c];if(S>=0){S<16?l[o++]=S+224:(l[o++]=198,S&1?k(15-S>>1):k(S-16>>1));return}else if(M&&!e.pack){let v=M.get(c);v?v.count++:M.set(c,{count:1})}}let h=c.length;if($&&h>=4&&h<1024){if(($.size+=h)>pn){let v,x=($[0]?$[0].length*3+$[1].length:0)+10;o+x>se&&(l=de(o+x)),l[o++]=217,l[o++]=223,l[o++]=249,l[o++]=$.position?132:130,l[o++]=26,v=o-r,o+=4,$.position&&dr(r,k),$=["",""],$.size=0,$.position=v}let S=yn.test(c);$[S?0:1]+=c,l[o++]=S?206:207,k(h);return}let u;h<32?u=1:h<256?u=2:h<65536?u=3:u=5;let b=h*3;if(o+b>se&&(l=de(o+b)),h<64||!y){let S,v,x,T=o+u;for(S=0;S<h;S++)v=c.charCodeAt(S),v<128?l[T++]=v:v<2048?(l[T++]=v>>6|192,l[T++]=v&63|128):(v&64512)===55296&&((x=c.charCodeAt(S+1))&64512)===56320?(v=65536+((v&1023)<<10)+(x&1023),S++,l[T++]=v>>18|240,l[T++]=v>>12&63|128,l[T++]=v>>6&63|128,l[T++]=v&63|128):(l[T++]=v>>12|224,l[T++]=v>>6&63|128,l[T++]=v&63|128);d=T-o-u}else d=y(c,o+u,b);d<24?l[o++]=96|d:d<256?(u<2&&l.copyWithin(o+2,o+1,o+1+d),l[o++]=120,l[o++]=d):d<65536?(u<3&&l.copyWithin(o+3,o+2,o+2+d),l[o++]=121,l[o++]=d>>8,l[o++]=d&255):(u<5&&l.copyWithin(o+5,o+3,o+3+d),l[o++]=122,P.setUint32(o,d),o+=4),o+=d}else if(g==="number")if(!this.alwaysUseFloat&&c>>>0===c)c<24?l[o++]=c:c<256?(l[o++]=24,l[o++]=c):c<65536?(l[o++]=25,l[o++]=c>>8,l[o++]=c&255):(l[o++]=26,P.setUint32(o,c),o+=4);else if(!this.alwaysUseFloat&&c>>0===c)c>=-24?l[o++]=31-c:c>=-256?(l[o++]=56,l[o++]=~c):c>=-65536?(l[o++]=57,P.setUint16(o,~c),o+=2):(l[o++]=58,P.setUint32(o,~c),o+=4);else if(!this.alwaysUseFloat&&c<0&&c>=-4294967296&&Math.floor(c)===c)l[o++]=58,P.setUint32(o,-1-c),o+=4;else{let h;if((h=this.useFloat32)>0&&c<4294967296&&c>=-2147483648){l[o++]=250,P.setFloat32(o,c);let u;if(h<4||(u=c*dt[(l[o]&127)<<1|l[o+1]>>7])>>0===u){o+=4;return}else o--}l[o++]=251,P.setFloat64(o,c),o+=8}else if(g==="object")if(!c)l[o++]=246;else{if(a){let u=a.get(c);if(u){if(l[o++]=216,l[o++]=29,l[o++]=25,!u.references){let b=a.idsToInsert||(a.idsToInsert=[]);u.references=[],b.push(u)}u.references.push(o-r),o+=2;return}else a.set(c,{offset:o-r})}let h=c.constructor;if(h===Object)this.skipFunction===!0&&(c=Object.fromEntries([...Object.keys(c).filter(u=>typeof c[u]!="function").map(u=>[u,c[u]])])),q(c);else if(h===Array){d=c.length,d<24?l[o++]=128|d:ee(d);for(let u=0;u<d;u++)k(c[u])}else if(h===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(l[o++]=217,l[o++]=1,l[o++]=3),d=c.size,d<24?l[o++]=160|d:d<256?(l[o++]=184,l[o++]=d):d<65536?(l[o++]=185,l[o++]=d>>8,l[o++]=d&255):(l[o++]=186,P.setUint32(o,d),o+=4),p.keyMap)for(let[u,b]of c)k(p.encodeKey(u)),k(b);else for(let[u,b]of c)k(u),k(b);else{for(let u=0,b=pt.length;u<b;u++){let S=ir[u];if(c instanceof S){let v=pt[u],x=v.tag;x==null&&(x=v.getTag&&v.getTag.call(this,c)),x<24?l[o++]=192|x:x<256?(l[o++]=216,l[o++]=x):x<65536?(l[o++]=217,l[o++]=x>>8,l[o++]=x&255):x>-1&&(l[o++]=218,P.setUint32(o,x),o+=4),v.encode.call(this,c,k,de);return}}if(c[Symbol.iterator]){if(wt){let u=new Error("Iterable should be serialized as iterator");throw u.iteratorNotHandled=!0,u}l[o++]=159;for(let u of c)k(u);l[o++]=255;return}if(c[Symbol.asyncIterator]||gt(c)){let u=new Error("Iterable/blob should be serialized as iterator");throw u.iteratorNotHandled=!0,u}if(this.useToJSON&&c.toJSON){const u=c.toJSON();if(u!==c)return k(u)}q(c)}}else if(g==="boolean")l[o++]=c?245:244;else if(g==="bigint"){if(c<BigInt(1)<<BigInt(64)&&c>=0)l[o++]=27,P.setBigUint64(o,c);else if(c>-(BigInt(1)<<BigInt(64))&&c<0)l[o++]=59,P.setBigUint64(o,-c-BigInt(1));else if(this.largeBigIntToFloat)l[o++]=251,P.setFloat64(o,Number(c));else{c>=BigInt(0)?l[o++]=194:(l[o++]=195,c=BigInt(-1)-c);let h=[];for(;c;)h.push(Number(c&BigInt(255))),c>>=BigInt(8);mt(new Uint8Array(h.reverse()),de);return}o+=8}else if(g==="undefined")l[o++]=247;else throw new Error("Unknown type: "+g)},q=this.useRecords===!1?this.variableMapSize?c=>{let g=Object.keys(c),d=Object.values(c),h=g.length;if(h<24?l[o++]=160|h:h<256?(l[o++]=184,l[o++]=h):h<65536?(l[o++]=185,l[o++]=h>>8,l[o++]=h&255):(l[o++]=186,P.setUint32(o,h),o+=4),p.keyMap)for(let u=0;u<h;u++)k(p.encodeKey(g[u])),k(d[u]);else for(let u=0;u<h;u++)k(g[u]),k(d[u])}:c=>{l[o++]=185;let g=o-r;o+=2;let d=0;if(p.keyMap)for(let h in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(h))&&(k(p.encodeKey(h)),k(c[h]),d++);else for(let h in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(h))&&(k(h),k(c[h]),d++);l[g+++r]=d>>8,l[g+r]=d&255}:(c,g)=>{let d,h=i.transitions||(i.transitions=Object.create(null)),u=0,b=0,S,v;if(this.keyMap){v=Object.keys(c).map(T=>this.encodeKey(T)),b=v.length;for(let T=0;T<b;T++){let Ut=v[T];d=h[Ut],d||(d=h[Ut]=Object.create(null),u++),h=d}}else for(let T in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(T))&&(d=h[T],d||(h[G]&1048576&&(S=h[G]&65535),d=h[T]=Object.create(null),u++),h=d,b++);let x=h[G];if(x!==void 0)x&=65535,l[o++]=217,l[o++]=x>>8|224,l[o++]=x&255;else if(v||(v=h.__keys__||(h.__keys__=Object.keys(c))),S===void 0?(x=i.nextId++,x||(x=0,i.nextId=1),x>=ar&&(i.nextId=(x=E)+1)):x=S,i[x]=v,x<E){l[o++]=217,l[o++]=x>>8|224,l[o++]=x&255,h=i.transitions;for(let T=0;T<b;T++)(h[G]===void 0||h[G]&1048576)&&(h[G]=x),h=h[v[T]];h[G]=x|1048576,n=!0}else{if(h[G]=x,P.setUint32(o,3655335680),o+=3,u&&(ve+=Q*u),Y.length>=ar-E&&(Y.shift()[G]=void 0),Y.push(h),ee(b+2),k(57344+x),k(v),g)return;for(let T in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(T))&&k(c[T]);return}if(b<24?l[o++]=128|b:ee(b),!g)for(let T in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(T))&&k(c[T])},de=c=>{let g;if(c>16777216){if(c-r>cr)throw new Error("Encoded buffer would be larger than maximum buffer size");g=Math.min(cr,Math.round(Math.max((c-r)*(c>67108864?1.25:2),4194304)/4096)*4096)}else g=(Math.max(c-r<<2,l.length-1)>>12)+1<<12;let d=new yt(g);return P=new DataView(d.buffer,0,g),l.copy?l.copy(d,0,r,c):d.set(l.slice(r,c)),o-=r,r=0,se=d.length-10,l=d};let ie=100,Tt=1e3;this.encodeAsIterable=function(c,g){return Rt(c,g,he)},this.encodeAsAsyncIterable=function(c,g){return Rt(c,g,Mt)};function*he(c,g,d){let h=c.constructor;if(h===Object){let u=p.useRecords!==!1;u?q(c,!0):fr(Object.keys(c).length,160);for(let b in c){let S=c[b];u||k(b),S&&typeof S=="object"?g[b]?yield*he(S,g[b]):yield*He(S,g,b):k(S)}}else if(h===Array){let u=c.length;ee(u);for(let b=0;b<u;b++){let S=c[b];S&&(typeof S=="object"||o-r>ie)?g.element?yield*he(S,g.element):yield*He(S,g,"element"):k(S)}}else if(c[Symbol.iterator]&&!c.buffer){l[o++]=159;for(let u of c)u&&(typeof u=="object"||o-r>ie)?g.element?yield*he(u,g.element):yield*He(u,g,"element"):k(u);l[o++]=255}else gt(c)?(fr(c.size,64),yield l.subarray(r,o),yield c,Ae()):c[Symbol.asyncIterator]?(l[o++]=159,yield l.subarray(r,o),yield c,Ae(),l[o++]=255):k(c);d&&o>r?yield l.subarray(r,o):o-r>ie&&(yield l.subarray(r,o),Ae())}function*He(c,g,d){let h=o-r;try{k(c),o-r>ie&&(yield l.subarray(r,o),Ae())}catch(u){if(u.iteratorNotHandled)g[d]={},o=r+h,yield*he.call(this,c,g[d]);else throw u}}function Ae(){ie=Tt,p.encode(null,Et)}function Rt(c,g,d){return g&&g.chunkThreshold?ie=Tt=g.chunkThreshold:ie=100,c&&typeof c=="object"?(p.encode(null,Et),d(c,p.iterateProperties||(p.iterateProperties={}),!0)):[p.encode(c)]}async function*Mt(c,g){for(let d of he(c,g,!0)){let h=d.constructor;if(h===or||h===Uint8Array)yield d;else if(gt(d)){let u=d.stream().getReader(),b;for(;!(b=await u.read()).done;)yield b.value}else if(d[Symbol.asyncIterator])for await(let u of d)Ae(),u?yield*Mt(u,g.async||(g.async={})):yield p.encode(u);else yield d}}}useBuffer(e){l=e,P=new DataView(l.buffer,l.byteOffset,l.byteLength),o=0}clearSharedData(){this.structures&&(this.structures=[]),this.sharedValues&&(this.sharedValues=void 0)}updateSharedData(){let e=this.sharedVersion||0;this.sharedVersion=e+1;let r=this.structures.slice(0),s=new ur(r,this.sharedValues,this.sharedVersion),n=this.saveShared(s,i=>(i&&i.version||0)==e);return n===!1?(s=this.getShared()||{},this.structures=s.structures||[],this.sharedValues=s.packedValues,this.sharedVersion=s.version,this.structures.nextId=this.structures.length):r.forEach((i,a)=>this.structures[a]=i),n}}function fr(t,e){t<24?l[o++]=e|t:t<256?(l[o++]=e|24,l[o++]=t):t<65536?(l[o++]=e|25,l[o++]=t>>8,l[o++]=t&255):(l[o++]=e|26,P.setUint32(o,t),o+=4)}class ur{constructor(e,r,s){this.structures=e,this.packedValues=r,this.version=s}}function ee(t){t<24?l[o++]=128|t:t<256?(l[o++]=152,l[o++]=t):t<65536?(l[o++]=153,l[o++]=t>>8,l[o++]=t&255):(l[o++]=154,P.setUint32(o,t),o+=4)}const wn=typeof Blob>"u"?function(){}:Blob;function gt(t){if(t instanceof wn)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function Ke(t,e){switch(typeof t){case"string":if(t.length>3){if(e.objectMap[t]>-1||e.values.length>=e.maxValues)return;let s=e.get(t);if(s)++s.count==2&&e.values.push(t);else if(e.set(t,{count:1}),e.samplingPackedValues){let n=e.samplingPackedValues.get(t);n?n.count++:e.samplingPackedValues.set(t,{count:1})}}break;case"object":if(t)if(t instanceof Array)for(let s=0,n=t.length;s<n;s++)Ke(t[s],e);else{let s=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(s&&Ke(r,e),Ke(t[r],e))}break;case"function":console.log(t)}}const gn=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;ir=[Date,Set,Error,RegExp,fe,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,ur],pt=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(l[o++]=26,P.setUint32(o,r),o+=4):(l[o++]=251,P.setFloat64(o,r),o+=8)}},{tag:258,encode(t,e){let r=Array.from(t);e(r)}},{tag:27,encode(t,e){e([t.name,t.message])}},{tag:27,encode(t,e){e(["RegExp",t.source,t.flags])}},{getTag(t){return t.tag},encode(t,e){e(t.value)}},{encode(t,e,r){mt(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Me&&this.tagUint8Array!==!1))return 64},encode(t,e,r){mt(t,r)}},te(68,1),te(69,2),te(70,4),te(71,8),te(72,1),te(77,2),te(78,4),te(79,8),te(85,4),te(86,8),{encode(t,e){let r=t.packedValues||[],s=t.structures||[];if(r.values.length>0){l[o++]=216,l[o++]=51,ee(4);let n=r.values;e(n),ee(0),ee(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let i=0,a=n.length;i<a;i++)packedObjectMap[n[i]]=i}if(s){P.setUint32(o,3655335424),o+=3;let n=s.slice(0);n.unshift(57344),n.push(new fe(t.version,1399353956)),e(n)}else e(new fe(t.version,1399353956))}}];function te(t,e){return!gn&&e>1&&(t-=4),{tag:t,encode:function(s,n){let i=s.byteLength,a=s.byteOffset||0,y=s.buffer||s;n(Me?qe.from(y,a,i):new Uint8Array(y,a,i))}}}function mt(t,e){let r=t.byteLength;r<24?l[o++]=64+r:r<256?(l[o++]=88,l[o++]=r):r<65536?(l[o++]=89,l[o++]=r>>8,l[o++]=r&255):(l[o++]=90,P.setUint32(o,r),o+=4),o+r>=l.length&&e(o+r),l.set(t.buffer?t:new Uint8Array(t),o),o+=r}function mn(t,e){let r,s=e.length*2,n=t.length-s;e.sort((i,a)=>i.offset>a.offset?1:-1);for(let i=0;i<e.length;i++){let a=e[i];a.id=i;for(let y of a.references)t[y++]=i>>8,t[y]=i&255}for(;r=e.pop();){let i=r.offset;t.copyWithin(i+s,i,n),s-=2;let a=i+s;t[a++]=216,t[a++]=28,n=i}return t}function dr(t,e){P.setUint32($.position+t,o-$.position-t+1);let r=$;$=null,e(r[0]),e(r[1])}let bt=new lr({useRecords:!1});const bn=bt.encode;bt.encodeAsIterable,bt.encodeAsAsyncIterable;const hr=512,En=1024,Et=2048;class Sn extends Jr{constructor(e){e||(e={}),e.objectMode=!0,super(e),e.structures=[],this.decoder=e.decoder||new Se(e)}_transform(e,r,s){this.incompleteBuffer&&(e=Buffer.concat([this.incompleteBuffer,e]),this.incompleteBuffer=null);let n,i;try{n=this.decoder.decodeMultiple(e)}catch(a){n=a.values,a.incomplete?this.incompleteBuffer=e.slice(a.lastPosition):i=a}for(let a of n||[])a===null&&(a=this.getNullValue()),this.push(a);s(i)}getNullValue(){return Symbol.for(null)}}const vn=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!vn){let t;try{typeof require=="function"?t=require("cbor-extract"):t=Gr(import.meta.url)("cbor-extract"),t&&rn(t.extractStrings)}catch{}}const pr=is,yr=os;function An(t){return{adbShellCommand:t.android?.shell,appearance:t.appearance,deviceType:t.id,disableVirtualKeyboard:t.android?.softKeyboard===!1?!0:void 0,fontSize:t.fontSize,iosAutocorrect:t.ios?.autocorrect,iosKeyboard:t.ios?.keyboards,language:t.locale,locale:t.locale,location:t.location&&[t.location.latitude,t.location.longitude],orientation:t.orientation,osVersion:t.osVersion,timezone:t.timezone}}const wr=["grant"];function xn(t){return{grantPermissions:t?.permissions==="grant"?!0:void 0,launchApp:t?.app,launchArgs:t?.ios?.args,launchUrl:t?.url,params:t?.params}}class gr extends Error{code;issues;constructor(e,r,s=[]){super(r),this.name="SessionRequestError",this.code=e,this.issues=s}}const C=t=>`expected ${t}`,be=t=>m.string(C(t)).check(m.minLength(1,C(t))),Ue=t=>m.literal(t,C(`one of ${t.join(", ")}`)),Ee=t=>m.object(t,C("an object")),mr=()=>m.boolean(C("true or false")),br=t=>m.number(C("a number")).check(m.gte(-t,C(`at least -${String(t)}`)),m.lte(t,C(`at most ${String(t)}`))),kn=/^\w{2}(?:_\w{2})?@sw(=[\w-]+)?$/,In=/^[a-z0-9_.=:/ ()"-]+$/i,On='letters, digits or _ . = : / ( ) " - and spaces',Tn=/^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})*$/;function Rn(t){if(!Tn.test(t))return!1;try{return new Intl.Locale(t.replaceAll("_","-")),!0}catch{return!1}}function Mn(t){try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),!0}catch{return!1}}const St={code:"needsTarget"},Er={code:"needsLaunchApp"},vt="has no effect without a target",Sr="has no effect without a target, or with launch.app: false";function vr({launch:t}){return t?.app!==!1}const Un=m.object({apiToken:m.optional(be("an API token")),codec:m.optional(Ue(ns)),device:Ee({android:m.optional(Ee({shell:m.optional(be("a shell command")),softKeyboard:m.optional(mr())})),appearance:m.optional(Ue(pr)),fontSize:m.optional(Ue(yr)),id:be("a device id"),ios:m.optional(Ee({autocorrect:m.optional(mr()),keyboards:m.optional(m.array(m.string(C("a keyboard layout")).check(m.regex(kn,C("a layout like en_US@sw=QWERTY"))),C("a list of keyboard layouts")))})),locale:m.optional(m.string(C("a BCP 47 tag, e.g. fr-CA")).check(m.refine(Rn,{error:C("a BCP 47 tag, e.g. fr-CA")}))),location:m.optional(Ee({latitude:br(90),longitude:br(180)})),orientation:m.optional(Ue(zt)),osVersion:m.optional(be("an OS version")),timezone:m.optional(m.string(C("an IANA timezone")).check(m.refine(Mn,{error:C("an IANA timezone, e.g. America/Toronto")})))}),endpoint:m.optional(m.url(C("a URL"))),launch:m.optional(Ee({app:m.optional(m.union([be("an app id"),m.literal(!1)],C("an app id or false"))),ios:m.optional(Ee({args:m.optional(m.array(m.string(C("an argument")).check(m.regex(In,C(On))),C("a list of arguments")).check(m.maxLength(20,C("at most 20 arguments"))))})),params:m.optional(m.custom(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),C("an object"))),permissions:m.optional(Ue(wr)),url:m.optional(m.url(C("a URL")))})),proxy:m.optional(m.union([m.literal("intercept"),m.templateLiteral(["http://",m.string()])],C("intercept or an http:// URL"))),target:m.optional(be("an app, build or group id"))}).check(m.refine(t=>t.device.android?.shell===void 0||t.target!==void 0,{error:vt,params:St,path:["device","android","shell"]}),m.refine(t=>t.launch?.app===void 0||t.target!==void 0,{error:vt,params:St,path:["launch","app"]}),m.refine(t=>t.launch?.permissions===void 0||t.target!==void 0,{error:vt,params:St,path:["launch","permissions"]}),m.refine(t=>t.launch?.params===void 0||t.target!==void 0&&vr(t),{error:Sr,params:Er,path:["launch","params"]}),m.refine(t=>t.launch?.ios?.args===void 0||t.target!==void 0&&vr(t),{error:Sr,params:Er,path:["launch","ios","args"]}));function Ln(t){if(t.code==="custom"){const e=t.params?.code;if(e==="needsTarget"||e==="needsLaunchApp")return e}return"invalidValue"}function Pn(t){const e=Un.safeParse(t);if(e.success)return;const r=e.error.issues.map(s=>({code:Ln(s),message:s.message,path:s.path.join(".")}));throw new gr("invalid",r.map(({message:s,path:n})=>`${n}: ${s}`).join(`
2
+ `),r)}const Cn={dateStyle:"medium",timeStyle:"short"},_n=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;function We(t){return Array.isArray(t)?t.map(We).join(", "):typeof t=="boolean"?t?"yes":"no":typeof t=="number"?t.toLocaleString():Nn(t)}function Nn(t){if(_n.test(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r.toLocaleString(void 0,Cn)}const e=Pt();return t===e?"~":t.startsWith(`${e}${Wr}`)?`~${t.slice(e.length)}`:t}function Ar(){return process.env.APPETIZE_CLI_HOME??oe(Pt(),".appetize","cli","sessions")}function At(t){return oe(Ar(),t)}class Je extends Error{details;constructor(e,r={},s){super(e,s===void 0?void 0:{cause:s}),this.name="CommandError",this.details=r}hints(e){return[]}}class Pe extends Je{sessionDir;constructor(e,{cause:r,details:s={},sessionId:n}){const i=At(n);super(e,Object.assign({sessionDir:i},s),r),this.name="SessionError",this.sessionDir=i}static wrap(e,r){if(e instanceof Pe||e instanceof ne)return e;const s=e instanceof Error?e.message:String(e),n=e instanceof Je?e.details:{};return new Pe(s,{cause:e,details:n,sessionId:r})}hints(){return[`Check the session logs for details: ${We(this.sessionDir)}`]}}class zn extends Pe{constructor(e){super(`Session ${e} already exists`,{sessionId:e}),this.name="SessionAlreadyExistsError"}hints(){return[`Pass --force to replace it, deleting ${We(this.sessionDir)}`]}}class ne extends Je{#e;constructor(e,r=[]){super(e),this.name="UsageError",this.#e=r}hints({command:e}){return[...this.#e,`Run 'appetize ${e} --help' for usage`]}}function Dn(t,e,r){const s=e instanceof Error?e.message:String(e);if(!(e instanceof Je))return t==="json"?JSON.stringify({error:{message:s}},null,2):`\u2716 ${s}`;const n=e.hints(r);if(t==="json"){const i=n.length>0?{hints:n}:{};return JSON.stringify({error:{message:s,...e.details,...i}},null,2)}return[`\u2716 ${s}`,...n.map(i=>` ${i}`)].join(`
3
+ `)}function xt(t){try{return process.kill(t,0),!0}catch{return!1}}const Bn=["SIGINT","SIGTERM"],jn=150;function Fn(t){const e=new AbortController,r=setInterval(()=>{xt(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},jn);return r.unref(),e.signal}function xr(){const t=new AbortController;for(const e of Bn)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function $n(t,e){return new Promise((r,s)=>{if(e.aborted){s(kr(e.reason));return}const n=()=>{clearTimeout(i),s(kr(e.reason))},i=setTimeout(()=>{e.removeEventListener("abort",n),r()},t);e.addEventListener("abort",n,{once:!0})})}function kr(t){return t instanceof Error?t:new Error(String(t))}function Vn(t){return Object.values(t).some(e=>e!==void 0)?t:void 0}function qn(t,{defaultValue:e=!1}={}){return t===!e?!e:void 0}function Kn(t,e,r){const s=Ge(t,r);if(s===void 0)return;const n=e.find(i=>i===s);if(n===void 0)throw new ne(`${r} expects one of ${e.join(", ")}`);return n}function Wn(t){const e=t.at(-1);return{options:Hn(e)?e:{},positionals:t.slice(0,-1).filter(r=>typeof r=="string"),signal:xr()}}function Jn(t,e){const r=Ir(t,e);return r===void 0?void 0:Or(r,e)}function Ir(t,e){if(t===void 0)return;const r=typeof t=="boolean"?Number.NaN:Number(t);if(!Number.isFinite(r))throw new ne(`${e} expects a number, e.g., ${e}=-0.1`);return r}function Gn(t,e){return t===void 0?void 0:(Array.isArray(t)?t:[t]).map(s=>Tr(s,e))}function Ge(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new ne(`${e} needs a value`);return t}}function Or(t,e){if(!(t>=0&&t<=1))throw new ne(`${e} expects a number between 0 and 1`);return t}function Tr(t,e){const r=Ge(t,e);if(r===void 0)throw new ne(`${e} needs a value`);return r}function Hn(t){return typeof t=="object"&&t!==null}const Zn="APPETIZEIO_FEATURE_FLAGS";function Yn(){const t={};for(const e of(process.env[Zn]??"").split(",")){const r=e.trim();r!==""&&(t[r]=!0)}return t}function Qn(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function Rr(t){return Ge(t.endpoint,"--endpoint")??Xn()}function Xn(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const ei="https://appetize.io";async function Mr(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const i=new URL(t,Rr(r)??ei);for(const[p,A]of Object.entries(s))i.searchParams.set(p,A);const a=new Headers(n.headers);e&&a.set("x-api-key",Qn());const y=await fetch(i,{...n,headers:a});if(!y.ok)throw new Error(await ri(y));return await y.json()}function ti(t){if(!(typeof t!="object"||t===null||!("message"in t)))return typeof t.message=="string"?t.message:void 0}async function ri(t){const e=`The webserver rejected the request (${String(t.status)})`,r=await t.json().catch(()=>{}),s=ti(r);return s?`${e}: ${s}`:e}const Ur=["android","ios"];function Lr(t={},e){return Mr("/api/v2/service/devices",{authorize:!1,commandOptions:t,signal:e})}function si(t){return Ur.includes(t)}async function ni(t,e={}){return(await Lr(e)).find(s=>s.id===t)?.platform}function ii(t){let e={...t,updatedAt:new Date().toISOString()};return{path:It(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},hi(e),e)}}function Pr(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:xt(t.pid)}function oi(){const t=Ar();return Lt(t,{recursive:!0}),Kr(t).map(e=>kt(e)).filter(e=>e!==void 0)}function ai(t){if(t!==void 0){const r=kt(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=oi().filter(Pr);if(e.length===0)throw new Error("No active sessions");if(e.length>1)throw new ne("There are multiple active sessions",["Specify --session-id to pick one"]);return e[0]}function kt(t){try{return JSON.parse(Vr(It(t),"utf8"))}catch{return}}function ci(t){qr(At(t),{force:!0,recursive:!0})}function li(t){return oe(Le(t),"control.sock")}function Cr(t){return oe(Le(t),"daemon.log")}function fi(t){return oe(Le(t),"device.log.jsonl")}function ui(t,e){return{daemon:Cr(t),device:fi(t),...e==="intercept"?{network:di(t)}:void 0}}function di(t){return oe(Le(t),"network.jsonl")}function Le(t){const e=At(t);return Lt(e,{recursive:!0}),e}function It(t){return oe(Le(t),"state.json")}function hi(t){const e=It(t.sessionId),r=`${e}.tmp`;Fr(r,`${JSON.stringify(t,null,2)}
4
+ `),$r(r,e)}const Ot="APPETIZE_DAEMON_CONFIG";function pi(){const t=process.env[Ot];if(!t)throw new Error(`${Ot} is not set`);return JSON.parse(t)}function yi(t){return JSON.stringify(t)}function wi(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const _r={useRecords:!1},gi=new lr(_r);class Nr extends xe{#e=[];#r;constructor(e,{signal:r}={}){super(async a=>{this.#r.write(gi.encode(a))},{signal:r}),this.#r=e;const s=new Sn(_r);s.on("data",a=>{tt(a)&&this[U].dispatchMessage(a)}),s.on("error",()=>{this.close()});const n=a=>{s.write(a)},i=()=>{this.close()};e.on("data",n),e.once("close",i),e.once("error",i),this.#e.push(()=>{e.off("data",n),e.off("close",i),e.off("error",i),s.destroy()})}handleClose(e){for(const r of this.#e.splice(0))r();super.handleClose(e)}}function mi(t,e){const{promise:r,reject:s,resolve:n}=wi(),i=Hr(t),a=e?.signal,y=()=>{i.off("connect",E),i.off("error",R),a?.removeEventListener("abort",A)},p=M=>{y(),i.destroy(),s(M)},A=()=>{p(new Error("The connection was aborted"))},E=()=>{y();const M=new Nr(i,e);M[U].addEventListener("close",()=>{i.destroy()},{once:!0}),n(M)},R=M=>{p(M)};return a?.aborted?(p(new Error("The connection was aborted")),r):(i.once("connect",E),i.once("error",R),a?.addEventListener("abort",A,{once:!0}),r)}export{Nr as $,Rr as A,kt as B,zn as C,Ot as D,ci as E,ui as F,Jn as G,We as H,mi as I,Gs as J,_t as K,ai as L,Wn as M,Dn as N,Xe as O,bn as P,U as Q,hn as R,Pe as S,xe as T,ne as U,tt as V,Wt as W,Ne as X,xn as Y,An as Z,Qe as _,Ge as a,pi as a0,ii as a1,ni as a2,li as a3,xr as a4,Kn as b,qn as c,Ir as d,$n as e,Mr as f,Lr as g,Ur as h,si as i,qt as j,Tr as k,wr as l,zt as m,Vn as n,Cr as o,Gn as p,Pr as q,Or as r,yi as s,xt as t,Fn as u,yr as v,pr as w,Pn as x,gr as y,Yn as z};