@appetize/cli 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @appetize/cli
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Minor Changes
6
+
7
+ - feat(session): expose the local browser viewer.
8
+
3
9
  ## 0.15.2
4
10
 
5
11
  ### Patch Changes
package/cli.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- import Se from"sade";import{d as U,D as ve,p as m,a as p,f as $,b as xe,i as Ee,c as be,r as j,e as v,g as Oe,h as $e,s as Ie,j as C,k as Pe,l as Ae,m as J,n as Ne,o as Te,q as De,t as ke,u as Le,v as _e,w as Re}from"./close-event-DSfV7BZf.js";import{existsSync as M,openAsBlob as ze,openSync as Fe,closeSync as Ue}from"node:fs";import{basename as B,extname as je,resolve as G,dirname as Ce,join as w,relative as Je}from"node:path";import{writeFile as K,stat as Me,rm as Be,cp as Ge}from"node:fs/promises";import{spawn as Ke}from"node:child_process";import{fileURLToPath as q}from"node:url";import{humanId as qe}from"human-id";import{homedir as Xe}from"node:os";import Ze from"debug";import"stream";import"module";import"node:net";import"json-rpc-2.0";const X=["back","menu","unlock","volumeDown","volumeUp"],Z=["home","lock"],V=[...Z,...X],I=["down","left","right","up"];async function Ve(e,t={}){const o=await U(e,{signal:t.signal});return new ve(o,{...t,onClose:()=>{o.close(),t.onClose?.()}})}function W({appId:e,buildNumber:t,created:o,id:n,platform:i,versionName:s}){return{appId:e,buildNumber:t,created:o,id:n,platform:i,versionName:s}}const We=["app"],He=10;async function Ye(e){const t=m(e.app,"--app"),o=p(e.limit,"--limit")??He,n=p(e.page,"--page"),i={limit:String(o)};t!==void 0&&(i.appId=t),n!==void 0&&(i.page=String(n));const s=await $("/api/v2/builds",{commandOptions:e,query:i}),a={builds:s.builds.map(W),nextPage:s.nextPage,total:s.total};process.stdout.write(`${JSON.stringify(a,null,2)}
3
- `)}const Qe=["note","tags"],H=12e4,et=2e3,P=[".apk",".apks",".zip",".tar.gz",".tgz"],tt={".apk":"android",".apks":"android",".tar.gz":"ios",".tgz":"ios",".zip":"ios"};async function ot(e,t){const o=rt(e),n=await at(e,o,t);console.error(`build uploaded with id: ${n.id}`);const i=t.wait===!0?await nt(n.id,t):n;process.stdout.write(`${JSON.stringify(W(i),null,2)}
4
- `)}async function nt(e,t){const o=p(t.timeout,"--timeout")??H,n=Date.now()+o;for(;;){const i=await $(`/api/v2/builds/${e}`,{commandOptions:t});if(i.appId!==void 0)return i;if(Date.now()>=n)throw new Error(`Build ${e} is still being processed after ${String(o)}ms; find it with 'appetize build list'`);await it(et)}}function it(e){return new Promise(t=>setTimeout(t,e))}async function st(e){if(!M(e))throw new Error(`No build file at ${e}`);return await ze(e)}function rt(e){const t=e.toLowerCase(),o=P.find(n=>t.endsWith(n));if(o===void 0)throw new Error(`Cannot tell the platform of ${B(e)}; upload a ${P.join(", ")} file`);return tt[o]}async function at(e,t,o){const n=new FormData;n.set("platform",t);const i=m(o.note,"--note");i!==void 0&&n.set("note",i);const s=m(o.tags,"--tags");return s!==void 0&&n.set("tags",s),n.set("file",await st(e),B(e)),await $("/api/v2/builds",{body:n,commandOptions:o,method:"POST"})}const ct=["platform"];async function pt(e){const t=dt(e.platform),n={devices:(await xe(e)).filter(i=>t===void 0||i.platform===t).map(lt)};process.stdout.write(`${JSON.stringify(n,null,2)}
5
- `)}function dt(e){const t=m(e,"--platform");if(t!==void 0){if(!Ee(t))throw new Error(`--platform expects one of: ${be.join(", ")}`);return t}}function lt({id:e,name:t,osVersions:o,platform:n}){return{id:e,name:t,osVersions:o,platform:n}}function A(e,{extension:t,strict:o=!1}){const n=je(e);if(n==="")return`${e}${t}`;if(o&&n!==t)throw new Error(`The output must be a path ending in ${t}`);return e}const h=["text","testId"],d="select",y={testId:{help:"Test id to match by exact string",suffix:"test-id"},text:{help:'Text to match by exact string or regex (e.g., "Sign in" or "/sign in/i")',suffix:"text"}},N="index",x="position",T="x",D="y";function Y(e,{prefix:t=d}={}){return h.reduce((o,n)=>{const{help:i,suffix:s}=y[n];return o.option(`--${r(t,s)}`,i)},e).option(`--${r(t,N)}`,"Which match when multiple (0-based)")}function k(e,t={}){const{prefix:o=d}=t;return Y(e,t).option(`--${r(o,x)}`,"Screen position to use as x,y (0-1), e.g., 0.5,0.75").option(`--${r(o,T)}`,"Horizontal position within the element (0-1, outside allowed)").option(`--${r(o,D)}`,"Vertical position within the element (0-1, outside allowed)")}function Q(e,{prefix:t=d}={}){const o=_(e,t);if(o.length===0)throw new Error(`A selector is required: pass one of ${b(h,t)}`);if(o.length>1)throw new Error(`Only one selector may be given, got ${b(o,t)}`);const[n]=o,i=se(e,r(t,y[n].suffix)),s=p(e[r(t,N)],`--${r(t,N)}`);switch(n){case"testId":return{by:"testId",index:s,testId:i};case"text":return{by:"text",index:s,text:mt(i)}}}function ee(e){const t=p(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function ut(e,{prefix:t=d}={}){return ne(e,t)?Q(e,{prefix:t}):void 0}function E(e,{prefix:t=d}={}){return ne(e,t)?te(e,{prefix:t}):void 0}function te(e,{prefix:t=d}={}){const o=r(t,x),n=e[o],i=ie(e,r(t,T)),s=ie(e,r(t,D));if(n===void 0){if(_(e,t).length===0)throw new Error(`A selector is required: pass one of ${S({prefix:t})}`);return{...Q(e,{prefix:t}),x:i,y:s}}if(_(e,t).length>0)throw new Error(`--${o} may not be combined with ${b(h,t)}`);if(i!==void 0||s!==void 0)throw new Error(`--${o} may not be combined with --${r(t,T)} or --${r(t,D)}`);return ft(se(e,o),o)}function S(e={}){const{prefix:t=d}=e;return`${b(h,t)}, --${r(t,x)}`}function L(e={}){const{prefix:t=d}=e;return[...oe(e),r(t,x)]}function oe({prefix:e=d}={}){return h.map(t=>r(e,y[t].suffix))}function _(e,t){return h.filter(o=>e[r(t,y[o].suffix)]!==void 0)}function r(...e){return e.filter(Boolean).join("-")}function b(e,t){return e.map(o=>`--${r(t,y[o].suffix)}`).join(", ")}function ne(e,t){return Object.entries(e).some(([o,n])=>n!==void 0&&o.startsWith(`${t}-`))}function ie(e,t){return p(e[t],`--${t}`)}function ft(e,t){const o=e.split(",");if(o.length!==2)throw new Error(`--${t} expects x,y (0-1), e.g., 0.5,0.75`);const[n,i]=o.map(s=>Number(s.trim()));return{by:"position",x:j(n,`--${t}`),y:j(i,`--${t}`)}}function mt(e){const t=/^\/(.*)\/([a-z]*)$/s.exec(e);return t?new RegExp(t[1],t[2]):e}function se(e,t){return v(e[t],`--${t}`)}const wt=oe(),ht=async({device:e,options:t,positionals:[o]})=>{const n=gt(o),i=ut(t),s=await e.inspect(i,ee(t)),a=yt(s,t.pretty===!0);await K(n,a);const c={bytes:Buffer.byteLength(a),nodes:re(s.root),output:n};process.stdout.write(`${JSON.stringify(c,null,2)}
6
- `)};function re(e){return e.children.reduce((t,o)=>t+re(o),1)}function gt(e="inspect"){return A(e,{extension:".json"})}function yt(e,t){return`${JSON.stringify(e,null,t?2:void 0)}
7
- `}const St=new Set(V),vt=async({device:e,positionals:[t]})=>{if(!xt(t))throw new Error(`Button must be one of: ${V.join(", ")}`);await e.press(t),process.stdout.write(`${JSON.stringify({pressed:!0},null,2)}
8
- `)};function xt(e){return typeof e=="string"&&St.has(e)}const Et=async({control:e,options:t,positionals:[o]})=>{const{path:n}=await e.recordStart({force:t.force===!0,path:Ot(o)});process.stdout.write(`${JSON.stringify({path:n,recording:!0},null,2)}
9
- `)},bt=async({control:e})=>{const{path:t}=await e.recordStop();process.stdout.write(`${JSON.stringify({path:t,recording:!1},null,2)}
10
- `)};function Ot(e){const t=G(A(e,{extension:".mp4",strict:!0})),o=Ce(t);if(!M(o))throw new Error(`No such directory: ${o}`);return t}const ae={landscapeLeft:!0,landscapeRight:!0,portrait:!0,upsideDown:!0},$t=async({device:e,positionals:[t]})=>{if(!It(t))throw new Error(`Orientation must be one of: ${Object.keys(ae).join(", ")}`);const o=await e.rotate(t);process.stdout.write(`${JSON.stringify(o,null,2)}
11
- `)};function It(e){return typeof e=="string"&&Object.hasOwn(ae,e)}const Pt=async({device:e,positionals:[t]})=>{const o=await e.screenshot(),n=Nt(o.mimeType,t);await K(n,o.data),process.stdout.write(`${JSON.stringify({bytes:o.data.byteLength,mimeType:o.mimeType,output:n},null,2)}
12
- `)};function At(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function Nt(e,t="screenshot"){return A(t,{extension:At(e)})}function Tt(e){const t=q(new URL("./daemon.js",import.meta.url)),o=Fe(Oe(e.sessionId),"a"),n=Ke(process.execPath,[t],{detached:!0,env:{...process.env,[$e]:Ie(e),DEBUG:Dt(process.env.DEBUG)},stdio:["ignore",o,o]});if(Ue(o),n.unref(),n.pid===void 0)throw new Error("Failed to spawn the session daemon");return n.pid}function Dt(e){return e?`${e},appetize:daemon`:"appetize:daemon"}const kt=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function Lt(){return qe({capitalize:!1,separator:"-"})}function _t(e){if(!kt.test(e))throw new Error('--session-id must use letters, digits, ".", "-" or "_"');return e}const Rt=["device-os-version","proxy"],zt=150;async function Ft(e,{onPhase:t,signal:o}){let n;for(;;){const i=C(e),s=i?.state?.phase;if(s&&s!==n&&(n=s,t?.(s)),i&&s==="ready"&&i.controlSocket!==void 0)return{...i,controlSocket:i.controlSocket};if(s==="error")throw new Error(i?.endedReason??"The session failed to start");if(s==="ended")throw new Error(i?.endedReason??"The session ended");await Ct(zt,o)}}function Ut(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!Jt(e))throw new Error("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function jt(e,t,o){const n=m(o["device-os-version"],"--device-os-version"),i=m(o["session-id"],"--session-id"),s=i===void 0?Lt():_t(i);if(C(s)!==void 0)throw new Error(`Session ${s} already exists`);const a={device:n===void 0?{id:e}:{id:e,osVersion:n},endpoint:Pe(o),proxy:Ut(o.proxy),sessionId:s,target:t};Tt(a),console.error(`session started with id: ${s}`);const c=Ae(s,a.proxy);if(o.wait===!1){process.stdout.write(`${JSON.stringify({logs:c,sessionId:s},null,2)}
13
- `);return}const O=await Ft(s,{onPhase:ye=>{console.error(ye)},signal:J()}),ge={adbSerial:O.adbSerial,baseUrl:O.baseUrl,controlSocket:O.controlSocket,logs:c,sessionId:s};process.stdout.write(`${JSON.stringify(ge,null,2)}
14
- `)}function Ct(e,t){return new Promise((o,n)=>{if(t.aborted){n(ce(t.reason));return}const i=()=>{clearTimeout(s),n(ce(t.reason))},s=setTimeout(()=>{t.removeEventListener("abort",i),o()},e);t.addEventListener("abort",i,{once:!0})})}function Jt(e){return e.startsWith("http://")}function ce(e){return e instanceof Error?e:new Error(String(e))}const Mt=async({record:{pid:e,sessionId:t}})=>{Ne(e)&&process.kill(e,"SIGTERM"),process.stdout.write(`${JSON.stringify({ended:!0,sessionId:t},null,2)}
15
- `)},pe="appetize",Bt=q(new URL(`./skills/${pe}/`,import.meta.url)),R=["agents","claude","codex","copilot","cursor"],de=["project","user"],Gt={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},Kt=w(".agents","skills"),qt=["claude","agents"];function Xt(e){return R.some(t=>t===e)}function Zt(e){return de.some(t=>t===e)}async function Vt(e){const t=e.agents??await Wt(e),o=await Promise.all(t.map(n=>le(n,e)));return[...new Set(o.flat())]}async function le(e,t){const o=ue(e,t);if(e==="claude")return[w(o,"skills")];const n=w(t.root,Kt);return t.scope==="project"?[n]:await fe(o)?[n,w(o,"skills")]:[n]}function ue(e,t){if(e==="claude"&&t.scope==="user"){const o=process.env.CLAUDE_CONFIG_DIR?.trim();if(o)return G(o)}return w(t.root,Gt[e])}async function Wt(e){const o=(await Promise.all(R.map(async n=>await Ht(n,e)?n:void 0))).filter(n=>n!==void 0);return o.length>0?o:qt}async function Ht(e,t){const o=[ue(e,t),...await le(e,t)];return(await Promise.all(o.map(i=>fe(i)))).includes(!0)}async function fe(e){try{return(await Me(e)).isDirectory()}catch{return!1}}const Yt=["agent","scope"];async function Qt(e){const t=oo(e.scope),o=to(e.agent),n=t==="user"?Xe():process.cwd(),i=await Vt({agents:o,root:n,scope:t}),s=[];for(const a of i){const c=w(a,pe);await Be(c,{force:!0,recursive:!0}),await Ge(Bt,c,{recursive:!0}),s.push(t==="user"?c:Je(n,c))}process.stdout.write(`${JSON.stringify({installed:s},null,2)}
16
- `)}function eo(e){const t=v(e,"--agent");if(!Xt(t))throw new Error(`--agent expects one of ${R.join(", ")}`);return t}function to(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(o=>eo(o))}function oo(e){if(e===void 0)return"project";const t=v(e,"--scope");if(!Zt(t))throw new Error(`--scope expects one of ${de.join(", ")}`);return t}const l="from",u="to",no=[...L({prefix:l}),...L({prefix:u})],io=async({device:e,options:t})=>{await e.swipe(co(t),lo(t)),process.stdout.write(`${JSON.stringify({swiped:!0},null,2)}
17
- `)};function so(e){return I.some(t=>t===e)}function ro(e){if(e===void 0)return;const t=v(e,"--direction");if(!so(t))throw new Error(`--direction expects one of ${I.join(", ")}`);return t}function ao(e,t){const o=Te(e.distance,"--distance");if(E(e,{prefix:u})!==void 0)throw new Error(`--direction may not be combined with --${u}-*`);return{direction:t,distance:o,from:E(e,{prefix:l})}}function co(e){const t=ro(e.direction);return t===void 0?po(e):ao(e,t)}function po(e){if(e.distance!==void 0)throw new Error("--distance is only valid with --direction");return{from:me(E(e,{prefix:l}),l),to:me(E(e,{prefix:u}),u)}}function lo(e){const t=p(e.duration,"--duration"),o=p(e.timeout,"--timeout");return t===void 0&&o===void 0?void 0:{duration:t,timeout:o}}function me(e,t){if(e===void 0)throw new Error(`A swipe needs --direction, or both endpoints: pass one of ${S({prefix:t})}`);return e}const uo=L(),fo=async({device:e,options:t})=>{const o=te(t);await e.tap(o,ee(t)),process.stdout.write(`${JSON.stringify({tapped:!0},null,2)}
18
- `)},mo=async({device:e,options:t,positionals:[o]})=>{await e.type(o,wo(t)),process.stdout.write(`${JSON.stringify({typed:!0},null,2)}
19
- `)};function wo(e){const t=p(e.delay,"--delay");return t===void 0?void 0:{delay:t}}const z=Ze("appetize:cli");function ho(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return Ve(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function go(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const o=await U(e.controlSocket,{signal:t}),{client:n}=De(o,{});return{close:()=>{o.close()},recordStart:async i=>await n.request("appetizeio.cli.record.start",i),recordStop:async()=>await n.request("appetizeio.cli.record.stop")}}function yo(e){return async(...t)=>{const{options:o,positionals:n}=Eo(t),i=o["session-id"],s=ke(typeof i=="string"?i:void 0),a=AbortSignal.any([J(),Le(s.pid)]);await e({options:o,positionals:n,record:s,signal:a})}}function So(e){return async({options:t,positionals:o,record:n,signal:i})=>{const s=await ho(n,i);try{await e({device:s,options:t,positionals:o,signal:i})}finally{s.close()}}}function vo(e){return async({options:t,positionals:o,record:n,signal:i})=>{const s=await go(n,i);try{await e({control:s,options:t,positionals:o,signal:i})}finally{s.close()}}}function xo(e){return typeof e=="object"&&e!==null}function Eo(e){const t=e.at(-1);return{options:xo(t)?t:{},positionals:e.slice(0,-1).filter(o=>typeof o=="string")}}const bo=["session-id",...We,...Qe,...ct,...wt,...Yt,...Rt,...no,...uo];function Oo(e){const t=Se("appetize").version(e);return g(t.command("session start <device-id> <target>").describe(["Start a device session and wait until it is ready","","Environment variables:","APPETIZE_API_TOKEN: Authorizes private APIs and session targets","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--device-os-version","Device OS version (e.g., 17 for iOS, 14 for Android)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--no-wait","Return without waiting for the device session to be ready").option("--proxy","Route traffic through a proxy: 'intercept' to capture it, or an http url").option("--session-id","Session id; defaults to a generated 3-word id").example("session start iphone15pro app_a1b2c3").example("session start pixel7 app_a1b2c3 --device-os-version 14"),jt),F(t.command("session stop").describe("Stop a running device session"),Mt),g(t.command("build list").describe(["List uploaded builds, printing session start targets","","Environment variables:","APPETIZE_API_TOKEN: Authorizes the listing request","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--app","App id to filter by (bundle or package id)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--limit","Builds per page (default 10, max 200)").option("--page","Page of results to fetch (default 1)").example("build list").example("build list --app com.example.app").example("build list --app com.example.app --page 2"),Ye),g(t.command("build upload <file>").describe([`Upload a build (${P.join(", ")}) as a session start target`,"","Environment variables:","APPETIZE_API_TOKEN: Authorizes the upload","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--note","Note to store with the build").option("--tags","Comma separated tags to store with the build").option("--timeout",`Milliseconds to wait with --wait (default ${String(H)})`).option("--wait","Wait for the app id and version metadata to resolve").example("build upload ./app.apk").example("build upload ./app.zip").example("build upload ./app.apk --wait").example('build upload ./app.apk --tags beta,latest --note "PR 42"'),ot),g(t.command("device list").describe(["List device models and their supported OS versions","","Environment variables:","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--platform","Platform to filter by: ios or android").example("device list").example("device list --platform ios"),pt),f(t.command("press <button>").describe(`Press a device button: ${Z.join(", ")}; Android only: ${X.join(", ")}`).example("press home").example("press volumeUp"),vt),f(t.command("rotate <orientation>").describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),$t),f(t.command("screenshot [output]").describe("Take a screenshot of the current device screen").example("screenshot").example("screenshot home-screen").example("screenshot ./shots/checkout.png"),Pt),f(k(t.command("tap").describe(["Tap an element matched by a selector, or a screen position","",`Pick one of: ${S()}`])).option("--timeout","Milliseconds to wait for the element").example("tap --select-text 'Log in'").example("tap --select-test-id save").example("tap --select-text '/^Item \\d+/i' --select-index 2").example("tap --select-position 0.5,0.75").example("tap --select-test-id slider --select-x 0.9").example("tap --select-test-id dialog --select-x=-0.1").example("tap --select-test-id row --select-y=1.2"),fo),f(k(k(t.command("swipe").describe(["Swipe in a direction, or along a path between two points","",`Pick a --direction with an optional --${l} starting point,`,`or both a --${l}-* and a --${u}-* point to form a path`,"",`Pick one per point: ${S({prefix:l})}`,` ${S({prefix:u})}`]).option("--direction",`Direction to travel: ${I.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:l}),{prefix:u}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${l}/--${u} elements`).example("swipe --direction up").example("swipe --direction up --distance 0.25").example("swipe --direction left --from-test-id card --from-index 1").example("swipe --from-position 0.5,0.75 --to-position 0.5,0.3").example("swipe --from-text 'Drag me' --from-y 0.9 --to-test-id drop-zone"),io),f(Y(t.command("inspect [output]").describe("Capture the view hierarchy of the screen, or of an element matched by a selector")).option("--timeout","Milliseconds to wait for the element").option("--pretty","Pretty-print the JSON",!1).example("inspect").example("inspect --select-text 'Log in'").example("inspect hierarchy.json --pretty"),ht),f(t.command("type <text>").describe(`Type text; {...} presses a named key: ${_e.join(", ")}`).option("--delay","Milliseconds to wait between steps").example("type 'hello{Enter}'").example("type '{Backspace>16/}'").example("type 'user@example.com{Tab}hunter2{Enter}' --delay 50"),mo),we(t.command("recording start <output>").describe("Start recording the device video to an mp4 file").option("--force","Overwrite the file if it already exists",!1).example("recording start login-flow").example("recording start ./captures/checkout.mp4").example("recording start login-flow --force"),Et),we(t.command("recording stop").describe("Stop recording the device video and close the file").example("recording stop"),bt),g(t.command("skill install").describe("Install the Appetize agent skill for coding agents").option("--agent","Agent to install for, repeatable; defaults to the agents detected").option("--scope","Install for the project (default) or the user").example("skill install").example("skill install --scope user").example("skill install --agent claude --agent cursor"),Qt),t}function g(e,t){return e.action(Io(t))}function F(e,t){return g(e.option("--session-id","Target session id; defaults to the sole active session"),yo(t))}function f(e,t){return F(e,So(t))}function we(e,t){return F(e,vo(t))}function he(e){return`${String(Date.now()-e)}ms`}async function $o(e,...t){const o=Date.now();z(`invoked: ${process.argv.slice(2).join(" ")}`);try{await e(...t),z(`ok in ${he(o)}`)}catch(n){const i=n instanceof Error?n.message:String(n);console.error(i),z(`failed after ${he(o)}:`,n),process.exitCode=1}}function Io(e){return(...t)=>{$o(e,...t)}}Re(),Oo("0.15.2").parse(process.argv,{string:bo});
2
+ import Se from"sade";import{d as U,D as ve,p as m,a as p,f as $,b as xe,i as Ee,c as be,r as j,e as x,g as Oe,h as $e,s as Ie,j as C,k as Pe,l as Ae,m as Ne,n as J,o as Te,q as De,t as ke,u as Le,v as _e,w as Re,x as ze}from"./close-event-BFzpneqE.js";import{existsSync as M,openAsBlob as Fe,openSync as Ue,closeSync as je}from"node:fs";import{basename as B,extname as Ce,resolve as G,dirname as Je,join as w,relative as Me}from"node:path";import{writeFile as K,stat as Be,rm as Ge,cp as Ke}from"node:fs/promises";import{spawn as qe}from"node:child_process";import{fileURLToPath as q}from"node:url";import{humanId as Xe}from"human-id";import{homedir as Ze}from"node:os";import Ve from"debug";import"stream";import"module";import"node:net";import"json-rpc-2.0";const X=["back","menu","unlock","volumeDown","volumeUp"],Z=["home","lock"],V=[...Z,...X],I=["down","left","right","up"];async function We(e,t={}){const o=await U(e,{signal:t.signal});return new ve(o,{...t,onClose:()=>{o.close(),t.onClose?.()}})}function W({appId:e,buildNumber:t,created:o,id:n,platform:i,versionName:s}){return{appId:e,buildNumber:t,created:o,id:n,platform:i,versionName:s}}const He=["app"],Ye=10;async function Qe(e){const t=m(e.app,"--app"),o=p(e.limit,"--limit")??Ye,n=p(e.page,"--page"),i={limit:String(o)};t!==void 0&&(i.appId=t),n!==void 0&&(i.page=String(n));const s=await $("/api/v2/builds",{commandOptions:e,query:i}),a={builds:s.builds.map(W),nextPage:s.nextPage,total:s.total};process.stdout.write(`${JSON.stringify(a,null,2)}
3
+ `)}const et=["note","tags"],H=12e4,tt=2e3,P=[".apk",".apks",".zip",".tar.gz",".tgz"],ot={".apk":"android",".apks":"android",".tar.gz":"ios",".tgz":"ios",".zip":"ios"};async function nt(e,t){const o=at(e),n=await ct(e,o,t);console.error(`build uploaded with id: ${n.id}`);const i=t.wait===!0?await it(n.id,t):n;process.stdout.write(`${JSON.stringify(W(i),null,2)}
4
+ `)}async function it(e,t){const o=p(t.timeout,"--timeout")??H,n=Date.now()+o;for(;;){const i=await $(`/api/v2/builds/${e}`,{commandOptions:t});if(i.appId!==void 0)return i;if(Date.now()>=n)throw new Error(`Build ${e} is still being processed after ${String(o)}ms; find it with 'appetize build list'`);await st(tt)}}function st(e){return new Promise(t=>setTimeout(t,e))}async function rt(e){if(!M(e))throw new Error(`No build file at ${e}`);return await Fe(e)}function at(e){const t=e.toLowerCase(),o=P.find(n=>t.endsWith(n));if(o===void 0)throw new Error(`Cannot tell the platform of ${B(e)}; upload a ${P.join(", ")} file`);return ot[o]}async function ct(e,t,o){const n=new FormData;n.set("platform",t);const i=m(o.note,"--note");i!==void 0&&n.set("note",i);const s=m(o.tags,"--tags");return s!==void 0&&n.set("tags",s),n.set("file",await rt(e),B(e)),await $("/api/v2/builds",{body:n,commandOptions:o,method:"POST"})}const pt=["platform"];async function lt(e){const t=dt(e.platform),n={devices:(await xe(e)).filter(i=>t===void 0||i.platform===t).map(ut)};process.stdout.write(`${JSON.stringify(n,null,2)}
5
+ `)}function dt(e){const t=m(e,"--platform");if(t!==void 0){if(!Ee(t))throw new Error(`--platform expects one of: ${be.join(", ")}`);return t}}function ut({id:e,name:t,osVersions:o,platform:n}){return{id:e,name:t,osVersions:o,platform:n}}function A(e,{extension:t,strict:o=!1}){const n=Ce(e);if(n==="")return`${e}${t}`;if(o&&n!==t)throw new Error(`The output must be a path ending in ${t}`);return e}const h=["text","testId"],l="select",y={testId:{help:"Test id to match by exact string",suffix:"test-id"},text:{help:'Text to match by exact string or regex (e.g., "Sign in" or "/sign in/i")',suffix:"text"}},N="index",E="position",T="x",D="y";function Y(e,{prefix:t=l}={}){return h.reduce((o,n)=>{const{help:i,suffix:s}=y[n];return o.option(`--${r(t,s)}`,i)},e).option(`--${r(t,N)}`,"Which match when multiple (0-based)")}function k(e,t={}){const{prefix:o=l}=t;return Y(e,t).option(`--${r(o,E)}`,"Screen position to use as x,y (0-1), e.g., 0.5,0.75").option(`--${r(o,T)}`,"Horizontal position within the element (0-1, outside allowed)").option(`--${r(o,D)}`,"Vertical position within the element (0-1, outside allowed)")}function Q(e,{prefix:t=l}={}){const o=_(e,t);if(o.length===0)throw new Error(`A selector is required: pass one of ${O(h,t)}`);if(o.length>1)throw new Error(`Only one selector may be given, got ${O(o,t)}`);const[n]=o,i=se(e,r(t,y[n].suffix)),s=p(e[r(t,N)],`--${r(t,N)}`);switch(n){case"testId":return{by:"testId",index:s,testId:i};case"text":return{by:"text",index:s,text:wt(i)}}}function ee(e){const t=p(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function ft(e,{prefix:t=l}={}){return ne(e,t)?Q(e,{prefix:t}):void 0}function b(e,{prefix:t=l}={}){return ne(e,t)?te(e,{prefix:t}):void 0}function te(e,{prefix:t=l}={}){const o=r(t,E),n=e[o],i=ie(e,r(t,T)),s=ie(e,r(t,D));if(n===void 0){if(_(e,t).length===0)throw new Error(`A selector is required: pass one of ${S({prefix:t})}`);return{...Q(e,{prefix:t}),x:i,y:s}}if(_(e,t).length>0)throw new Error(`--${o} may not be combined with ${O(h,t)}`);if(i!==void 0||s!==void 0)throw new Error(`--${o} may not be combined with --${r(t,T)} or --${r(t,D)}`);return mt(se(e,o),o)}function S(e={}){const{prefix:t=l}=e;return`${O(h,t)}, --${r(t,E)}`}function L(e={}){const{prefix:t=l}=e;return[...oe(e),r(t,E)]}function oe({prefix:e=l}={}){return h.map(t=>r(e,y[t].suffix))}function _(e,t){return h.filter(o=>e[r(t,y[o].suffix)]!==void 0)}function r(...e){return e.filter(Boolean).join("-")}function O(e,t){return e.map(o=>`--${r(t,y[o].suffix)}`).join(", ")}function ne(e,t){return Object.entries(e).some(([o,n])=>n!==void 0&&o.startsWith(`${t}-`))}function ie(e,t){return p(e[t],`--${t}`)}function mt(e,t){const o=e.split(",");if(o.length!==2)throw new Error(`--${t} expects x,y (0-1), e.g., 0.5,0.75`);const[n,i]=o.map(s=>Number(s.trim()));return{by:"position",x:j(n,`--${t}`),y:j(i,`--${t}`)}}function wt(e){const t=/^\/(.*)\/([a-z]*)$/s.exec(e);return t?new RegExp(t[1],t[2]):e}function se(e,t){return x(e[t],`--${t}`)}const ht=oe(),gt=async({device:e,options:t,positionals:[o]})=>{const n=yt(o),i=ft(t),s=await e.inspect(i,ee(t)),a=St(s,t.pretty===!0);await K(n,a);const c={bytes:Buffer.byteLength(a),nodes:re(s.root),output:n};process.stdout.write(`${JSON.stringify(c,null,2)}
6
+ `)};function re(e){return e.children.reduce((t,o)=>t+re(o),1)}function yt(e="inspect"){return A(e,{extension:".json"})}function St(e,t){return`${JSON.stringify(e,null,t?2:void 0)}
7
+ `}const vt=new Set(V),xt=async({device:e,positionals:[t]})=>{if(!Et(t))throw new Error(`Button must be one of: ${V.join(", ")}`);await e.press(t),process.stdout.write(`${JSON.stringify({pressed:!0},null,2)}
8
+ `)};function Et(e){return typeof e=="string"&&vt.has(e)}const bt=async({control:e,options:t,positionals:[o]})=>{const{path:n}=await e.recordStart({force:t.force===!0,path:$t(o)});process.stdout.write(`${JSON.stringify({path:n,recording:!0},null,2)}
9
+ `)},Ot=async({control:e})=>{const{path:t}=await e.recordStop();process.stdout.write(`${JSON.stringify({path:t,recording:!1},null,2)}
10
+ `)};function $t(e){const t=G(A(e,{extension:".mp4",strict:!0})),o=Je(t);if(!M(o))throw new Error(`No such directory: ${o}`);return t}const ae={landscapeLeft:!0,landscapeRight:!0,portrait:!0,upsideDown:!0},It=async({device:e,positionals:[t]})=>{if(!Pt(t))throw new Error(`Orientation must be one of: ${Object.keys(ae).join(", ")}`);const o=await e.rotate(t);process.stdout.write(`${JSON.stringify(o,null,2)}
11
+ `)};function Pt(e){return typeof e=="string"&&Object.hasOwn(ae,e)}const At=async({device:e,positionals:[t]})=>{const o=await e.screenshot(),n=Tt(o.mimeType,t);await K(n,o.data),process.stdout.write(`${JSON.stringify({bytes:o.data.byteLength,mimeType:o.mimeType,output:n},null,2)}
12
+ `)};function Nt(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function Tt(e,t="screenshot"){return A(t,{extension:Nt(e)})}function Dt(e){const t=q(new URL("./daemon.js",import.meta.url)),o=Ue(Oe(e.sessionId),"a"),n=qe(process.execPath,[t],{detached:!0,env:{...process.env,[$e]:Ie(e),DEBUG:kt(process.env.DEBUG)},stdio:["ignore",o,o]});if(je(o),n.unref(),n.pid===void 0)throw new Error("Failed to spawn the session daemon");return n.pid}function kt(e){return e?`${e},appetize:daemon`:"appetize:daemon"}const Lt=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function _t(){return Xe({capitalize:!1,separator:"-"})}function Rt(e){if(!Lt.test(e))throw new Error('--session-id must use letters, digits, ".", "-" or "_"');return e}const zt=["device-os-version","proxy"],Ft=150;async function Ut(e,{onPhase:t,signal:o}){let n;for(;;){const i=C(e),s=i?.state?.phase;if(s&&s!==n&&(n=s,t?.(s)),i&&s==="ready"&&i.controlSocket!==void 0)return{...i,controlSocket:i.controlSocket};if(s==="error")throw new Error(i?.endedReason??"The session failed to start");if(s==="ended")throw new Error(i?.endedReason??"The session ended");await Jt(Ft,o)}}function jt(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!Mt(e))throw new Error("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function Ct(e,t,o){const n=m(o["device-os-version"],"--device-os-version"),i=m(o["session-id"],"--session-id"),s=i===void 0?_t():Rt(i);if(C(s)!==void 0)throw new Error(`Session ${s} already exists`);const a={device:n===void 0?{id:e}:{id:e,osVersion:n},endpoint:Ae(o),featureFlags:Pe(),proxy:jt(o.proxy),sessionId:s,target:t};Dt(a),console.error(`session started with id: ${s}`);const c=Ne(s,a.proxy);if(o.wait===!1){process.stdout.write(`${JSON.stringify({logs:c,sessionId:s},null,2)}
13
+ `);return}const v=await Ut(s,{onPhase:ye=>{console.error(ye)},signal:J()}),ge={adbSerial:v.adbSerial,baseUrl:v.baseUrl,controlSocket:v.controlSocket,logs:c,sessionId:s,viewerUrl:v.viewerUrl};process.stdout.write(`${JSON.stringify(ge,null,2)}
14
+ `)}function Jt(e,t){return new Promise((o,n)=>{if(t.aborted){n(ce(t.reason));return}const i=()=>{clearTimeout(s),n(ce(t.reason))},s=setTimeout(()=>{t.removeEventListener("abort",i),o()},e);t.addEventListener("abort",i,{once:!0})})}function Mt(e){return e.startsWith("http://")}function ce(e){return e instanceof Error?e:new Error(String(e))}const Bt=async({record:{pid:e,sessionId:t}})=>{Te(e)&&process.kill(e,"SIGTERM"),process.stdout.write(`${JSON.stringify({ended:!0,sessionId:t},null,2)}
15
+ `)},pe="appetize",Gt=q(new URL(`./skills/${pe}/`,import.meta.url)),R=["agents","claude","codex","copilot","cursor"],le=["project","user"],Kt={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},qt=w(".agents","skills"),Xt=["claude","agents"];function Zt(e){return R.some(t=>t===e)}function Vt(e){return le.some(t=>t===e)}async function Wt(e){const t=e.agents??await Ht(e),o=await Promise.all(t.map(n=>de(n,e)));return[...new Set(o.flat())]}async function de(e,t){const o=ue(e,t);if(e==="claude")return[w(o,"skills")];const n=w(t.root,qt);return t.scope==="project"?[n]:await fe(o)?[n,w(o,"skills")]:[n]}function ue(e,t){if(e==="claude"&&t.scope==="user"){const o=process.env.CLAUDE_CONFIG_DIR?.trim();if(o)return G(o)}return w(t.root,Kt[e])}async function Ht(e){const o=(await Promise.all(R.map(async n=>await Yt(n,e)?n:void 0))).filter(n=>n!==void 0);return o.length>0?o:Xt}async function Yt(e,t){const o=[ue(e,t),...await de(e,t)];return(await Promise.all(o.map(i=>fe(i)))).includes(!0)}async function fe(e){try{return(await Be(e)).isDirectory()}catch{return!1}}const Qt=["agent","scope"];async function eo(e){const t=no(e.scope),o=oo(e.agent),n=t==="user"?Ze():process.cwd(),i=await Wt({agents:o,root:n,scope:t}),s=[];for(const a of i){const c=w(a,pe);await Ge(c,{force:!0,recursive:!0}),await Ke(Gt,c,{recursive:!0}),s.push(t==="user"?c:Me(n,c))}process.stdout.write(`${JSON.stringify({installed:s},null,2)}
16
+ `)}function to(e){const t=x(e,"--agent");if(!Zt(t))throw new Error(`--agent expects one of ${R.join(", ")}`);return t}function oo(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(o=>to(o))}function no(e){if(e===void 0)return"project";const t=x(e,"--scope");if(!Vt(t))throw new Error(`--scope expects one of ${le.join(", ")}`);return t}const d="from",u="to",io=[...L({prefix:d}),...L({prefix:u})],so=async({device:e,options:t})=>{await e.swipe(po(t),uo(t)),process.stdout.write(`${JSON.stringify({swiped:!0},null,2)}
17
+ `)};function ro(e){return I.some(t=>t===e)}function ao(e){if(e===void 0)return;const t=x(e,"--direction");if(!ro(t))throw new Error(`--direction expects one of ${I.join(", ")}`);return t}function co(e,t){const o=De(e.distance,"--distance");if(b(e,{prefix:u})!==void 0)throw new Error(`--direction may not be combined with --${u}-*`);return{direction:t,distance:o,from:b(e,{prefix:d})}}function po(e){const t=ao(e.direction);return t===void 0?lo(e):co(e,t)}function lo(e){if(e.distance!==void 0)throw new Error("--distance is only valid with --direction");return{from:me(b(e,{prefix:d}),d),to:me(b(e,{prefix:u}),u)}}function uo(e){const t=p(e.duration,"--duration"),o=p(e.timeout,"--timeout");return t===void 0&&o===void 0?void 0:{duration:t,timeout:o}}function me(e,t){if(e===void 0)throw new Error(`A swipe needs --direction, or both endpoints: pass one of ${S({prefix:t})}`);return e}const fo=L(),mo=async({device:e,options:t})=>{const o=te(t);await e.tap(o,ee(t)),process.stdout.write(`${JSON.stringify({tapped:!0},null,2)}
18
+ `)},wo=async({device:e,options:t,positionals:[o]})=>{await e.type(o,ho(t)),process.stdout.write(`${JSON.stringify({typed:!0},null,2)}
19
+ `)};function ho(e){const t=p(e.delay,"--delay");return t===void 0?void 0:{delay:t}}const z=Ve("appetize:cli");function go(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return We(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function yo(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const o=await U(e.controlSocket,{signal:t}),{client:n}=ke(o,{});return{close:()=>{o.close()},recordStart:async i=>await n.request("appetizeio.cli.record.start",i),recordStop:async()=>await n.request("appetizeio.cli.record.stop")}}function So(e){return async(...t)=>{const{options:o,positionals:n}=bo(t),i=o["session-id"],s=Le(typeof i=="string"?i:void 0),a=AbortSignal.any([J(),_e(s.pid)]);await e({options:o,positionals:n,record:s,signal:a})}}function vo(e){return async({options:t,positionals:o,record:n,signal:i})=>{const s=await go(n,i);try{await e({device:s,options:t,positionals:o,signal:i})}finally{s.close()}}}function xo(e){return async({options:t,positionals:o,record:n,signal:i})=>{const s=await yo(n,i);try{await e({control:s,options:t,positionals:o,signal:i})}finally{s.close()}}}function Eo(e){return typeof e=="object"&&e!==null}function bo(e){const t=e.at(-1);return{options:Eo(t)?t:{},positionals:e.slice(0,-1).filter(o=>typeof o=="string")}}const Oo=["session-id",...He,...et,...pt,...ht,...Qt,...zt,...io,...fo];function $o(e){const t=Se("appetize").version(e);return g(t.command("session start <device-id> <target>").describe(["Start a device session and wait until it is ready","","Environment variables:","APPETIZE_API_TOKEN: Authorizes private APIs and session targets","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--device-os-version","Device OS version (e.g., 17 for iOS, 14 for Android)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--no-wait","Return without waiting for the device session to be ready").option("--proxy","Route traffic through a proxy: 'intercept' to capture it, or an http url").option("--session-id","Session id; defaults to a generated 3-word id").example("session start iphone15pro app_a1b2c3").example("session start pixel7 app_a1b2c3 --device-os-version 14"),Ct),F(t.command("session stop").describe("Stop a running device session"),Bt),g(t.command("build list").describe(["List uploaded builds, printing session start targets","","Environment variables:","APPETIZE_API_TOKEN: Authorizes the listing request","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--app","App id to filter by (bundle or package id)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--limit","Builds per page (default 10, max 200)").option("--page","Page of results to fetch (default 1)").example("build list").example("build list --app com.example.app").example("build list --app com.example.app --page 2"),Qe),g(t.command("build upload <file>").describe([`Upload a build (${P.join(", ")}) as a session start target`,"","Environment variables:","APPETIZE_API_TOKEN: Authorizes the upload","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--note","Note to store with the build").option("--tags","Comma separated tags to store with the build").option("--timeout",`Milliseconds to wait with --wait (default ${String(H)})`).option("--wait","Wait for the app id and version metadata to resolve").example("build upload ./app.apk").example("build upload ./app.zip").example("build upload ./app.apk --wait").example('build upload ./app.apk --tags beta,latest --note "PR 42"'),nt),g(t.command("device list").describe(["List device models and their supported OS versions","","Environment variables:","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--platform","Platform to filter by: ios or android").example("device list").example("device list --platform ios"),lt),f(t.command("press <button>").describe(`Press a device button: ${Z.join(", ")}; Android only: ${X.join(", ")}`).example("press home").example("press volumeUp"),xt),f(t.command("rotate <orientation>").describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),It),f(t.command("screenshot [output]").describe("Take a screenshot of the current device screen").example("screenshot").example("screenshot home-screen").example("screenshot ./shots/checkout.png"),At),f(k(t.command("tap").describe(["Tap an element matched by a selector, or a screen position","",`Pick one of: ${S()}`])).option("--timeout","Milliseconds to wait for the element").example("tap --select-text 'Log in'").example("tap --select-test-id save").example("tap --select-text '/^Item \\d+/i' --select-index 2").example("tap --select-position 0.5,0.75").example("tap --select-test-id slider --select-x 0.9").example("tap --select-test-id dialog --select-x=-0.1").example("tap --select-test-id row --select-y=1.2"),mo),f(k(k(t.command("swipe").describe(["Swipe in a direction, or along a path between two points","",`Pick a --direction with an optional --${d} starting point,`,`or both a --${d}-* and a --${u}-* point to form a path`,"",`Pick one per point: ${S({prefix:d})}`,` ${S({prefix:u})}`]).option("--direction",`Direction to travel: ${I.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:d}),{prefix:u}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${d}/--${u} elements`).example("swipe --direction up").example("swipe --direction up --distance 0.25").example("swipe --direction left --from-test-id card --from-index 1").example("swipe --from-position 0.5,0.75 --to-position 0.5,0.3").example("swipe --from-text 'Drag me' --from-y 0.9 --to-test-id drop-zone"),so),f(Y(t.command("inspect [output]").describe("Capture the view hierarchy of the screen, or of an element matched by a selector")).option("--timeout","Milliseconds to wait for the element").option("--pretty","Pretty-print the JSON",!1).example("inspect").example("inspect --select-text 'Log in'").example("inspect hierarchy.json --pretty"),gt),f(t.command("type <text>").describe(`Type text; {...} presses a named key: ${Re.join(", ")}`).option("--delay","Milliseconds to wait between steps").example("type 'hello{Enter}'").example("type '{Backspace>16/}'").example("type 'user@example.com{Tab}hunter2{Enter}' --delay 50"),wo),we(t.command("recording start <output>").describe("Start recording the device video to an mp4 file").option("--force","Overwrite the file if it already exists",!1).example("recording start login-flow").example("recording start ./captures/checkout.mp4").example("recording start login-flow --force"),bt),we(t.command("recording stop").describe("Stop recording the device video and close the file").example("recording stop"),Ot),g(t.command("skill install").describe("Install the Appetize agent skill for coding agents").option("--agent","Agent to install for, repeatable; defaults to the agents detected").option("--scope","Install for the project (default) or the user").example("skill install").example("skill install --scope user").example("skill install --agent claude --agent cursor"),eo),t}function g(e,t){return e.action(Po(t))}function F(e,t){return g(e.option("--session-id","Target session id; defaults to the sole active session"),So(t))}function f(e,t){return F(e,vo(t))}function we(e,t){return F(e,xo(t))}function he(e){return`${String(Date.now()-e)}ms`}async function Io(e,...t){const o=Date.now();z(`invoked: ${process.argv.slice(2).join(" ")}`);try{await e(...t),z(`ok in ${he(o)}`)}catch(n){const i=n instanceof Error?n.message:String(n);console.error(i),z(`failed after ${he(o)}:`,n),process.exitCode=1}}function Po(e){return(...t)=>{Io(e,...t)}}ze(),$o("0.16.0").parse(process.argv,{string:Oo});
@@ -1,2 +1,2 @@
1
- import{Transform as Qt}from"stream";import{createRequire as er}from"module";import{connect as tr}from"node:net";import Be from"debug";import{JSONRPCServerAndClient as rr,JSONRPCServer as sr,JSONRPCClient as nr,JSONRPC as ir}from"json-rpc-2.0";import{writeFileSync as or,renameSync as ar,mkdirSync as pt,readFileSync as lr,readdirSync as cr}from"node:fs";import{homedir as fr}from"node:os";import{join as te}from"node:path";let Ne;try{Ne=new TextDecoder}catch{}let p,V,c=0;const De=[],ur=105,dr=57342,hr=57343,yt=57337,wt=6,fe={};let we=11281e4,Y=1681e4,re=De,be=0,O={},_,ge,me=0,se=0,B,q,N=[],Fe=[],K,j,Ee,bt={useRecords:!1,mapsAsObjects:!0},Se=!1,gt=2;try{new Function("")}catch{gt=1/0}class he{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[J(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(p)return Ot(()=>(Ke(),this?this.decode(e,r):he.prototype.decode.call(bt,e,r)));V=r>-1?r:e.length,c=0,be=0,se=0,ge=null,re=De,B=null,p=e;try{j=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(s){throw p=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 he){if(O=this,K=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return _=this.structures,Oe();(!_||_.length>0)&&(_=[])}else O=bt,(!_||_.length>0)&&(_=[]),K=null;return Oe()}decodeMultiple(e,r){let s,n=0;try{let o=e.length;Se=!0;let f=this?this.decode(e,o):qe.decode(e,o);if(r){if(r(f)===!1)return;for(;c<o;)if(n=c,r(Oe())===!1)return}else{for(s=[f];c<o;)n=c,s.push(Oe());return s}}catch(o){throw o.lastPosition=n,o.values=s,o}finally{Se=!1,Ke()}}}function Oe(){try{let t=I();if(B){if(c>=B.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}c=B.postBundlePosition,B=null}if(c==V)_=null,p=null,q&&(q=null);else if(c>V){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Se)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw Ke(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function ne(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function I(){if(!(c<V))throw ne();let t=p[c++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(c>=V)throw ne();t=p[c++];break;case 25:if(e==7)return br();t=j.getUint16(c),c+=2;break;case 26:if(e==7){let r=j.getFloat32(c);if(O.useFloat32>2){let s=$e[(p[c]&127)<<1|p[c+1]>>7];return c+=4,(s*r+(r>0?.5:-.5)>>0)/s}return c+=4,r}if(t=j.getUint32(c),c+=4,e===1)return-1-t;break;case 27:if(e==7){let r=j.getFloat64(c);return c+=8,r}if(e>1){if(j.getUint32(c)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=j.getUint32(c+4)}else O.int64AsNumber?(t=j.getUint32(c)*4294967296,t+=j.getUint32(c+4)):t=j.getBigUint64(c);c+=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=I())!=fe;){if(n>=we)throw new Error(`Array length exceeds ${we}`);r[n++]=s}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let o;if(O.mapsAsObjects){let f={},b=0;if(O.keyMap)for(;(o=I())!=fe;){if(b++>=Y)throw new Error(`Property count exceeds ${Y}`);f[J(O.decodeKey(o))]=I()}else for(;(o=I())!=fe;){if(b++>=Y)throw new Error(`Property count exceeds ${Y}`);f[J(o)]=I()}return f}else{Ee&&(O.mapsAsObjects=!0,Ee=!1);let f=new Map;if(O.keyMap){let b=0;for(;(o=I())!=fe;){if(b++>=Y)throw new Error(`Map size exceeds ${Y}`);f.set(O.decodeKey(o),I())}}else{let b=0;for(;(o=I())!=fe;){if(b++>=Y)throw new Error(`Map size exceeds ${Y}`);f.set(o,I())}}return f}case 7:return fe;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:return wr(t);case 3:if(se>=c)return ge.slice(c-me,(c+=t)-me);if(se==0&&V<140&&t<32){let n=t<16?St(t):yr(t);if(n!=null)return n}return Et(t);case 4:if(t>=we)throw new Error(`Array length exceeds ${we}`);if(t>V-c)throw ne();let r=new Array(t);for(let n=0;n<t;n++)r[n]=I();return r;case 5:if(t>=Y)throw new Error(`Map size exceeds ${we}`);if(t>(V-c)/2)throw ne();if(O.mapsAsObjects){let n={};if(O.keyMap)for(let o=0;o<t;o++)n[J(O.decodeKey(I()))]=I();else for(let o=0;o<t;o++)n[J(I())]=I();return n}else{Ee&&(O.mapsAsObjects=!0,Ee=!1);let n=new Map;if(O.keyMap)for(let o=0;o<t;o++)n.set(O.decodeKey(I()),I());else for(let o=0;o<t;o++)n.set(I(),I());return n}case 6:if(t>=yt){let n=_[t&8191];if(n)return n.read||(n.read=ze(n)),n.read();if(t<65536){if(t==hr){let o=de(),f=I(),b=I();je(f,b);let y={};if(O.keyMap)for(let v=2;v<o;v++){let m=O.decodeKey(b[v-2]);y[J(m)]=I()}else for(let v=2;v<o;v++){let m=b[v-2];y[J(m)]=I()}return y}else if(t==dr){let o=de(),f=I();for(let b=2;b<o;b++)je(f++,I());return I()}else if(t==yt)return Ar();if(O.getShared&&(Ve(),n=_[t&8191],n))return n.read||(n.read=ze(n)),n.read()}}let s=N[t];if(s)return s.handlesRead?s(I):s(I());{let n=I();for(let o=0;o<Fe.length;o++){let f=Fe[o](t,n);if(f!==void 0)return f}return new ie(n,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let n=(K||oe())[t];if(n!==void 0)return n;throw new Error("Unknown token "+t)}default:throw isNaN(t)?ne():new Error("Unknown CBOR token "+t)}}const mt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ze(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=p[c++];if(r=r&31,r>23)switch(r){case 24:r=p[c++];break;case 25:r=j.getUint16(c),c+=2;break;case 26:r=j.getUint32(c),c+=4;break;default:throw new Error("Expected array header, but got "+p[c-1])}let s=this.compiledReader;for(;s;){if(s.propertyCount===r)return s(I);s=s.next}if(this.slowReads++>=gt){let o=this.length==r?this:this.slice(0,r);return s=O.keyMap?new Function("r","return {"+o.map(f=>O.decodeKey(f)).map(f=>mt.test(f)?J(f)+":r()":"["+JSON.stringify(f)+"]:r()").join(",")+"}"):new Function("r","return {"+o.map(f=>mt.test(f)?J(f)+":r()":"["+JSON.stringify(f)+"]:r()").join(",")+"}"),this.compiledReader&&(s.next=this.compiledReader),s.propertyCount=r,this.compiledReader=s,s(I)}let n={};if(O.keyMap)for(let o=0;o<r;o++)n[J(O.decodeKey(this[o]))]=I();else for(let o=0;o<r;o++)n[J(this[o])]=I();return n}return t.slowReads=0,e}function J(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 Et=Ie;function pr(t){Et=e();function e(r){return function(n){let o=re[be++];if(o==null){if(B)return Ie(n);let b=t(c,V,n,p);if(typeof b=="string")o=b,re=De;else if(re=b,be=1,se=1,o=re[0],o===void 0)throw new Error("Unexpected end of buffer")}let f=o.length;return f<=n?(c+=n,o):(ge=o,me=c,se=c+f,c+=n,o.slice(0,n))}}}function Ie(t){let e;if(t<16&&(e=St(t)))return e;if(t>64&&Ne)return Ne.decode(p.subarray(c,c+=t));const r=c+t,s=[];for(e="";c<r;){const n=p[c++];if((n&128)===0)s.push(n);else if((n&224)===192)if(n<194||c>=r||(p[c]&192)!==128)s.push(65533);else{const o=p[c++]&63;s.push((n&31)<<6|o)}else if((n&240)===224){const o=c<r?p[c]:0;if(c>=r||(o&192)!==128||n===224&&o<160||n===237&&o>=160)s.push(65533);else if(c++,c>=r||(p[c]&192)!==128)s.push(65533);else{const f=p[c++]&63;s.push((n&31)<<12|(o&63)<<6|f)}}else if((n&248)===240){const o=c<r?p[c]:0;if(n>244||c>=r||(o&192)!==128||n===240&&o<144||n===244&&o>=144)s.push(65533);else if(c++,c>=r||(p[c]&192)!==128)s.push(65533);else{const f=p[c++]&63;if(c>=r||(p[c]&192)!==128)s.push(65533);else{const b=p[c++]&63;let y=(n&7)<<18|(o&63)<<12|f<<6|b;y-=65536,s.push(y>>>10&1023|55296),s.push(56320|y&1023)}}}else s.push(65533);s.length>=4096&&(e+=F.apply(String,s),s.length=0)}return s.length>0&&(e+=F.apply(String,s)),e}let F=String.fromCharCode;function yr(t){let e=c,r=new Array(t);for(let s=0;s<t;s++){const n=p[c++];if((n&128)>0){c=e;return}r[s]=n}return F.apply(String,r)}function St(t){if(t<4)if(t<2){if(t===0)return"";{let e=p[c++];if((e&128)>1){c-=1;return}return F(e)}}else{let e=p[c++],r=p[c++];if((e&128)>0||(r&128)>0){c-=2;return}if(t<3)return F(e,r);let s=p[c++];if((s&128)>0){c-=3;return}return F(e,r,s)}else{let e=p[c++],r=p[c++],s=p[c++],n=p[c++];if((e&128)>0||(r&128)>0||(s&128)>0||(n&128)>0){c-=4;return}if(t<6){if(t===4)return F(e,r,s,n);{let o=p[c++];if((o&128)>0){c-=5;return}return F(e,r,s,n,o)}}else if(t<8){let o=p[c++],f=p[c++];if((o&128)>0||(f&128)>0){c-=6;return}if(t<7)return F(e,r,s,n,o,f);let b=p[c++];if((b&128)>0){c-=7;return}return F(e,r,s,n,o,f,b)}else{let o=p[c++],f=p[c++],b=p[c++],y=p[c++];if((o&128)>0||(f&128)>0||(b&128)>0||(y&128)>0){c-=8;return}if(t<10){if(t===8)return F(e,r,s,n,o,f,b,y);{let v=p[c++];if((v&128)>0){c-=9;return}return F(e,r,s,n,o,f,b,y,v)}}else if(t<12){let v=p[c++],m=p[c++];if((v&128)>0||(m&128)>0){c-=10;return}if(t<11)return F(e,r,s,n,o,f,b,y,v,m);let x=p[c++];if((x&128)>0){c-=11;return}return F(e,r,s,n,o,f,b,y,v,m,x)}else{let v=p[c++],m=p[c++],x=p[c++],R=p[c++];if((v&128)>0||(m&128)>0||(x&128)>0||(R&128)>0){c-=12;return}if(t<14){if(t===12)return F(e,r,s,n,o,f,b,y,v,m,x,R);{let L=p[c++];if((L&128)>0){c-=13;return}return F(e,r,s,n,o,f,b,y,v,m,x,R,L)}}else{let L=p[c++],U=p[c++];if((L&128)>0||(U&128)>0){c-=14;return}if(t<15)return F(e,r,s,n,o,f,b,y,v,m,x,R,L,U);let P=p[c++];if((P&128)>0){c-=15;return}return F(e,r,s,n,o,f,b,y,v,m,x,R,L,U,P)}}}}}function wr(t){return O.copyBuffers?Uint8Array.prototype.slice.call(p,c,c+=t):p.subarray(c,c+=t)}let vt=new Float32Array(1),Me=new Uint8Array(vt.buffer,0,4);function br(){let t=p[c++],e=p[c++],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 Me[3]=t&128|(r>>1)+56,Me[2]=(t&7)<<5|e>>3,Me[1]=e<<5,Me[0]=0,vt[0]}new Array(4096);class ie{constructor(e,r){this.value=e,this.tag=r}}N[0]=t=>new Date(t),N[1]=t=>new Date(Math.round(t*1e3)),N[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},N[3]=t=>BigInt(-1)-N[2](t),N[4]=t=>+(t[1]+"e"+t[0]),N[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const je=(t,e)=>{t=t-57344;let r=_[t];r&&r.isShared&&((_.restoreStructures||(_.restoreStructures=[]))[t]=r),_[t]=e,e.read=ze(e)};N[ur]=t=>{let e=t.length,r=t[1];je(t[0],r);let s={};for(let n=2;n<e;n++){let o=r[n-2];s[J(o)]=t[n]}return s},N[14]=t=>B?B[0].slice(B.position0,B.position0+=t):new ie(t,14),N[15]=t=>B?B[1].slice(B.position1,B.position1+=t):new ie(t,15);let gr={Error,RegExp};N[27]=t=>(gr[t[0]]||Error)(t[1],t[2]);const At=t=>{if(p[c++]!=132){let r=new Error("Packed values structure must be followed by a 4 element array");throw p.length<c&&(r.incomplete=!0),r}let e=t();if(!e||!e.length){let r=new Error("Packed values structure must be followed by a 4 element array");throw r.incomplete=!0,r}return K=K?e.concat(K.slice(e.length)):e,K.prefixes=t(),K.suffixes=t(),t()};At.handlesRead=!0,N[51]=At,N[wt]=t=>{if(!K)if(O.getShared)Ve();else return new ie(t,wt);if(typeof t=="number")return K[16+(t>=0?2*t:-2*t-1)];let e=new Error("No support for non-integer packed references yet");throw t===void 0&&(e.incomplete=!0),e},N[28]=t=>{q||(q=new Map,q.id=0);let e=q.id++,r=c,s=p[c],n;s>>5==4?n=[]:n={};let o={target:n};q.set(e,o);let f=t();return o.used?(Object.getPrototypeOf(n)!==Object.getPrototypeOf(f)&&(c=r,n=f,q.set(e,{target:n}),f=t()),Object.assign(n,f)):(o.target=f,f)},N[28].handlesRead=!0,N[29]=t=>{let e=q.get(t);return e.used=!0,e.target},N[258]=t=>new Set(t),(N[259]=t=>(O.mapsAsObjects&&(O.mapsAsObjects=!1,Ee=!0),t())).handlesRead=!0;function ue(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function oe(){if(!K)if(O.getShared)Ve();else throw new Error("No packed values available");return K}const mr=1399353956;Fe.push((t,e)=>{if(t>=225&&t<=255)return ue(oe().prefixes[t-224],e);if(t>=28704&&t<=32767)return ue(oe().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return ue(oe().prefixes[t-1879048192],e);if(t>=216&&t<=223)return ue(e,oe().suffixes[t-216]);if(t>=27647&&t<=28671)return ue(e,oe().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return ue(e,oe().suffixes[t-1811939328]);if(t==mr)return{packedValues:K,structures:_.slice(0),version:e};if(t==55799)return e});const Er=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,kt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],Sr=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<kt.length;t++)vr(kt[t],Sr[t]);function vr(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 o=s==2?1:s==4?2:s==8?3:0;N[n?e:e-4]=s==1||n==Er?f=>{if(!t)throw new Error("Could not find typed array for code "+e);return!O.copyBuffers&&(s===1||s===2&&!(f.byteOffset&1)||s===4&&!(f.byteOffset&3)||s===8&&!(f.byteOffset&7))?new t(f.buffer,f.byteOffset,f.byteLength>>o):new t(Uint8Array.prototype.slice.call(f,0).buffer)}:f=>{if(!t)throw new Error("Could not find typed array for code "+e);let b=new DataView(f.buffer,f.byteOffset,f.byteLength),y=f.length>>o,v=new t(y),m=b[r];for(let x=0;x<y;x++)v[x]=m.call(b,x<<o,n);return v}}}function Ar(){let t=de(),e=c+I();for(let s=2;s<t;s++){let n=de();c+=n}let r=c;return c=e,B=[Ie(de()),Ie(de())],B.position0=0,B.position1=0,B.postBundlePosition=c,c=r,I()}function de(){if(!(c<V))throw ne();let t=p[c++]&31;if(t>23)switch(t){case 24:if(c>=V)throw ne();t=p[c++];break;case 25:t=j.getUint16(c),c+=2;break;case 26:t=j.getUint32(c),c+=4;break}return t}function Ve(){if(O.getShared){let t=Ot(()=>(p=null,O.getShared()))||{},e=t.structures||[];O.sharedVersion=t.version,K=O.sharedValues=t.packedValues,_===!0?O.structures=_=e:_.splice.apply(_,[0,e.length].concat(e))}}function Ot(t){let e=V,r=c,s=be,n=me,o=se,f=ge,b=re,y=q,v=B,m=new Uint8Array(p.slice(0,V)),x=_,R=O,L=Se,U=t();return V=e,c=r,be=s,me=n,se=o,ge=f,re=b,q=y,B=v,p=m,Se=L,_=x,O=R,j=new DataView(p.buffer,p.byteOffset,p.byteLength),U}function Ke(){p=null,q=null,_=null}const $e=new Array(147);for(let t=0;t<256;t++)$e[t]=+("1e"+Math.floor(45.15-t*.30103));let qe=new he({useRecords:!1});const kr=qe.decode;qe.decodeMultiple;let xe;try{xe=new TextEncoder}catch{}let Je,It;const Re=typeof globalThis=="object"&&globalThis.Buffer,ve=typeof Re<"u",We=ve?Re.allocUnsafeSlow:Uint8Array,Mt=ve?Re:Uint8Array,xt=256,Rt=ve?4294967296:2144337920;let He,l,C,i=0,Q,D=null;const Or=61440,Ir=/[\u0080-\uFFFF]/,$=Symbol("record-id");class Tt extends he{constructor(e){super(e),this.offset=0;let r,s,n,o,f;e=e||{};let b=Mt.prototype.utf8Write?function(a,w){return l.utf8Write(a,w,l.byteLength-w)}:xe&&xe.encodeInto?function(a,w){return xe.encodeInto(a,l.subarray(w)).written}:!1,y=this,v=e.structures||e.saveStructures,m=e.maxSharedStructures;if(m==null&&(m=v?128:0),m>8190)throw new Error("Maximum maxSharedStructure is 8190");let x=e.sequential;x&&(m=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let R,L,U=e.sharedValues,P;if(U){P=Object.create(null);for(let a=0,w=U.length;a<w;a++)P[U[a]]=a}let W=[],pe=0,H=0;this.mapEncode=function(a,w){return this._keyMap&&!this._mapped&&a.constructor.name==="Array"&&(a=a.map(d=>this.encodeKeys(d))),this.encode(a,w)},this.encode=function(a,w){if(l||(l=new We(8192),C=new DataView(l.buffer,0,8192),i=0),Q=l.length-10,Q-i<2048?(l=new We(l.length),C=new DataView(l.buffer,0,l.length),Q=l.length-10,i=0):w===Lt&&(i=i+7&2147483640),r=i,y.useSelfDescribedHeader&&(C.setUint32(i,3654940416),i+=3),f=y.structuredClone?new Map:null,y.bundleStrings&&typeof a!="string"?(D=[],D.size=1/0):D=null,s=y.structures,s){if(s.uninitialized){let h=y.getShared()||{};y.structures=s=h.structures||[],y.sharedVersion=h.version;let u=y.sharedValues=h.packedValues;if(u){P={};for(let g=0,E=u.length;g<E;g++)P[u[g]]=g}}let d=s.length;if(d>m&&!x&&(d=m),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let g,E=s.transitions;for(let S=0,A=u.length;S<A;S++){E[$]===void 0&&(E[$]=h);let M=u[S];g=E[M],g||(g=E[M]=Object.create(null)),E=g}E[$]=h|1048576}}x||(s.nextId=d)}if(n&&(n=!1),o=s||[],L=P,e.pack){let d=new Map;if(d.values=[],d.encoder=y,d.maxValues=e.maxPrivatePackedValues||(P?16:1/0),d.objectMap=P||!1,d.samplingPackedValues=R,Te(a,d),d.values.length>0){l[i++]=216,l[i++]=51,G(4);let h=d.values;k(h),G(0),G(0),L=Object.create(P||null);for(let u=0,g=h.length;u<g;u++)L[h[u]]=u}}He=w&Xe;try{if(He)return;if(k(a),D&&Ut(r,k),y.offset=i,f&&f.idsToInsert){i+=f.idsToInsert.length*2,i>Q&&le(i),y.offset=i;let d=Rr(l.subarray(r,i),f.idsToInsert);return f=null,d}return w&Lt?(l.start=r,l.end=i,l):l.subarray(r,i)}finally{if(s){if(H<10&&H++,s.length>m&&(s.length=m),pe>1e4)s.transitions=null,H=0,pe=0,W.length>0&&(W=[]);else if(W.length>0&&!x){for(let d=0,h=W.length;d<h;d++)W[d][$]=void 0;W=[]}}if(n&&y.saveShared){y.structures.length>m&&(y.structures=y.structures.slice(0,m));let d=l.subarray(r,i);return y.updateSharedData()===!1?y.encode(a):d}w&Cr&&(i=r)}},this.findCommonStringsToPack=()=>(R=new Map,P||(P=Object.create(null)),a=>{let w=a&&a.threshold||4,d=this.pack?a.maxPrivatePackedValues||16:0;U||(U=this.sharedValues=[]);for(let[h,u]of R)u.count>w&&(P[h]=d++,U.push(h),n=!0);for(;this.saveShared&&this.updateSharedData()===!1;);R=null});const k=a=>{i>Q&&(l=le(i));var w=typeof a,d;if(w==="string"){if(L){let E=L[a];if(E>=0){E<16?l[i++]=E+224:(l[i++]=198,E&1?k(15-E>>1):k(E-16>>1));return}else if(R&&!e.pack){let S=R.get(a);S?S.count++:R.set(a,{count:1})}}let h=a.length;if(D&&h>=4&&h<1024){if((D.size+=h)>Or){let S,A=(D[0]?D[0].length*3+D[1].length:0)+10;i+A>Q&&(l=le(i+A)),l[i++]=217,l[i++]=223,l[i++]=249,l[i++]=D.position?132:130,l[i++]=26,S=i-r,i+=4,D.position&&Ut(r,k),D=["",""],D.size=0,D.position=S}let E=Ir.test(a);D[E?0:1]+=a,l[i++]=E?206:207,k(h);return}let u;h<32?u=1:h<256?u=2:h<65536?u=3:u=5;let g=h*3;if(i+g>Q&&(l=le(i+g)),h<64||!b){let E,S,A,M=i+u;for(E=0;E<h;E++)S=a.charCodeAt(E),S<128?l[M++]=S:S<2048?(l[M++]=S>>6|192,l[M++]=S&63|128):(S&64512)===55296&&((A=a.charCodeAt(E+1))&64512)===56320?(S=65536+((S&1023)<<10)+(A&1023),E++,l[M++]=S>>18|240,l[M++]=S>>12&63|128,l[M++]=S>>6&63|128,l[M++]=S&63|128):(l[M++]=S>>12|224,l[M++]=S>>6&63|128,l[M++]=S&63|128);d=M-i-u}else d=b(a,i+u,g);d<24?l[i++]=96|d:d<256?(u<2&&l.copyWithin(i+2,i+1,i+1+d),l[i++]=120,l[i++]=d):d<65536?(u<3&&l.copyWithin(i+3,i+2,i+2+d),l[i++]=121,l[i++]=d>>8,l[i++]=d&255):(u<5&&l.copyWithin(i+5,i+3,i+3+d),l[i++]=122,C.setUint32(i,d),i+=4),i+=d}else if(w==="number")if(!this.alwaysUseFloat&&a>>>0===a)a<24?l[i++]=a:a<256?(l[i++]=24,l[i++]=a):a<65536?(l[i++]=25,l[i++]=a>>8,l[i++]=a&255):(l[i++]=26,C.setUint32(i,a),i+=4);else if(!this.alwaysUseFloat&&a>>0===a)a>=-24?l[i++]=31-a:a>=-256?(l[i++]=56,l[i++]=~a):a>=-65536?(l[i++]=57,C.setUint16(i,~a),i+=2):(l[i++]=58,C.setUint32(i,~a),i+=4);else if(!this.alwaysUseFloat&&a<0&&a>=-4294967296&&Math.floor(a)===a)l[i++]=58,C.setUint32(i,-1-a),i+=4;else{let h;if((h=this.useFloat32)>0&&a<4294967296&&a>=-2147483648){l[i++]=250,C.setFloat32(i,a);let u;if(h<4||(u=a*$e[(l[i]&127)<<1|l[i+1]>>7])>>0===u){i+=4;return}else i--}l[i++]=251,C.setFloat64(i,a),i+=8}else if(w==="object")if(!a)l[i++]=246;else{if(f){let u=f.get(a);if(u){if(l[i++]=216,l[i++]=29,l[i++]=25,!u.references){let g=f.idsToInsert||(f.idsToInsert=[]);u.references=[],g.push(u)}u.references.push(i-r),i+=2;return}else f.set(a,{offset:i-r})}let h=a.constructor;if(h===Object)this.skipFunction===!0&&(a=Object.fromEntries([...Object.keys(a).filter(u=>typeof a[u]!="function").map(u=>[u,a[u]])])),z(a);else if(h===Array){d=a.length,d<24?l[i++]=128|d:G(d);for(let u=0;u<d;u++)k(a[u])}else if(h===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(l[i++]=217,l[i++]=1,l[i++]=3),d=a.size,d<24?l[i++]=160|d:d<256?(l[i++]=184,l[i++]=d):d<65536?(l[i++]=185,l[i++]=d>>8,l[i++]=d&255):(l[i++]=186,C.setUint32(i,d),i+=4),y.keyMap)for(let[u,g]of a)k(y.encodeKey(u)),k(g);else for(let[u,g]of a)k(u),k(g);else{for(let u=0,g=Je.length;u<g;u++){let E=It[u];if(a instanceof E){let S=Je[u],A=S.tag;A==null&&(A=S.getTag&&S.getTag.call(this,a)),A<24?l[i++]=192|A:A<256?(l[i++]=216,l[i++]=A):A<65536?(l[i++]=217,l[i++]=A>>8,l[i++]=A&255):A>-1&&(l[i++]=218,C.setUint32(i,A),i+=4),S.encode.call(this,a,k,le);return}}if(a[Symbol.iterator]){if(He){let u=new Error("Iterable should be serialized as iterator");throw u.iteratorNotHandled=!0,u}l[i++]=159;for(let u of a)k(u);l[i++]=255;return}if(a[Symbol.asyncIterator]||Ge(a)){let u=new Error("Iterable/blob should be serialized as iterator");throw u.iteratorNotHandled=!0,u}if(this.useToJSON&&a.toJSON){const u=a.toJSON();if(u!==a)return k(u)}z(a)}}else if(w==="boolean")l[i++]=a?245:244;else if(w==="bigint"){if(a<BigInt(1)<<BigInt(64)&&a>=0)l[i++]=27,C.setBigUint64(i,a);else if(a>-(BigInt(1)<<BigInt(64))&&a<0)l[i++]=59,C.setBigUint64(i,-a-BigInt(1));else if(this.largeBigIntToFloat)l[i++]=251,C.setFloat64(i,Number(a));else{a>=BigInt(0)?l[i++]=194:(l[i++]=195,a=BigInt(-1)-a);let h=[];for(;a;)h.push(Number(a&BigInt(255))),a>>=BigInt(8);Ze(new Uint8Array(h.reverse()),le);return}i+=8}else if(w==="undefined")l[i++]=247;else throw new Error("Unknown type: "+w)},z=this.useRecords===!1?this.variableMapSize?a=>{let w=Object.keys(a),d=Object.values(a),h=w.length;if(h<24?l[i++]=160|h:h<256?(l[i++]=184,l[i++]=h):h<65536?(l[i++]=185,l[i++]=h>>8,l[i++]=h&255):(l[i++]=186,C.setUint32(i,h),i+=4),y.keyMap)for(let u=0;u<h;u++)k(y.encodeKey(w[u])),k(d[u]);else for(let u=0;u<h;u++)k(w[u]),k(d[u])}:a=>{l[i++]=185;let w=i-r;i+=2;let d=0;if(y.keyMap)for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(k(y.encodeKey(h)),k(a[h]),d++);else for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(k(h),k(a[h]),d++);l[w+++r]=d>>8,l[w+r]=d&255}:(a,w)=>{let d,h=o.transitions||(o.transitions=Object.create(null)),u=0,g=0,E,S;if(this.keyMap){S=Object.keys(a).map(M=>this.encodeKey(M)),g=S.length;for(let M=0;M<g;M++){let ht=S[M];d=h[ht],d||(d=h[ht]=Object.create(null),u++),h=d}}else for(let M in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(M))&&(d=h[M],d||(h[$]&1048576&&(E=h[$]&65535),d=h[M]=Object.create(null),u++),h=d,g++);let A=h[$];if(A!==void 0)A&=65535,l[i++]=217,l[i++]=A>>8|224,l[i++]=A&255;else if(S||(S=h.__keys__||(h.__keys__=Object.keys(a))),E===void 0?(A=o.nextId++,A||(A=0,o.nextId=1),A>=xt&&(o.nextId=(A=m)+1)):A=E,o[A]=S,A<m){l[i++]=217,l[i++]=A>>8|224,l[i++]=A&255,h=o.transitions;for(let M=0;M<g;M++)(h[$]===void 0||h[$]&1048576)&&(h[$]=A),h=h[S[M]];h[$]=A|1048576,n=!0}else{if(h[$]=A,C.setUint32(i,3655335680),i+=3,u&&(pe+=H*u),W.length>=xt-m&&(W.shift()[$]=void 0),W.push(h),G(g+2),k(57344+A),k(S),w)return;for(let M in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(M))&&k(a[M]);return}if(g<24?l[i++]=128|g:G(g),!w)for(let M in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(M))&&k(a[M])},le=a=>{let w;if(a>16777216){if(a-r>Rt)throw new Error("Encoded buffer would be larger than maximum buffer size");w=Math.min(Rt,Math.round(Math.max((a-r)*(a>67108864?1.25:2),4194304)/4096)*4096)}else w=(Math.max(a-r<<2,l.length-1)>>12)+1<<12;let d=new We(w);return C=new DataView(d.buffer,0,w),l.copy?l.copy(d,0,r,a):d.set(l.slice(r,a)),i-=r,r=0,Q=d.length-10,l=d};let ee=100,ft=1e3;this.encodeAsIterable=function(a,w){return ut(a,w,ce)},this.encodeAsAsyncIterable=function(a,w){return ut(a,w,dt)};function*ce(a,w,d){let h=a.constructor;if(h===Object){let u=y.useRecords!==!1;u?z(a,!0):Ct(Object.keys(a).length,160);for(let g in a){let E=a[g];u||k(g),E&&typeof E=="object"?w[g]?yield*ce(E,w[g]):yield*_e(E,w,g):k(E)}}else if(h===Array){let u=a.length;G(u);for(let g=0;g<u;g++){let E=a[g];E&&(typeof E=="object"||i-r>ee)?w.element?yield*ce(E,w.element):yield*_e(E,w,"element"):k(E)}}else if(a[Symbol.iterator]&&!a.buffer){l[i++]=159;for(let u of a)u&&(typeof u=="object"||i-r>ee)?w.element?yield*ce(u,w.element):yield*_e(u,w,"element"):k(u);l[i++]=255}else Ge(a)?(Ct(a.size,64),yield l.subarray(r,i),yield a,ye()):a[Symbol.asyncIterator]?(l[i++]=159,yield l.subarray(r,i),yield a,ye(),l[i++]=255):k(a);d&&i>r?yield l.subarray(r,i):i-r>ee&&(yield l.subarray(r,i),ye())}function*_e(a,w,d){let h=i-r;try{k(a),i-r>ee&&(yield l.subarray(r,i),ye())}catch(u){if(u.iteratorNotHandled)w[d]={},i=r+h,yield*ce.call(this,a,w[d]);else throw u}}function ye(){ee=ft,y.encode(null,Xe)}function ut(a,w,d){return w&&w.chunkThreshold?ee=ft=w.chunkThreshold:ee=100,a&&typeof a=="object"?(y.encode(null,Xe),d(a,y.iterateProperties||(y.iterateProperties={}),!0)):[y.encode(a)]}async function*dt(a,w){for(let d of ce(a,w,!0)){let h=d.constructor;if(h===Mt||h===Uint8Array)yield d;else if(Ge(d)){let u=d.stream().getReader(),g;for(;!(g=await u.read()).done;)yield g.value}else if(d[Symbol.asyncIterator])for await(let u of d)ye(),u?yield*dt(u,w.async||(w.async={})):yield y.encode(u);else yield d}}}useBuffer(e){l=e,C=new DataView(l.buffer,l.byteOffset,l.byteLength),i=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 Pt(r,this.sharedValues,this.sharedVersion),n=this.saveShared(s,o=>(o&&o.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((o,f)=>this.structures[f]=o),n}}function Ct(t,e){t<24?l[i++]=e|t:t<256?(l[i++]=e|24,l[i++]=t):t<65536?(l[i++]=e|25,l[i++]=t>>8,l[i++]=t&255):(l[i++]=e|26,C.setUint32(i,t),i+=4)}class Pt{constructor(e,r,s){this.structures=e,this.packedValues=r,this.version=s}}function G(t){t<24?l[i++]=128|t:t<256?(l[i++]=152,l[i++]=t):t<65536?(l[i++]=153,l[i++]=t>>8,l[i++]=t&255):(l[i++]=154,C.setUint32(i,t),i+=4)}const Mr=typeof Blob>"u"?function(){}:Blob;function Ge(t){if(t instanceof Mr)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function Te(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++)Te(t[s],e);else{let s=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(s&&Te(r,e),Te(t[r],e))}break;case"function":console.log(t)}}const xr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;It=[Date,Set,Error,RegExp,ie,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,Pt],Je=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(l[i++]=26,C.setUint32(i,r),i+=4):(l[i++]=251,C.setFloat64(i,r),i+=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){Ze(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||ve&&this.tagUint8Array!==!1))return 64},encode(t,e,r){Ze(t,r)}},Z(68,1),Z(69,2),Z(70,4),Z(71,8),Z(72,1),Z(77,2),Z(78,4),Z(79,8),Z(85,4),Z(86,8),{encode(t,e){let r=t.packedValues||[],s=t.structures||[];if(r.values.length>0){l[i++]=216,l[i++]=51,G(4);let n=r.values;e(n),G(0),G(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let o=0,f=n.length;o<f;o++)packedObjectMap[n[o]]=o}if(s){C.setUint32(i,3655335424),i+=3;let n=s.slice(0);n.unshift(57344),n.push(new ie(t.version,1399353956)),e(n)}else e(new ie(t.version,1399353956))}}];function Z(t,e){return!xr&&e>1&&(t-=4),{tag:t,encode:function(s,n){let o=s.byteLength,f=s.byteOffset||0,b=s.buffer||s;n(ve?Re.from(b,f,o):new Uint8Array(b,f,o))}}}function Ze(t,e){let r=t.byteLength;r<24?l[i++]=64+r:r<256?(l[i++]=88,l[i++]=r):r<65536?(l[i++]=89,l[i++]=r>>8,l[i++]=r&255):(l[i++]=90,C.setUint32(i,r),i+=4),i+r>=l.length&&e(i+r),l.set(t.buffer?t:new Uint8Array(t),i),i+=r}function Rr(t,e){let r,s=e.length*2,n=t.length-s;e.sort((o,f)=>o.offset>f.offset?1:-1);for(let o=0;o<e.length;o++){let f=e[o];f.id=o;for(let b of f.references)t[b++]=o>>8,t[b]=o&255}for(;r=e.pop();){let o=r.offset;t.copyWithin(o+s,o,n),s-=2;let f=o+s;t[f++]=216,t[f++]=28,n=o}return t}function Ut(t,e){C.setUint32(D.position+t,i-D.position-t+1);let r=D;D=null,e(r[0]),e(r[1])}let Ye=new Tt({useRecords:!1});const Tr=Ye.encode;Ye.encodeAsIterable,Ye.encodeAsAsyncIterable;const Lt=512,Cr=1024,Xe=2048;class Pr extends Qt{constructor(e){e||(e={}),e.objectMode=!0,super(e),e.structures=[],this.decoder=e.decoder||new he(e)}_transform(e,r,s){this.incompleteBuffer&&(e=Buffer.concat([this.incompleteBuffer,e]),this.incompleteBuffer=null);let n;try{n=this.decoder.decodeMultiple(e)}catch(o){if(o.incomplete)this.incompleteBuffer=e.slice(o.lastPosition),n=o.values;else return s(o)}finally{for(let o of n||[])o===null&&(o=this.getNullValue()),this.push(o)}s()}getNullValue(){return Symbol.for(null)}}const Ur=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!Ur){let t;try{typeof require=="function"?t=require("cbor-extract"):t=er(import.meta.url)("cbor-extract"),t&&pr(t.extractStrings)}catch{}}class Lr{#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 T=Symbol.for("@appetizeio/rpc:rpcMethods");class _r extends Lr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(new CloseEvent("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}function Qe(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}function Br(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}class Ae{closed=!1;[T];#e;constructor(e,{signal:r}={}){this[T]=new _r(e),this.#e=r,this.#e?.addEventListener("abort",this.#t)}close(e={}){this.closed||(this.closed=!0,this.handleClose(e))}handleClose(e){this.#e?.removeEventListener("abort",this.#t),this[T].dispatchClose(e)}#t=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const _t={useRecords:!1},Nr=new Tt(_t);class Bt extends Ae{#e=[];#t;constructor(e,{signal:r}={}){super(async f=>{this.#t.write(Nr.encode(f))},{signal:r}),this.#t=e;const s=new Pr(_t);s.on("data",f=>{Qe(f)&&this[T].dispatchMessage(f)}),s.on("error",()=>{this.close()});const n=f=>{s.write(f)},o=()=>{this.close()};e.on("data",n),e.once("close",o),e.once("error",o),this.#e.push(()=>{e.off("data",n),e.off("close",o),e.off("error",o),s.destroy()})}handleClose(e){for(const r of this.#e.splice(0))r();super.handleClose(e)}}function Dr(t,e){const{promise:r,reject:s,resolve:n}=Br(),o=tr(t),f=e?.signal,b=()=>{o.off("connect",m),o.off("error",x),f?.removeEventListener("abort",v)},y=R=>{b(),o.destroy(),s(R)},v=()=>{y(new Error("The connection was aborted"))},m=()=>{b();const R=new Bt(o,e);R[T].addEventListener("close",()=>{o.destroy()},{once:!0}),n(R)},x=R=>{y(R)};return f?.aborted?(y(new Error("The connection was aborted")),r):(o.once("connect",m),o.once("error",x),f?.addEventListener("abort",v,{once:!0}),r)}const Nt=Be("appetize.io:error:rpc");function et(t,e){const r=new rr(new sr({errorListener:Nt}),Fr(t),{errorListener:Nt}),s=t[T].addEventListener("message",({detail:o})=>{r.receiveAndSend(o)}),n=t[T].addEventListener("close",()=>{s(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const o in e){const f=e[o];f&&r.addMethod(o,f.bind(e))}return{rpc:r,unsub:()=>{s(),n()}}}function Dt(t,e){const{rpc:r,unsub:s}=et(t,e);return{client:r.client,unsub:s}}function Ce(t,e){const r=t[T].addEventListener("message",({detail:n})=>{if("method"in n)try{e({method:n.method,param:n.params})}catch{}}),s=t[T].addEventListener("close",r,{once:!0});return()=>{r(),s()}}function Fr(t){return new nr(t[T].send.bind(t[T]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function tt(t,e,{leftEffects:r=()=>({}),notifiesLeft:s,notifiesRight:n,rightEffects:o=()=>({})}={}){const f=et(t,{}),b=et(e,{}),y=[()=>{f.unsub(),b.unsub()}],v=()=>{for(const U of y)try{U()}catch{}},m=b.rpc.client,x=f.rpc.client;y.push(t[T].addEventListener("close",()=>{v()},{once:!0}),e[T].addEventListener("close",()=>{v()},{once:!0}));const R=r(m,x);for(const U in R){const P=R[U];P&&f.rpc.addMethod(U,P)}const L=o(x,m);for(const U in L){const P=L[U];P&&b.rpc.addMethod(U,P)}return Ft(f.rpc,b.rpc,{notifies:s}),Ft(b.rpc,f.rpc,{notifies:n}),v}function Ft(t,e,{notifies:r}={}){t.applyServerMiddleware(async(s,n)=>{const o=r?.();if(o){const{id:b,...y}=n;o[T].send(y)}if(t.hasMethod(n.method))return await s(n);if(!n.id)return e.notify(n.method,n.params),null;const f=await e.request(n.method,n.params);return{id:n.id,jsonrpc:ir,result:f}})}function X(t,...e){t.notify(e[0],e[1],e[2])}const zr=(...t)=>Dt(...t),rt=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"];function st(){const t=new Ae(async r=>{e[T].dispatchMessage(r)}),e=new Ae(async r=>{t[T].dispatchMessage(r)});return t[T].addEventListener("close",()=>{e.close()},{once:!0}),e[T].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function zt(t,e){const r=[],s=()=>{for(const n of r)n()};r.push(t[T].addEventListener("message",n=>e[T].send(n.detail))),r.push(t[T].addEventListener("close",s,{once:!0})),r.push(e[T].addEventListener("message",n=>t[T].send(n.detail))),r.push(e[T].addEventListener("close",s,{once:!0}))}const ae=Be("appetize.io:trace:transport:iframe");class jt extends Ae{onmessage;#e;#t;constructor(e,{origin:r="*",signal:s}={}){super(async n=>{e.postMessage(n,this.#e)},{signal:s}),this.#t=e,this.#e=r,window.addEventListener("message",this.#r)}postMessage(e,r,s){ae("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#t.postMessage(e,r??this.#e,s)}handleClose(e){ae("close()"),window.removeEventListener("message",this.#r),super.handleClose(e)}#r=async e=>{if(ae("handleMessage()",e),e.source!==this.#t||(ae("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ae("handleMessage() -> origin ok");const r=e.data;if(!Qe(r)){ae("handleMessage() -> legacy"),this.onmessage?.(e);return}ae("handleMessage() -> jsonrpc"),this[T].dispatchMessage(r)}}function Pe(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const jr=2*1024*1024,Vt=Be("appetize:client:acked-writable-stream");class Vr{unacked=0;#e;#t;#r;#s;#n=[];#i;constructor(e){this.#r=e,this.#i=e.window??jr}abort(e){this.#a(e),this.#r.onAbort?.(e)}async close(){await this.#l(()=>this.unacked===0),this.#r.onClose?.()}fail(e){this.#a(e)&&this.#r.onError?.(e)}start(e){this.#e=e}write(e){const r=e.byteLength;return this.unacked+=r,this.#r.send(e).then(()=>{this.unacked-=r,this.#s&&(this.#s.acked+=r),this.#o()},s=>{this.fail(s)}),this.unacked>=this.#i&&!this.#s&&(this.#s={acked:0,at:performance.now()},Vt("window full: %d bytes unacked, writes stalled",this.unacked)),this.#l(()=>this.unacked<this.#i)}#o(){if(this.#s&&this.unacked<=this.#i/2){const e=performance.now()-this.#s.at;Vt("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)}#a(e){if(this.#t)return!1;this.#t={reason:e},this.#e.error(e);const r=this.#n;this.#n=[];for(const s of r)s.reject(e);return!0}#l(e){if(e())return Promise.resolve();const r={...Pe(),until:e};return this.#n.push(r),r.promise}}class Kr extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new Vr(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 $r=1024*1024;class qr{#e;#t=!1;#r;#s;constructor(e){this.#r=e}cancel(e){this.#n(),this.#r?.(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.#t)return;this.#s??=Pe();const{promise:r}=this.#s;this.#e.enqueue(e),await r}start(e){this.#e=e}#n(){return this.#t?!1:(this.#t=!0,this.pull(),!0)}}class Jr extends ReadableStream{#e;constructor({highWaterMark:e=$r,onCancel:r}={}){const s=new qr(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 Wr{closed;readable;writable;#e=[];#t;#r;#s;#n;#i;#o="starting";constructor(e,{onClose:r,receiveBuffer:s,sendWindow:n,signal:o}){if(this.#i=e,this.#t=Pe(),this.closed=this.#t.promise,this.closed.catch(Hr),this.#s=new Jr({highWaterMark:s,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#s,this.#n=new Kr({onAbort:()=>{this.#a(void 0)},onClose:()=>{this.#a(void 0)},onError:f=>{this.#a(f)},send:f=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:f}),window:n}),this.writable=this.#n,o){const f=()=>{this.#a(o.reason)};o.addEventListener("abort",f,{once:!0}),this.#e.push(()=>{o.removeEventListener("abort",f)})}this.#e.push(()=>{r(this)})}close=()=>{this.#a(void 0)};detach(){this.#a(void 0,{notifyServer:!1})}async handleData(e){this.#o==="open"&&await this.#s.push(e)}handleStopped({error:e}){this.#o==="open"&&this.#a(e?new Error(e):void 0)}async start(){try{await this.#i.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#a(e),e}if(this.#o==="closed")throw this.#r?this.#r:new Error("The adb tunnel closed before it started");this.#o="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#a(e,{notifyServer:r=!0}={}){if(this.#o!=="closed"){this.#o="closed",this.#r=e,r&&X(this.#i,"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.#t.reject(e):this.#t.resolve(void 0)}}}function Hr(){}class Gr{readable;ready;#e=[];#t=!1;#r;#s;#n;constructor({label:e,onClose:r,signal:s}){this.#s=e,this.ready=new Promise((o,f)=>{this.#n={reject:f,resolve:o}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#o()},start:o=>{n=o}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#r=n,s){const o=()=>{this.fail(s.reason)};s.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",o)})}this.#e.push(()=>{r(this)})}close=()=>{this.#i()};fail(e){this.#i(e)}handleItem(e){this.#r.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()}}#i(e){this.#t||(this.#r.close(),this.#o(e))}#o(e){this.#t=!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 Zr{get subscribers(){return this.#r}#e;#t;#r=new Set;constructor(e){this.#e=e}close(){this.#t=void 0;for(const e of[...this.#r])e.close();this.#r.clear()}add(e){this.#r.add(e)}ensureStarted(){return this.#t||(this.#t=(async()=>{try{return await this.#e.start()}catch(e){throw this.#t=void 0,e}})()),this.#t}release(e){this.#r.delete(e),!(this.#r.size>0||!this.#t)&&(this.#t=void 0,this.#e.stop())}}class Kt extends Zr{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Gr({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 Yr{#e;#t;#r;#s;constructor(e){this.#s=e,this.#t=new Kt({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{X(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#r=new Kt({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{X(e,"appetizeio.device.server.debug.proxyIntercept.stop",void 0)}})}close(){this.#e?.detach(),this.#t.close(),this.#r.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new Wr(this.#s,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#t.createStream(e)}async createProxyInterceptStream(e){return await this.#r.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#t.handleNotification(e)}handleProxyInterceptEvent(e){this.#r.handleNotification(e)}}function nt(t){return{...Xr(t),index:t.index,within:t.within?nt(t.within):void 0}}function Xr(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:Qr(t.text)}}}function Qr(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function es(t){return{press:e=>{X(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function ts({onRequest:t,parent:e,proxyInlet:r,signal:s}){const n=new jt(e,{signal:s}),o=[()=>{n.close()}];return zt(n,r),t&&o.push(Ce(n,f=>{t(f,{source:"parent"})})),{cleanup:()=>{for(const f of o)f()},notifies:()=>e===globalThis.window?void 0:n}}const rs="@appetizeio/rpc:playwrightAdapter",Ue=Symbol.for(rs);function ss(t){window[Ue]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[T].send(r)},subscribe(r){return t[T].addEventListener("message",s=>{r(s.detail)})}};return window[Ue]=e,()=>{window[Ue]===e&&delete window[Ue]}}function ns({onRequest:t,proxyInlet:e}){const[r,s]=st(),o=[ss(s),()=>{r.close()}];return zt(r,e),t&&o.push(Ce(r,f=>{t(f,{source:"parent"})})),{cleanup:()=>{for(const f of o)f()},notifies:()=>r}}function Le(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...nt(t),x:t.x,y:t.y}}function is(t){return"to"in t?{from:Le(t.from),kind:"path",to:Le(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?Le(t.from):void 0,kind:"direction"}}function os(t){return{down:(e,r)=>{X(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{X(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{X(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const as=new Set(rt),ls=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,cs=/(\{\{|\{[^{}]*\})/u;function fs(t){const e=[];let r="";function s(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[n,o]of t.split(cs).entries())if(n%2===0){if(o.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=o}else o==="{{"?r+="{":(s(),e.push(ds(o.slice(1,-1))));return s(),e}function us(t,e){if(!as.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: ${rt.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function ds(t){const e=ls.exec(t)?.groups,r=e?.key??t;if(us(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 hs=Symbol("@appetizeio/client:v1Compat");function $t(t){return t?.[hs]}class ps{readable;ready;get dimensions(){return this.#s}#e=[];#t=!1;#r;#s;#n;#i;constructor({onClose:e,requestKeyFrame:r,signal:s}){this.#n=r,this.ready=new Promise((o,f)=>{this.#i={reject:f,resolve:o}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:o=>{n=o}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#r=n,s){const o=()=>{this.fail(s.reason)};s.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",o)})}this.#e.push(()=>{e(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleChunk(e){if(this.#i){if(e.type!=="key")return;const{resolve:r}=this.#i;this.#i=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.#r.enqueue(e)}requestKeyFrame=()=>{this.#t||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()}}#o(e){this.#t||(this.#r.close(),this.#a(e))}#a(e){this.#t=!0;for(const r of this.#e)r();this.#i?.reject(e??new Error("Video stream closed before the first key chunk")),this.#i=void 0}}class ys{#e=!1;#t;#r;#s=new Set;constructor(e){this.#t=e}close(){this.#r=void 0;for(const e of[...this.#s])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new ps({onClose:s=>{this.#i(s)},requestKeyFrame:()=>{this.#o()},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.#r?(this.#o(),this.#r):(this.#e=!0,this.#r=(async()=>{try{await this.#t.request("appetizeio.device.server.video.start")}catch(e){throw this.#r=void 0,e}})(),this.#r)}#i(e){this.#s.delete(e),!(this.#s.size>0||!this.#r)&&(this.#r=void 0,X(this.#t,"appetizeio.device.server.video.stop",void 0))}#o(){this.#e||(this.#e=!0,X(this.#t,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class ws{debug;keyboard;touch;video;#e;#t=[];#r;constructor(e,r={}){const s=$t(r)??{},{baseUrl:n,onClose:o,signal:f}=r;this.#e=n?bs(n):void 0;const{onRequest:b,parent:y,proxyRequest:v}=s,m=gs(b);f?.addEventListener("abort",this.close);const[x,R]=st(),[L,U]=st();this.#t.push(()=>{x.close(),R.close(),L.close(),U.close()}),this.#t.push(tt(U,e,{leftEffects:v}));const P=y==="playwright"?ns({onRequest:m,proxyInlet:L}):y?ts({onRequest:m,parent:y,proxyInlet:L,signal:f}):void 0;P&&this.#t.push(P.cleanup),this.#t.push(tt(R,L,{notifiesLeft:P?.notifies}));const{client:W,unsub:pe}=zr(x,{"appetizeio.device.client.debug.adbTunnel.data":z=>H.handleAdbTunnelData(z),"appetizeio.device.client.debug.adbTunnel.stopped":async z=>{H.handleAdbTunnelStopped(z)},"appetizeio.device.client.debug.log.entry":async z=>{H.handleLogEntry(z)},"appetizeio.device.client.debug.proxyIntercept.event":async z=>{H.handleProxyInterceptEvent(z)},"appetizeio.device.client.video.chunk":async z=>{k.handleChunk(z)}});this.#r=W,this.#t.push(pe);const H=new Yr(this.#r);this.#t.push(()=>{H.close()});const k=new ys(this.#r);this.#t.push(()=>{k.close()}),this.debug=H,this.keyboard=es(this.#r),this.touch=os(this.#r),this.video=k,m&&(this.#t.push(Ce(R,z=>{m(z,{source:"self"})})),e instanceof jt&&this.#t.push(Ce(e,z=>{m(z,{source:"iframe"})}))),this.#t.push(()=>o?.())}close=()=>{for(const e of this.#t)try{e()}catch(r){console.error("Device cleanup error:",r)}};async inspect(e,r){return await this.#r.request("appetizeio.device.server.inspect",{options:r,selector:e?nt(e):void 0})}async press(e){await this.#r.request("appetizeio.device.server.press",{action:e})}async rotate(e){return await this.#r.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(){const e=await this.#r.request("appetizeio.device.server.screenshot"),r=this.#e?new URL(e.url,this.#e).href:e.url,s=await fetch(r);if(!s.ok)throw new Error(`Screenshot download failed: ${String(s.status)} ${s.statusText}`);const n=s.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await s.arrayBuffer()),mimeType:n}}async swipe(e,r){await this.#r.request("appetizeio.device.server.swipe",{gesture:is(e),options:r})}async tap(e,r){await this.#r.request("appetizeio.device.server.tap",{options:r,selector:Le(e)})}async type(e,r){await this.#r.request("appetizeio.device.server.type",{options:r,steps:fs(e)})}}function bs(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const gs=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};function ms(t,e){const r=qt(t,e);return r===void 0?void 0:Jt(r,e)}function qt(t,e){if(t===void 0)return;const r=typeof t=="boolean"?Number.NaN:Number(t);if(!Number.isFinite(r))throw new Error(`${e} expects a number, e.g., ${e}=-0.1`);return r}function it(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new Error(`${e} needs a value`);return t}}function Jt(t,e){if(!(t>=0&&t<=1))throw new Error(`${e} expects a number between 0 and 1`);return t}function Es(t,e){const r=it(t,e);if(r===void 0)throw new Error(`${e} needs a value`);return r}function Ss(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function Wt(t){return it(t.endpoint,"--endpoint")??vs()}function vs(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const As="https://appetize.io";async function Ht(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const o=new URL(t,Wt(r)??As);for(const[y,v]of Object.entries(s))o.searchParams.set(y,v);const f=new Headers(n.headers);e&&f.set("x-api-key",Ss());const b=await fetch(o,{...n,headers:f});if(!b.ok)throw new Error(`The webserver rejected the request (${String(b.status)})`);return await b.json()}const Gt=["android","ios"];function Zt(t={}){return Ht("/api/v2/service/devices",{authorize:!1,commandOptions:t})}function ks(t){return Gt.includes(t)}async function Os(t,e={}){return(await Zt(e)).find(s=>s.id===t)?.platform}function ot(t){try{return process.kill(t,0),!0}catch{return!1}}function Is(t){let e={...t,updatedAt:new Date().toISOString()};return{path:lt(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},Ls(e),e)}}function Ms(){const t=Xt();return pt(t,{recursive:!0}),cr(t).map(e=>at(e)).filter(e=>e!==void 0)}function xs(t){if(t!==void 0){const r=at(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=Ms().filter(Us);if(e.length===0)throw new Error("No active sessions");if(e.length>1)throw new Error("Multiple active sessions; specify --session-id");return e[0]}function at(t){try{return JSON.parse(lr(lt(t),"utf8"))}catch{return}}function Rs(t){return te(ke(t),"control.sock")}function Yt(t){return te(ke(t),"daemon.log")}function Ts(t){return te(ke(t),"device.log.jsonl")}function Cs(t,e){return{daemon:Yt(t),device:Ts(t),...e==="intercept"?{network:Ps(t)}:void 0}}function Ps(t){return te(ke(t),"network.jsonl")}function ke(t){const e=te(Xt(),t);return pt(e,{recursive:!0}),e}function lt(t){return te(ke(t),"state.json")}function Xt(){return process.env.APPETIZE_CLI_HOME??te(fr(),".appetize","cli","sessions")}function Us(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:ot(t.pid)}function Ls(t){const e=lt(t.sessionId),r=`${e}.tmp`;or(r,`${JSON.stringify(t,null,2)}
2
- `),ar(r,e)}const ct="APPETIZE_DAEMON_CONFIG";function _s(){const t=process.env[ct];if(!t)throw new Error(`${ct} is not set`);return JSON.parse(t)}function Bs(t){return JSON.stringify(t)}const Ns=["SIGINT","SIGTERM"],Ds=150;function Fs(t){const e=new AbortController,r=setInterval(()=>{ot(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},Ds);return r.unref(),e.signal}function zs(){const t=new AbortController;for(const e of Ns)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function js(){"CloseEvent"in globalThis||(globalThis.CloseEvent=class 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}})}export{Qe as A,$t as B,Pe as C,ws as D,_s as E,Is as F,Os as G,tt as H,Rs as I,Bt as S,Ae as T,qt as a,Zt as b,Gt as c,Dr as d,Es as e,Ht as f,Yt as g,ct as h,ks as i,at as j,Wt as k,Cs as l,zs as m,ot as n,ms as o,it as p,Dt as q,Jt as r,Bs as s,xs as t,Fs as u,rt as v,js as w,Tr as x,T as y,kr as z};
1
+ import{Transform as Qt}from"stream";import{createRequire as er}from"module";import{connect as tr}from"node:net";import Be from"debug";import{JSONRPCServerAndClient as rr,JSONRPCServer as sr,JSONRPCClient as nr,JSONRPC as ir}from"json-rpc-2.0";import{writeFileSync as or,renameSync as ar,mkdirSync as pt,readFileSync as lr,readdirSync as cr}from"node:fs";import{homedir as fr}from"node:os";import{join as te}from"node:path";let Ne;try{Ne=new TextDecoder}catch{}let p,V,c=0;const De=[],ur=105,dr=57342,hr=57343,yt=57337,wt=6,fe={};let we=11281e4,Y=1681e4,re=De,be=0,O={},_,ge,me=0,se=0,B,q,N=[],Fe=[],K,j,Ee,bt={useRecords:!1,mapsAsObjects:!0},Se=!1,gt=2;try{new Function("")}catch{gt=1/0}class he{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[J(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(p)return Ot(()=>(Ke(),this?this.decode(e,r):he.prototype.decode.call(bt,e,r)));V=r>-1?r:e.length,c=0,be=0,se=0,ge=null,re=De,B=null,p=e;try{j=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(s){throw p=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 he){if(O=this,K=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return _=this.structures,Oe();(!_||_.length>0)&&(_=[])}else O=bt,(!_||_.length>0)&&(_=[]),K=null;return Oe()}decodeMultiple(e,r){let s,n=0;try{let o=e.length;Se=!0;let f=this?this.decode(e,o):qe.decode(e,o);if(r){if(r(f)===!1)return;for(;c<o;)if(n=c,r(Oe())===!1)return}else{for(s=[f];c<o;)n=c,s.push(Oe());return s}}catch(o){throw o.lastPosition=n,o.values=s,o}finally{Se=!1,Ke()}}}function Oe(){try{let t=I();if(B){if(c>=B.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}c=B.postBundlePosition,B=null}if(c==V)_=null,p=null,q&&(q=null);else if(c>V){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Se)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw Ke(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function ne(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function I(){if(!(c<V))throw ne();let t=p[c++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(c>=V)throw ne();t=p[c++];break;case 25:if(e==7)return br();t=j.getUint16(c),c+=2;break;case 26:if(e==7){let r=j.getFloat32(c);if(O.useFloat32>2){let s=$e[(p[c]&127)<<1|p[c+1]>>7];return c+=4,(s*r+(r>0?.5:-.5)>>0)/s}return c+=4,r}if(t=j.getUint32(c),c+=4,e===1)return-1-t;break;case 27:if(e==7){let r=j.getFloat64(c);return c+=8,r}if(e>1){if(j.getUint32(c)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=j.getUint32(c+4)}else O.int64AsNumber?(t=j.getUint32(c)*4294967296,t+=j.getUint32(c+4)):t=j.getBigUint64(c);c+=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=I())!=fe;){if(n>=we)throw new Error(`Array length exceeds ${we}`);r[n++]=s}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let o;if(O.mapsAsObjects){let f={},b=0;if(O.keyMap)for(;(o=I())!=fe;){if(b++>=Y)throw new Error(`Property count exceeds ${Y}`);f[J(O.decodeKey(o))]=I()}else for(;(o=I())!=fe;){if(b++>=Y)throw new Error(`Property count exceeds ${Y}`);f[J(o)]=I()}return f}else{Ee&&(O.mapsAsObjects=!0,Ee=!1);let f=new Map;if(O.keyMap){let b=0;for(;(o=I())!=fe;){if(b++>=Y)throw new Error(`Map size exceeds ${Y}`);f.set(O.decodeKey(o),I())}}else{let b=0;for(;(o=I())!=fe;){if(b++>=Y)throw new Error(`Map size exceeds ${Y}`);f.set(o,I())}}return f}case 7:return fe;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:return wr(t);case 3:if(se>=c)return ge.slice(c-me,(c+=t)-me);if(se==0&&V<140&&t<32){let n=t<16?St(t):yr(t);if(n!=null)return n}return Et(t);case 4:if(t>=we)throw new Error(`Array length exceeds ${we}`);if(t>V-c)throw ne();let r=new Array(t);for(let n=0;n<t;n++)r[n]=I();return r;case 5:if(t>=Y)throw new Error(`Map size exceeds ${we}`);if(t>(V-c)/2)throw ne();if(O.mapsAsObjects){let n={};if(O.keyMap)for(let o=0;o<t;o++)n[J(O.decodeKey(I()))]=I();else for(let o=0;o<t;o++)n[J(I())]=I();return n}else{Ee&&(O.mapsAsObjects=!0,Ee=!1);let n=new Map;if(O.keyMap)for(let o=0;o<t;o++)n.set(O.decodeKey(I()),I());else for(let o=0;o<t;o++)n.set(I(),I());return n}case 6:if(t>=yt){let n=_[t&8191];if(n)return n.read||(n.read=ze(n)),n.read();if(t<65536){if(t==hr){let o=de(),f=I(),b=I();je(f,b);let y={};if(O.keyMap)for(let v=2;v<o;v++){let m=O.decodeKey(b[v-2]);y[J(m)]=I()}else for(let v=2;v<o;v++){let m=b[v-2];y[J(m)]=I()}return y}else if(t==dr){let o=de(),f=I();for(let b=2;b<o;b++)je(f++,I());return I()}else if(t==yt)return Ar();if(O.getShared&&(Ve(),n=_[t&8191],n))return n.read||(n.read=ze(n)),n.read()}}let s=N[t];if(s)return s.handlesRead?s(I):s(I());{let n=I();for(let o=0;o<Fe.length;o++){let f=Fe[o](t,n);if(f!==void 0)return f}return new ie(n,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let n=(K||oe())[t];if(n!==void 0)return n;throw new Error("Unknown token "+t)}default:throw isNaN(t)?ne():new Error("Unknown CBOR token "+t)}}const mt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ze(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=p[c++];if(r=r&31,r>23)switch(r){case 24:r=p[c++];break;case 25:r=j.getUint16(c),c+=2;break;case 26:r=j.getUint32(c),c+=4;break;default:throw new Error("Expected array header, but got "+p[c-1])}let s=this.compiledReader;for(;s;){if(s.propertyCount===r)return s(I);s=s.next}if(this.slowReads++>=gt){let o=this.length==r?this:this.slice(0,r);return s=O.keyMap?new Function("r","return {"+o.map(f=>O.decodeKey(f)).map(f=>mt.test(f)?J(f)+":r()":"["+JSON.stringify(f)+"]:r()").join(",")+"}"):new Function("r","return {"+o.map(f=>mt.test(f)?J(f)+":r()":"["+JSON.stringify(f)+"]:r()").join(",")+"}"),this.compiledReader&&(s.next=this.compiledReader),s.propertyCount=r,this.compiledReader=s,s(I)}let n={};if(O.keyMap)for(let o=0;o<r;o++)n[J(O.decodeKey(this[o]))]=I();else for(let o=0;o<r;o++)n[J(this[o])]=I();return n}return t.slowReads=0,e}function J(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 Et=Ie;function pr(t){Et=e();function e(r){return function(n){let o=re[be++];if(o==null){if(B)return Ie(n);let b=t(c,V,n,p);if(typeof b=="string")o=b,re=De;else if(re=b,be=1,se=1,o=re[0],o===void 0)throw new Error("Unexpected end of buffer")}let f=o.length;return f<=n?(c+=n,o):(ge=o,me=c,se=c+f,c+=n,o.slice(0,n))}}}function Ie(t){let e;if(t<16&&(e=St(t)))return e;if(t>64&&Ne)return Ne.decode(p.subarray(c,c+=t));const r=c+t,s=[];for(e="";c<r;){const n=p[c++];if((n&128)===0)s.push(n);else if((n&224)===192)if(n<194||c>=r||(p[c]&192)!==128)s.push(65533);else{const o=p[c++]&63;s.push((n&31)<<6|o)}else if((n&240)===224){const o=c<r?p[c]:0;if(c>=r||(o&192)!==128||n===224&&o<160||n===237&&o>=160)s.push(65533);else if(c++,c>=r||(p[c]&192)!==128)s.push(65533);else{const f=p[c++]&63;s.push((n&31)<<12|(o&63)<<6|f)}}else if((n&248)===240){const o=c<r?p[c]:0;if(n>244||c>=r||(o&192)!==128||n===240&&o<144||n===244&&o>=144)s.push(65533);else if(c++,c>=r||(p[c]&192)!==128)s.push(65533);else{const f=p[c++]&63;if(c>=r||(p[c]&192)!==128)s.push(65533);else{const b=p[c++]&63;let y=(n&7)<<18|(o&63)<<12|f<<6|b;y-=65536,s.push(y>>>10&1023|55296),s.push(56320|y&1023)}}}else s.push(65533);s.length>=4096&&(e+=F.apply(String,s),s.length=0)}return s.length>0&&(e+=F.apply(String,s)),e}let F=String.fromCharCode;function yr(t){let e=c,r=new Array(t);for(let s=0;s<t;s++){const n=p[c++];if((n&128)>0){c=e;return}r[s]=n}return F.apply(String,r)}function St(t){if(t<4)if(t<2){if(t===0)return"";{let e=p[c++];if((e&128)>1){c-=1;return}return F(e)}}else{let e=p[c++],r=p[c++];if((e&128)>0||(r&128)>0){c-=2;return}if(t<3)return F(e,r);let s=p[c++];if((s&128)>0){c-=3;return}return F(e,r,s)}else{let e=p[c++],r=p[c++],s=p[c++],n=p[c++];if((e&128)>0||(r&128)>0||(s&128)>0||(n&128)>0){c-=4;return}if(t<6){if(t===4)return F(e,r,s,n);{let o=p[c++];if((o&128)>0){c-=5;return}return F(e,r,s,n,o)}}else if(t<8){let o=p[c++],f=p[c++];if((o&128)>0||(f&128)>0){c-=6;return}if(t<7)return F(e,r,s,n,o,f);let b=p[c++];if((b&128)>0){c-=7;return}return F(e,r,s,n,o,f,b)}else{let o=p[c++],f=p[c++],b=p[c++],y=p[c++];if((o&128)>0||(f&128)>0||(b&128)>0||(y&128)>0){c-=8;return}if(t<10){if(t===8)return F(e,r,s,n,o,f,b,y);{let v=p[c++];if((v&128)>0){c-=9;return}return F(e,r,s,n,o,f,b,y,v)}}else if(t<12){let v=p[c++],m=p[c++];if((v&128)>0||(m&128)>0){c-=10;return}if(t<11)return F(e,r,s,n,o,f,b,y,v,m);let x=p[c++];if((x&128)>0){c-=11;return}return F(e,r,s,n,o,f,b,y,v,m,x)}else{let v=p[c++],m=p[c++],x=p[c++],R=p[c++];if((v&128)>0||(m&128)>0||(x&128)>0||(R&128)>0){c-=12;return}if(t<14){if(t===12)return F(e,r,s,n,o,f,b,y,v,m,x,R);{let L=p[c++];if((L&128)>0){c-=13;return}return F(e,r,s,n,o,f,b,y,v,m,x,R,L)}}else{let L=p[c++],U=p[c++];if((L&128)>0||(U&128)>0){c-=14;return}if(t<15)return F(e,r,s,n,o,f,b,y,v,m,x,R,L,U);let C=p[c++];if((C&128)>0){c-=15;return}return F(e,r,s,n,o,f,b,y,v,m,x,R,L,U,C)}}}}}function wr(t){return O.copyBuffers?Uint8Array.prototype.slice.call(p,c,c+=t):p.subarray(c,c+=t)}let vt=new Float32Array(1),Me=new Uint8Array(vt.buffer,0,4);function br(){let t=p[c++],e=p[c++],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 Me[3]=t&128|(r>>1)+56,Me[2]=(t&7)<<5|e>>3,Me[1]=e<<5,Me[0]=0,vt[0]}new Array(4096);class ie{constructor(e,r){this.value=e,this.tag=r}}N[0]=t=>new Date(t),N[1]=t=>new Date(Math.round(t*1e3)),N[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},N[3]=t=>BigInt(-1)-N[2](t),N[4]=t=>+(t[1]+"e"+t[0]),N[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const je=(t,e)=>{t=t-57344;let r=_[t];r&&r.isShared&&((_.restoreStructures||(_.restoreStructures=[]))[t]=r),_[t]=e,e.read=ze(e)};N[ur]=t=>{let e=t.length,r=t[1];je(t[0],r);let s={};for(let n=2;n<e;n++){let o=r[n-2];s[J(o)]=t[n]}return s},N[14]=t=>B?B[0].slice(B.position0,B.position0+=t):new ie(t,14),N[15]=t=>B?B[1].slice(B.position1,B.position1+=t):new ie(t,15);let gr={Error,RegExp};N[27]=t=>(gr[t[0]]||Error)(t[1],t[2]);const At=t=>{if(p[c++]!=132){let r=new Error("Packed values structure must be followed by a 4 element array");throw p.length<c&&(r.incomplete=!0),r}let e=t();if(!e||!e.length){let r=new Error("Packed values structure must be followed by a 4 element array");throw r.incomplete=!0,r}return K=K?e.concat(K.slice(e.length)):e,K.prefixes=t(),K.suffixes=t(),t()};At.handlesRead=!0,N[51]=At,N[wt]=t=>{if(!K)if(O.getShared)Ve();else return new ie(t,wt);if(typeof t=="number")return K[16+(t>=0?2*t:-2*t-1)];let e=new Error("No support for non-integer packed references yet");throw t===void 0&&(e.incomplete=!0),e},N[28]=t=>{q||(q=new Map,q.id=0);let e=q.id++,r=c,s=p[c],n;s>>5==4?n=[]:n={};let o={target:n};q.set(e,o);let f=t();return o.used?(Object.getPrototypeOf(n)!==Object.getPrototypeOf(f)&&(c=r,n=f,q.set(e,{target:n}),f=t()),Object.assign(n,f)):(o.target=f,f)},N[28].handlesRead=!0,N[29]=t=>{let e=q.get(t);return e.used=!0,e.target},N[258]=t=>new Set(t),(N[259]=t=>(O.mapsAsObjects&&(O.mapsAsObjects=!1,Ee=!0),t())).handlesRead=!0;function ue(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function oe(){if(!K)if(O.getShared)Ve();else throw new Error("No packed values available");return K}const mr=1399353956;Fe.push((t,e)=>{if(t>=225&&t<=255)return ue(oe().prefixes[t-224],e);if(t>=28704&&t<=32767)return ue(oe().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return ue(oe().prefixes[t-1879048192],e);if(t>=216&&t<=223)return ue(e,oe().suffixes[t-216]);if(t>=27647&&t<=28671)return ue(e,oe().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return ue(e,oe().suffixes[t-1811939328]);if(t==mr)return{packedValues:K,structures:_.slice(0),version:e};if(t==55799)return e});const Er=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,kt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],Sr=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<kt.length;t++)vr(kt[t],Sr[t]);function vr(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 o=s==2?1:s==4?2:s==8?3:0;N[n?e:e-4]=s==1||n==Er?f=>{if(!t)throw new Error("Could not find typed array for code "+e);return!O.copyBuffers&&(s===1||s===2&&!(f.byteOffset&1)||s===4&&!(f.byteOffset&3)||s===8&&!(f.byteOffset&7))?new t(f.buffer,f.byteOffset,f.byteLength>>o):new t(Uint8Array.prototype.slice.call(f,0).buffer)}:f=>{if(!t)throw new Error("Could not find typed array for code "+e);let b=new DataView(f.buffer,f.byteOffset,f.byteLength),y=f.length>>o,v=new t(y),m=b[r];for(let x=0;x<y;x++)v[x]=m.call(b,x<<o,n);return v}}}function Ar(){let t=de(),e=c+I();for(let s=2;s<t;s++){let n=de();c+=n}let r=c;return c=e,B=[Ie(de()),Ie(de())],B.position0=0,B.position1=0,B.postBundlePosition=c,c=r,I()}function de(){if(!(c<V))throw ne();let t=p[c++]&31;if(t>23)switch(t){case 24:if(c>=V)throw ne();t=p[c++];break;case 25:t=j.getUint16(c),c+=2;break;case 26:t=j.getUint32(c),c+=4;break}return t}function Ve(){if(O.getShared){let t=Ot(()=>(p=null,O.getShared()))||{},e=t.structures||[];O.sharedVersion=t.version,K=O.sharedValues=t.packedValues,_===!0?O.structures=_=e:_.splice.apply(_,[0,e.length].concat(e))}}function Ot(t){let e=V,r=c,s=be,n=me,o=se,f=ge,b=re,y=q,v=B,m=new Uint8Array(p.slice(0,V)),x=_,R=O,L=Se,U=t();return V=e,c=r,be=s,me=n,se=o,ge=f,re=b,q=y,B=v,p=m,Se=L,_=x,O=R,j=new DataView(p.buffer,p.byteOffset,p.byteLength),U}function Ke(){p=null,q=null,_=null}const $e=new Array(147);for(let t=0;t<256;t++)$e[t]=+("1e"+Math.floor(45.15-t*.30103));let qe=new he({useRecords:!1});const kr=qe.decode;qe.decodeMultiple;let xe;try{xe=new TextEncoder}catch{}let Je,It;const Re=typeof globalThis=="object"&&globalThis.Buffer,ve=typeof Re<"u",We=ve?Re.allocUnsafeSlow:Uint8Array,Mt=ve?Re:Uint8Array,xt=256,Rt=ve?4294967296:2144337920;let Ge,l,P,i=0,Q,D=null;const Or=61440,Ir=/[\u0080-\uFFFF]/,$=Symbol("record-id");class Tt extends he{constructor(e){super(e),this.offset=0;let r,s,n,o,f;e=e||{};let b=Mt.prototype.utf8Write?function(a,w){return l.utf8Write(a,w,l.byteLength-w)}:xe&&xe.encodeInto?function(a,w){return xe.encodeInto(a,l.subarray(w)).written}:!1,y=this,v=e.structures||e.saveStructures,m=e.maxSharedStructures;if(m==null&&(m=v?128:0),m>8190)throw new Error("Maximum maxSharedStructure is 8190");let x=e.sequential;x&&(m=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let R,L,U=e.sharedValues,C;if(U){C=Object.create(null);for(let a=0,w=U.length;a<w;a++)C[U[a]]=a}let W=[],pe=0,G=0;this.mapEncode=function(a,w){return this._keyMap&&!this._mapped&&a.constructor.name==="Array"&&(a=a.map(d=>this.encodeKeys(d))),this.encode(a,w)},this.encode=function(a,w){if(l||(l=new We(8192),P=new DataView(l.buffer,0,8192),i=0),Q=l.length-10,Q-i<2048?(l=new We(l.length),P=new DataView(l.buffer,0,l.length),Q=l.length-10,i=0):w===Lt&&(i=i+7&2147483640),r=i,y.useSelfDescribedHeader&&(P.setUint32(i,3654940416),i+=3),f=y.structuredClone?new Map:null,y.bundleStrings&&typeof a!="string"?(D=[],D.size=1/0):D=null,s=y.structures,s){if(s.uninitialized){let h=y.getShared()||{};y.structures=s=h.structures||[],y.sharedVersion=h.version;let u=y.sharedValues=h.packedValues;if(u){C={};for(let g=0,E=u.length;g<E;g++)C[u[g]]=g}}let d=s.length;if(d>m&&!x&&(d=m),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let g,E=s.transitions;for(let S=0,A=u.length;S<A;S++){E[$]===void 0&&(E[$]=h);let M=u[S];g=E[M],g||(g=E[M]=Object.create(null)),E=g}E[$]=h|1048576}}x||(s.nextId=d)}if(n&&(n=!1),o=s||[],L=C,e.pack){let d=new Map;if(d.values=[],d.encoder=y,d.maxValues=e.maxPrivatePackedValues||(C?16:1/0),d.objectMap=C||!1,d.samplingPackedValues=R,Te(a,d),d.values.length>0){l[i++]=216,l[i++]=51,H(4);let h=d.values;k(h),H(0),H(0),L=Object.create(C||null);for(let u=0,g=h.length;u<g;u++)L[h[u]]=u}}Ge=w&Xe;try{if(Ge)return;if(k(a),D&&Ut(r,k),y.offset=i,f&&f.idsToInsert){i+=f.idsToInsert.length*2,i>Q&&le(i),y.offset=i;let d=Rr(l.subarray(r,i),f.idsToInsert);return f=null,d}return w&Lt?(l.start=r,l.end=i,l):l.subarray(r,i)}finally{if(s){if(G<10&&G++,s.length>m&&(s.length=m),pe>1e4)s.transitions=null,G=0,pe=0,W.length>0&&(W=[]);else if(W.length>0&&!x){for(let d=0,h=W.length;d<h;d++)W[d][$]=void 0;W=[]}}if(n&&y.saveShared){y.structures.length>m&&(y.structures=y.structures.slice(0,m));let d=l.subarray(r,i);return y.updateSharedData()===!1?y.encode(a):d}w&Pr&&(i=r)}},this.findCommonStringsToPack=()=>(R=new Map,C||(C=Object.create(null)),a=>{let w=a&&a.threshold||4,d=this.pack?a.maxPrivatePackedValues||16:0;U||(U=this.sharedValues=[]);for(let[h,u]of R)u.count>w&&(C[h]=d++,U.push(h),n=!0);for(;this.saveShared&&this.updateSharedData()===!1;);R=null});const k=a=>{i>Q&&(l=le(i));var w=typeof a,d;if(w==="string"){if(L){let E=L[a];if(E>=0){E<16?l[i++]=E+224:(l[i++]=198,E&1?k(15-E>>1):k(E-16>>1));return}else if(R&&!e.pack){let S=R.get(a);S?S.count++:R.set(a,{count:1})}}let h=a.length;if(D&&h>=4&&h<1024){if((D.size+=h)>Or){let S,A=(D[0]?D[0].length*3+D[1].length:0)+10;i+A>Q&&(l=le(i+A)),l[i++]=217,l[i++]=223,l[i++]=249,l[i++]=D.position?132:130,l[i++]=26,S=i-r,i+=4,D.position&&Ut(r,k),D=["",""],D.size=0,D.position=S}let E=Ir.test(a);D[E?0:1]+=a,l[i++]=E?206:207,k(h);return}let u;h<32?u=1:h<256?u=2:h<65536?u=3:u=5;let g=h*3;if(i+g>Q&&(l=le(i+g)),h<64||!b){let E,S,A,M=i+u;for(E=0;E<h;E++)S=a.charCodeAt(E),S<128?l[M++]=S:S<2048?(l[M++]=S>>6|192,l[M++]=S&63|128):(S&64512)===55296&&((A=a.charCodeAt(E+1))&64512)===56320?(S=65536+((S&1023)<<10)+(A&1023),E++,l[M++]=S>>18|240,l[M++]=S>>12&63|128,l[M++]=S>>6&63|128,l[M++]=S&63|128):(l[M++]=S>>12|224,l[M++]=S>>6&63|128,l[M++]=S&63|128);d=M-i-u}else d=b(a,i+u,g);d<24?l[i++]=96|d:d<256?(u<2&&l.copyWithin(i+2,i+1,i+1+d),l[i++]=120,l[i++]=d):d<65536?(u<3&&l.copyWithin(i+3,i+2,i+2+d),l[i++]=121,l[i++]=d>>8,l[i++]=d&255):(u<5&&l.copyWithin(i+5,i+3,i+3+d),l[i++]=122,P.setUint32(i,d),i+=4),i+=d}else if(w==="number")if(!this.alwaysUseFloat&&a>>>0===a)a<24?l[i++]=a:a<256?(l[i++]=24,l[i++]=a):a<65536?(l[i++]=25,l[i++]=a>>8,l[i++]=a&255):(l[i++]=26,P.setUint32(i,a),i+=4);else if(!this.alwaysUseFloat&&a>>0===a)a>=-24?l[i++]=31-a:a>=-256?(l[i++]=56,l[i++]=~a):a>=-65536?(l[i++]=57,P.setUint16(i,~a),i+=2):(l[i++]=58,P.setUint32(i,~a),i+=4);else if(!this.alwaysUseFloat&&a<0&&a>=-4294967296&&Math.floor(a)===a)l[i++]=58,P.setUint32(i,-1-a),i+=4;else{let h;if((h=this.useFloat32)>0&&a<4294967296&&a>=-2147483648){l[i++]=250,P.setFloat32(i,a);let u;if(h<4||(u=a*$e[(l[i]&127)<<1|l[i+1]>>7])>>0===u){i+=4;return}else i--}l[i++]=251,P.setFloat64(i,a),i+=8}else if(w==="object")if(!a)l[i++]=246;else{if(f){let u=f.get(a);if(u){if(l[i++]=216,l[i++]=29,l[i++]=25,!u.references){let g=f.idsToInsert||(f.idsToInsert=[]);u.references=[],g.push(u)}u.references.push(i-r),i+=2;return}else f.set(a,{offset:i-r})}let h=a.constructor;if(h===Object)this.skipFunction===!0&&(a=Object.fromEntries([...Object.keys(a).filter(u=>typeof a[u]!="function").map(u=>[u,a[u]])])),z(a);else if(h===Array){d=a.length,d<24?l[i++]=128|d:H(d);for(let u=0;u<d;u++)k(a[u])}else if(h===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(l[i++]=217,l[i++]=1,l[i++]=3),d=a.size,d<24?l[i++]=160|d:d<256?(l[i++]=184,l[i++]=d):d<65536?(l[i++]=185,l[i++]=d>>8,l[i++]=d&255):(l[i++]=186,P.setUint32(i,d),i+=4),y.keyMap)for(let[u,g]of a)k(y.encodeKey(u)),k(g);else for(let[u,g]of a)k(u),k(g);else{for(let u=0,g=Je.length;u<g;u++){let E=It[u];if(a instanceof E){let S=Je[u],A=S.tag;A==null&&(A=S.getTag&&S.getTag.call(this,a)),A<24?l[i++]=192|A:A<256?(l[i++]=216,l[i++]=A):A<65536?(l[i++]=217,l[i++]=A>>8,l[i++]=A&255):A>-1&&(l[i++]=218,P.setUint32(i,A),i+=4),S.encode.call(this,a,k,le);return}}if(a[Symbol.iterator]){if(Ge){let u=new Error("Iterable should be serialized as iterator");throw u.iteratorNotHandled=!0,u}l[i++]=159;for(let u of a)k(u);l[i++]=255;return}if(a[Symbol.asyncIterator]||He(a)){let u=new Error("Iterable/blob should be serialized as iterator");throw u.iteratorNotHandled=!0,u}if(this.useToJSON&&a.toJSON){const u=a.toJSON();if(u!==a)return k(u)}z(a)}}else if(w==="boolean")l[i++]=a?245:244;else if(w==="bigint"){if(a<BigInt(1)<<BigInt(64)&&a>=0)l[i++]=27,P.setBigUint64(i,a);else if(a>-(BigInt(1)<<BigInt(64))&&a<0)l[i++]=59,P.setBigUint64(i,-a-BigInt(1));else if(this.largeBigIntToFloat)l[i++]=251,P.setFloat64(i,Number(a));else{a>=BigInt(0)?l[i++]=194:(l[i++]=195,a=BigInt(-1)-a);let h=[];for(;a;)h.push(Number(a&BigInt(255))),a>>=BigInt(8);Ze(new Uint8Array(h.reverse()),le);return}i+=8}else if(w==="undefined")l[i++]=247;else throw new Error("Unknown type: "+w)},z=this.useRecords===!1?this.variableMapSize?a=>{let w=Object.keys(a),d=Object.values(a),h=w.length;if(h<24?l[i++]=160|h:h<256?(l[i++]=184,l[i++]=h):h<65536?(l[i++]=185,l[i++]=h>>8,l[i++]=h&255):(l[i++]=186,P.setUint32(i,h),i+=4),y.keyMap)for(let u=0;u<h;u++)k(y.encodeKey(w[u])),k(d[u]);else for(let u=0;u<h;u++)k(w[u]),k(d[u])}:a=>{l[i++]=185;let w=i-r;i+=2;let d=0;if(y.keyMap)for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(k(y.encodeKey(h)),k(a[h]),d++);else for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(k(h),k(a[h]),d++);l[w+++r]=d>>8,l[w+r]=d&255}:(a,w)=>{let d,h=o.transitions||(o.transitions=Object.create(null)),u=0,g=0,E,S;if(this.keyMap){S=Object.keys(a).map(M=>this.encodeKey(M)),g=S.length;for(let M=0;M<g;M++){let ht=S[M];d=h[ht],d||(d=h[ht]=Object.create(null),u++),h=d}}else for(let M in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(M))&&(d=h[M],d||(h[$]&1048576&&(E=h[$]&65535),d=h[M]=Object.create(null),u++),h=d,g++);let A=h[$];if(A!==void 0)A&=65535,l[i++]=217,l[i++]=A>>8|224,l[i++]=A&255;else if(S||(S=h.__keys__||(h.__keys__=Object.keys(a))),E===void 0?(A=o.nextId++,A||(A=0,o.nextId=1),A>=xt&&(o.nextId=(A=m)+1)):A=E,o[A]=S,A<m){l[i++]=217,l[i++]=A>>8|224,l[i++]=A&255,h=o.transitions;for(let M=0;M<g;M++)(h[$]===void 0||h[$]&1048576)&&(h[$]=A),h=h[S[M]];h[$]=A|1048576,n=!0}else{if(h[$]=A,P.setUint32(i,3655335680),i+=3,u&&(pe+=G*u),W.length>=xt-m&&(W.shift()[$]=void 0),W.push(h),H(g+2),k(57344+A),k(S),w)return;for(let M in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(M))&&k(a[M]);return}if(g<24?l[i++]=128|g:H(g),!w)for(let M in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(M))&&k(a[M])},le=a=>{let w;if(a>16777216){if(a-r>Rt)throw new Error("Encoded buffer would be larger than maximum buffer size");w=Math.min(Rt,Math.round(Math.max((a-r)*(a>67108864?1.25:2),4194304)/4096)*4096)}else w=(Math.max(a-r<<2,l.length-1)>>12)+1<<12;let d=new We(w);return P=new DataView(d.buffer,0,w),l.copy?l.copy(d,0,r,a):d.set(l.slice(r,a)),i-=r,r=0,Q=d.length-10,l=d};let ee=100,ft=1e3;this.encodeAsIterable=function(a,w){return ut(a,w,ce)},this.encodeAsAsyncIterable=function(a,w){return ut(a,w,dt)};function*ce(a,w,d){let h=a.constructor;if(h===Object){let u=y.useRecords!==!1;u?z(a,!0):Pt(Object.keys(a).length,160);for(let g in a){let E=a[g];u||k(g),E&&typeof E=="object"?w[g]?yield*ce(E,w[g]):yield*_e(E,w,g):k(E)}}else if(h===Array){let u=a.length;H(u);for(let g=0;g<u;g++){let E=a[g];E&&(typeof E=="object"||i-r>ee)?w.element?yield*ce(E,w.element):yield*_e(E,w,"element"):k(E)}}else if(a[Symbol.iterator]&&!a.buffer){l[i++]=159;for(let u of a)u&&(typeof u=="object"||i-r>ee)?w.element?yield*ce(u,w.element):yield*_e(u,w,"element"):k(u);l[i++]=255}else He(a)?(Pt(a.size,64),yield l.subarray(r,i),yield a,ye()):a[Symbol.asyncIterator]?(l[i++]=159,yield l.subarray(r,i),yield a,ye(),l[i++]=255):k(a);d&&i>r?yield l.subarray(r,i):i-r>ee&&(yield l.subarray(r,i),ye())}function*_e(a,w,d){let h=i-r;try{k(a),i-r>ee&&(yield l.subarray(r,i),ye())}catch(u){if(u.iteratorNotHandled)w[d]={},i=r+h,yield*ce.call(this,a,w[d]);else throw u}}function ye(){ee=ft,y.encode(null,Xe)}function ut(a,w,d){return w&&w.chunkThreshold?ee=ft=w.chunkThreshold:ee=100,a&&typeof a=="object"?(y.encode(null,Xe),d(a,y.iterateProperties||(y.iterateProperties={}),!0)):[y.encode(a)]}async function*dt(a,w){for(let d of ce(a,w,!0)){let h=d.constructor;if(h===Mt||h===Uint8Array)yield d;else if(He(d)){let u=d.stream().getReader(),g;for(;!(g=await u.read()).done;)yield g.value}else if(d[Symbol.asyncIterator])for await(let u of d)ye(),u?yield*dt(u,w.async||(w.async={})):yield y.encode(u);else yield d}}}useBuffer(e){l=e,P=new DataView(l.buffer,l.byteOffset,l.byteLength),i=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 Ct(r,this.sharedValues,this.sharedVersion),n=this.saveShared(s,o=>(o&&o.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((o,f)=>this.structures[f]=o),n}}function Pt(t,e){t<24?l[i++]=e|t:t<256?(l[i++]=e|24,l[i++]=t):t<65536?(l[i++]=e|25,l[i++]=t>>8,l[i++]=t&255):(l[i++]=e|26,P.setUint32(i,t),i+=4)}class Ct{constructor(e,r,s){this.structures=e,this.packedValues=r,this.version=s}}function H(t){t<24?l[i++]=128|t:t<256?(l[i++]=152,l[i++]=t):t<65536?(l[i++]=153,l[i++]=t>>8,l[i++]=t&255):(l[i++]=154,P.setUint32(i,t),i+=4)}const Mr=typeof Blob>"u"?function(){}:Blob;function He(t){if(t instanceof Mr)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function Te(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++)Te(t[s],e);else{let s=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(s&&Te(r,e),Te(t[r],e))}break;case"function":console.log(t)}}const xr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;It=[Date,Set,Error,RegExp,ie,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,Ct],Je=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(l[i++]=26,P.setUint32(i,r),i+=4):(l[i++]=251,P.setFloat64(i,r),i+=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){Ze(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||ve&&this.tagUint8Array!==!1))return 64},encode(t,e,r){Ze(t,r)}},Z(68,1),Z(69,2),Z(70,4),Z(71,8),Z(72,1),Z(77,2),Z(78,4),Z(79,8),Z(85,4),Z(86,8),{encode(t,e){let r=t.packedValues||[],s=t.structures||[];if(r.values.length>0){l[i++]=216,l[i++]=51,H(4);let n=r.values;e(n),H(0),H(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let o=0,f=n.length;o<f;o++)packedObjectMap[n[o]]=o}if(s){P.setUint32(i,3655335424),i+=3;let n=s.slice(0);n.unshift(57344),n.push(new ie(t.version,1399353956)),e(n)}else e(new ie(t.version,1399353956))}}];function Z(t,e){return!xr&&e>1&&(t-=4),{tag:t,encode:function(s,n){let o=s.byteLength,f=s.byteOffset||0,b=s.buffer||s;n(ve?Re.from(b,f,o):new Uint8Array(b,f,o))}}}function Ze(t,e){let r=t.byteLength;r<24?l[i++]=64+r:r<256?(l[i++]=88,l[i++]=r):r<65536?(l[i++]=89,l[i++]=r>>8,l[i++]=r&255):(l[i++]=90,P.setUint32(i,r),i+=4),i+r>=l.length&&e(i+r),l.set(t.buffer?t:new Uint8Array(t),i),i+=r}function Rr(t,e){let r,s=e.length*2,n=t.length-s;e.sort((o,f)=>o.offset>f.offset?1:-1);for(let o=0;o<e.length;o++){let f=e[o];f.id=o;for(let b of f.references)t[b++]=o>>8,t[b]=o&255}for(;r=e.pop();){let o=r.offset;t.copyWithin(o+s,o,n),s-=2;let f=o+s;t[f++]=216,t[f++]=28,n=o}return t}function Ut(t,e){P.setUint32(D.position+t,i-D.position-t+1);let r=D;D=null,e(r[0]),e(r[1])}let Ye=new Tt({useRecords:!1});const Tr=Ye.encode;Ye.encodeAsIterable,Ye.encodeAsAsyncIterable;const Lt=512,Pr=1024,Xe=2048;class Cr extends Qt{constructor(e){e||(e={}),e.objectMode=!0,super(e),e.structures=[],this.decoder=e.decoder||new he(e)}_transform(e,r,s){this.incompleteBuffer&&(e=Buffer.concat([this.incompleteBuffer,e]),this.incompleteBuffer=null);let n;try{n=this.decoder.decodeMultiple(e)}catch(o){if(o.incomplete)this.incompleteBuffer=e.slice(o.lastPosition),n=o.values;else return s(o)}finally{for(let o of n||[])o===null&&(o=this.getNullValue()),this.push(o)}s()}getNullValue(){return Symbol.for(null)}}const Ur=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!Ur){let t;try{typeof require=="function"?t=require("cbor-extract"):t=er(import.meta.url)("cbor-extract"),t&&pr(t.extractStrings)}catch{}}class Lr{#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 T=Symbol.for("@appetizeio/rpc:rpcMethods");class _r extends Lr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(new CloseEvent("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}function Qe(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}function Br(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}class Ae{closed=!1;[T];#e;constructor(e,{signal:r}={}){this[T]=new _r(e),this.#e=r,this.#e?.addEventListener("abort",this.#t)}close(e={}){this.closed||(this.closed=!0,this.handleClose(e))}handleClose(e){this.#e?.removeEventListener("abort",this.#t),this[T].dispatchClose(e)}#t=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const _t={useRecords:!1},Nr=new Tt(_t);class Bt extends Ae{#e=[];#t;constructor(e,{signal:r}={}){super(async f=>{this.#t.write(Nr.encode(f))},{signal:r}),this.#t=e;const s=new Cr(_t);s.on("data",f=>{Qe(f)&&this[T].dispatchMessage(f)}),s.on("error",()=>{this.close()});const n=f=>{s.write(f)},o=()=>{this.close()};e.on("data",n),e.once("close",o),e.once("error",o),this.#e.push(()=>{e.off("data",n),e.off("close",o),e.off("error",o),s.destroy()})}handleClose(e){for(const r of this.#e.splice(0))r();super.handleClose(e)}}function Dr(t,e){const{promise:r,reject:s,resolve:n}=Br(),o=tr(t),f=e?.signal,b=()=>{o.off("connect",m),o.off("error",x),f?.removeEventListener("abort",v)},y=R=>{b(),o.destroy(),s(R)},v=()=>{y(new Error("The connection was aborted"))},m=()=>{b();const R=new Bt(o,e);R[T].addEventListener("close",()=>{o.destroy()},{once:!0}),n(R)},x=R=>{y(R)};return f?.aborted?(y(new Error("The connection was aborted")),r):(o.once("connect",m),o.once("error",x),f?.addEventListener("abort",v,{once:!0}),r)}const Nt=Be("appetize.io:error:rpc");function et(t,e){const r=new rr(new sr({errorListener:Nt}),Fr(t),{errorListener:Nt}),s=t[T].addEventListener("message",({detail:o})=>{r.receiveAndSend(o)}),n=t[T].addEventListener("close",()=>{s(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const o in e){const f=e[o];f&&r.addMethod(o,f.bind(e))}return{rpc:r,unsub:()=>{s(),n()}}}function Dt(t,e){const{rpc:r,unsub:s}=et(t,e);return{client:r.client,unsub:s}}function Pe(t,e){const r=t[T].addEventListener("message",({detail:n})=>{if("method"in n)try{e({method:n.method,param:n.params})}catch{}}),s=t[T].addEventListener("close",r,{once:!0});return()=>{r(),s()}}function Fr(t){return new nr(t[T].send.bind(t[T]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function tt(t,e,{leftEffects:r=()=>({}),notifiesLeft:s,notifiesRight:n,rightEffects:o=()=>({})}={}){const f=et(t,{}),b=et(e,{}),y=[()=>{f.unsub(),b.unsub()}],v=()=>{for(const U of y)try{U()}catch{}},m=b.rpc.client,x=f.rpc.client;y.push(t[T].addEventListener("close",()=>{v()},{once:!0}),e[T].addEventListener("close",()=>{v()},{once:!0}));const R=r(m,x);for(const U in R){const C=R[U];C&&f.rpc.addMethod(U,C)}const L=o(x,m);for(const U in L){const C=L[U];C&&b.rpc.addMethod(U,C)}return Ft(f.rpc,b.rpc,{notifies:s}),Ft(b.rpc,f.rpc,{notifies:n}),v}function Ft(t,e,{notifies:r}={}){t.applyServerMiddleware(async(s,n)=>{const o=r?.();if(o){const{id:b,...y}=n;o[T].send(y)}if(t.hasMethod(n.method))return await s(n);if(!n.id)return e.notify(n.method,n.params),null;const f=await e.request(n.method,n.params);return{id:n.id,jsonrpc:ir,result:f}})}function X(t,...e){t.notify(e[0],e[1],e[2])}const zr=(...t)=>Dt(...t),rt=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"];function st(){const t=new Ae(async r=>{e[T].dispatchMessage(r)}),e=new Ae(async r=>{t[T].dispatchMessage(r)});return t[T].addEventListener("close",()=>{e.close()},{once:!0}),e[T].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function zt(t,e){const r=[],s=()=>{for(const n of r)n()};r.push(t[T].addEventListener("message",n=>e[T].send(n.detail))),r.push(t[T].addEventListener("close",s,{once:!0})),r.push(e[T].addEventListener("message",n=>t[T].send(n.detail))),r.push(e[T].addEventListener("close",s,{once:!0}))}const ae=Be("appetize.io:trace:transport:iframe");class jt extends Ae{onmessage;#e;#t;constructor(e,{origin:r="*",signal:s}={}){super(async n=>{e.postMessage(n,this.#e)},{signal:s}),this.#t=e,this.#e=r,window.addEventListener("message",this.#r)}postMessage(e,r,s){ae("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#t.postMessage(e,r??this.#e,s)}handleClose(e){ae("close()"),window.removeEventListener("message",this.#r),super.handleClose(e)}#r=async e=>{if(ae("handleMessage()",e),e.source!==this.#t||(ae("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ae("handleMessage() -> origin ok");const r=e.data;if(!Qe(r)){ae("handleMessage() -> legacy"),this.onmessage?.(e);return}ae("handleMessage() -> jsonrpc"),this[T].dispatchMessage(r)}}function Ce(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const jr=2*1024*1024,Vt=Be("appetize:client:acked-writable-stream");class Vr{unacked=0;#e;#t;#r;#s;#n=[];#i;constructor(e){this.#r=e,this.#i=e.window??jr}abort(e){this.#a(e),this.#r.onAbort?.(e)}async close(){await this.#l(()=>this.unacked===0),this.#r.onClose?.()}fail(e){this.#a(e)&&this.#r.onError?.(e)}start(e){this.#e=e}write(e){const r=e.byteLength;return this.unacked+=r,this.#r.send(e).then(()=>{this.unacked-=r,this.#s&&(this.#s.acked+=r),this.#o()},s=>{this.fail(s)}),this.unacked>=this.#i&&!this.#s&&(this.#s={acked:0,at:performance.now()},Vt("window full: %d bytes unacked, writes stalled",this.unacked)),this.#l(()=>this.unacked<this.#i)}#o(){if(this.#s&&this.unacked<=this.#i/2){const e=performance.now()-this.#s.at;Vt("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)}#a(e){if(this.#t)return!1;this.#t={reason:e},this.#e.error(e);const r=this.#n;this.#n=[];for(const s of r)s.reject(e);return!0}#l(e){if(e())return Promise.resolve();const r={...Ce(),until:e};return this.#n.push(r),r.promise}}class Kr extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new Vr(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 $r=1024*1024;class qr{#e;#t=!1;#r;#s;constructor(e){this.#r=e}cancel(e){this.#n(),this.#r?.(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.#t)return;this.#s??=Ce();const{promise:r}=this.#s;this.#e.enqueue(e),await r}start(e){this.#e=e}#n(){return this.#t?!1:(this.#t=!0,this.pull(),!0)}}class Jr extends ReadableStream{#e;constructor({highWaterMark:e=$r,onCancel:r}={}){const s=new qr(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 Wr{closed;readable;writable;#e=[];#t;#r;#s;#n;#i;#o="starting";constructor(e,{onClose:r,receiveBuffer:s,sendWindow:n,signal:o}){if(this.#i=e,this.#t=Ce(),this.closed=this.#t.promise,this.closed.catch(Gr),this.#s=new Jr({highWaterMark:s,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#s,this.#n=new Kr({onAbort:()=>{this.#a(void 0)},onClose:()=>{this.#a(void 0)},onError:f=>{this.#a(f)},send:f=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:f}),window:n}),this.writable=this.#n,o){const f=()=>{this.#a(o.reason)};o.addEventListener("abort",f,{once:!0}),this.#e.push(()=>{o.removeEventListener("abort",f)})}this.#e.push(()=>{r(this)})}close=()=>{this.#a(void 0)};detach(){this.#a(void 0,{notifyServer:!1})}async handleData(e){this.#o==="open"&&await this.#s.push(e)}handleStopped({error:e}){this.#o==="open"&&this.#a(e?new Error(e):void 0)}async start(){try{await this.#i.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#a(e),e}if(this.#o==="closed")throw this.#r?this.#r:new Error("The adb tunnel closed before it started");this.#o="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#a(e,{notifyServer:r=!0}={}){if(this.#o!=="closed"){this.#o="closed",this.#r=e,r&&X(this.#i,"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.#t.reject(e):this.#t.resolve(void 0)}}}function Gr(){}class Hr{readable;ready;#e=[];#t=!1;#r;#s;#n;constructor({label:e,onClose:r,signal:s}){this.#s=e,this.ready=new Promise((o,f)=>{this.#n={reject:f,resolve:o}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#o()},start:o=>{n=o}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#r=n,s){const o=()=>{this.fail(s.reason)};s.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",o)})}this.#e.push(()=>{r(this)})}close=()=>{this.#i()};fail(e){this.#i(e)}handleItem(e){this.#r.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()}}#i(e){this.#t||(this.#r.close(),this.#o(e))}#o(e){this.#t=!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 Zr{get subscribers(){return this.#r}#e;#t;#r=new Set;constructor(e){this.#e=e}close(){this.#t=void 0;for(const e of[...this.#r])e.close();this.#r.clear()}add(e){this.#r.add(e)}ensureStarted(){return this.#t||(this.#t=(async()=>{try{return await this.#e.start()}catch(e){throw this.#t=void 0,e}})()),this.#t}release(e){this.#r.delete(e),!(this.#r.size>0||!this.#t)&&(this.#t=void 0,this.#e.stop())}}class Kt extends Zr{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Hr({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 Yr{#e;#t;#r;#s;constructor(e){this.#s=e,this.#t=new Kt({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{X(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#r=new Kt({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{X(e,"appetizeio.device.server.debug.proxyIntercept.stop",void 0)}})}close(){this.#e?.detach(),this.#t.close(),this.#r.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new Wr(this.#s,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#t.createStream(e)}async createProxyInterceptStream(e){return await this.#r.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#t.handleNotification(e)}handleProxyInterceptEvent(e){this.#r.handleNotification(e)}}function nt(t){return{...Xr(t),index:t.index,within:t.within?nt(t.within):void 0}}function Xr(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:Qr(t.text)}}}function Qr(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function es(t){return{press:e=>{X(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function ts({onRequest:t,parent:e,proxyInlet:r,signal:s}){const n=new jt(e,{signal:s}),o=[()=>{n.close()}];return zt(n,r),t&&o.push(Pe(n,f=>{t(f,{source:"parent"})})),{cleanup:()=>{for(const f of o)f()},notifies:()=>e===globalThis.window?void 0:n}}const rs="@appetizeio/rpc:playwrightAdapter",Ue=Symbol.for(rs);function ss(t){window[Ue]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[T].send(r)},subscribe(r){return t[T].addEventListener("message",s=>{r(s.detail)})}};return window[Ue]=e,()=>{window[Ue]===e&&delete window[Ue]}}function ns({onRequest:t,proxyInlet:e}){const[r,s]=st(),o=[ss(s),()=>{r.close()}];return zt(r,e),t&&o.push(Pe(r,f=>{t(f,{source:"parent"})})),{cleanup:()=>{for(const f of o)f()},notifies:()=>r}}function Le(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...nt(t),x:t.x,y:t.y}}function is(t){return"to"in t?{from:Le(t.from),kind:"path",to:Le(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?Le(t.from):void 0,kind:"direction"}}function os(t){return{down:(e,r)=>{X(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{X(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{X(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const as=new Set(rt),ls=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,cs=/(\{\{|\{[^{}]*\})/u;function fs(t){const e=[];let r="";function s(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[n,o]of t.split(cs).entries())if(n%2===0){if(o.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=o}else o==="{{"?r+="{":(s(),e.push(ds(o.slice(1,-1))));return s(),e}function us(t,e){if(!as.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: ${rt.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function ds(t){const e=ls.exec(t)?.groups,r=e?.key??t;if(us(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 hs=Symbol("@appetizeio/client:v1Compat");function $t(t){return t?.[hs]}class ps{readable;ready;get dimensions(){return this.#s}#e=[];#t=!1;#r;#s;#n;#i;constructor({onClose:e,requestKeyFrame:r,signal:s}){this.#n=r,this.ready=new Promise((o,f)=>{this.#i={reject:f,resolve:o}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:o=>{n=o}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#r=n,s){const o=()=>{this.fail(s.reason)};s.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",o)})}this.#e.push(()=>{e(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleChunk(e){if(this.#i){if(e.type!=="key")return;const{resolve:r}=this.#i;this.#i=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.#r.enqueue(e)}requestKeyFrame=()=>{this.#t||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()}}#o(e){this.#t||(this.#r.close(),this.#a(e))}#a(e){this.#t=!0;for(const r of this.#e)r();this.#i?.reject(e??new Error("Video stream closed before the first key chunk")),this.#i=void 0}}class ys{#e=!1;#t;#r;#s=new Set;constructor(e){this.#t=e}close(){this.#r=void 0;for(const e of[...this.#s])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new ps({onClose:s=>{this.#i(s)},requestKeyFrame:()=>{this.#o()},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.#r?(this.#o(),this.#r):(this.#e=!0,this.#r=(async()=>{try{await this.#t.request("appetizeio.device.server.video.start")}catch(e){throw this.#r=void 0,e}})(),this.#r)}#i(e){this.#s.delete(e),!(this.#s.size>0||!this.#r)&&(this.#r=void 0,X(this.#t,"appetizeio.device.server.video.stop",void 0))}#o(){this.#e||(this.#e=!0,X(this.#t,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class ws{debug;keyboard;touch;video;#e;#t=[];#r;constructor(e,r={}){const s=$t(r)??{},{baseUrl:n,onClose:o,signal:f}=r;this.#e=n?bs(n):void 0;const{onRequest:b,parent:y,proxyRequest:v}=s,m=gs(b);f?.addEventListener("abort",this.close);const[x,R]=st(),[L,U]=st();this.#t.push(()=>{x.close(),R.close(),L.close(),U.close()}),this.#t.push(tt(U,e,{leftEffects:v}));const C=y==="playwright"?ns({onRequest:m,proxyInlet:L}):y?ts({onRequest:m,parent:y,proxyInlet:L,signal:f}):void 0;C&&this.#t.push(C.cleanup),this.#t.push(tt(R,L,{notifiesLeft:C?.notifies}));const{client:W,unsub:pe}=zr(x,{"appetizeio.device.client.debug.adbTunnel.data":z=>G.handleAdbTunnelData(z),"appetizeio.device.client.debug.adbTunnel.stopped":async z=>{G.handleAdbTunnelStopped(z)},"appetizeio.device.client.debug.log.entry":async z=>{G.handleLogEntry(z)},"appetizeio.device.client.debug.proxyIntercept.event":async z=>{G.handleProxyInterceptEvent(z)},"appetizeio.device.client.video.chunk":async z=>{k.handleChunk(z)}});this.#r=W,this.#t.push(pe);const G=new Yr(this.#r);this.#t.push(()=>{G.close()});const k=new ys(this.#r);this.#t.push(()=>{k.close()}),this.debug=G,this.keyboard=es(this.#r),this.touch=os(this.#r),this.video=k,m&&(this.#t.push(Pe(R,z=>{m(z,{source:"self"})})),e instanceof jt&&this.#t.push(Pe(e,z=>{m(z,{source:"iframe"})}))),this.#t.push(()=>o?.())}close=()=>{for(const e of this.#t)try{e()}catch(r){console.error("Device cleanup error:",r)}};async inspect(e,r){return await this.#r.request("appetizeio.device.server.inspect",{options:r,selector:e?nt(e):void 0})}async press(e){await this.#r.request("appetizeio.device.server.press",{action:e})}async rotate(e){return await this.#r.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(){const e=await this.#r.request("appetizeio.device.server.screenshot"),r=this.#e?new URL(e.url,this.#e).href:e.url,s=await fetch(r);if(!s.ok)throw new Error(`Screenshot download failed: ${String(s.status)} ${s.statusText}`);const n=s.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await s.arrayBuffer()),mimeType:n}}async swipe(e,r){await this.#r.request("appetizeio.device.server.swipe",{gesture:is(e),options:r})}async tap(e,r){await this.#r.request("appetizeio.device.server.tap",{options:r,selector:Le(e)})}async type(e,r){await this.#r.request("appetizeio.device.server.type",{options:r,steps:fs(e)})}}function bs(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const gs=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};function ms(t,e){const r=qt(t,e);return r===void 0?void 0:Jt(r,e)}function qt(t,e){if(t===void 0)return;const r=typeof t=="boolean"?Number.NaN:Number(t);if(!Number.isFinite(r))throw new Error(`${e} expects a number, e.g., ${e}=-0.1`);return r}function it(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new Error(`${e} needs a value`);return t}}function Jt(t,e){if(!(t>=0&&t<=1))throw new Error(`${e} expects a number between 0 and 1`);return t}function Es(t,e){const r=it(t,e);if(r===void 0)throw new Error(`${e} needs a value`);return r}const Ss="APPETIZEIO_FEATURE_FLAGS";function vs(){const t={};for(const e of(process.env[Ss]??"").split(",")){const r=e.trim();r!==""&&(t[r]=!0)}return t}function As(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function Wt(t){return it(t.endpoint,"--endpoint")??ks()}function ks(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const Os="https://appetize.io";async function Gt(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const o=new URL(t,Wt(r)??Os);for(const[y,v]of Object.entries(s))o.searchParams.set(y,v);const f=new Headers(n.headers);e&&f.set("x-api-key",As());const b=await fetch(o,{...n,headers:f});if(!b.ok)throw new Error(`The webserver rejected the request (${String(b.status)})`);return await b.json()}const Ht=["android","ios"];function Zt(t={}){return Gt("/api/v2/service/devices",{authorize:!1,commandOptions:t})}function Is(t){return Ht.includes(t)}async function Ms(t,e={}){return(await Zt(e)).find(s=>s.id===t)?.platform}function ot(t){try{return process.kill(t,0),!0}catch{return!1}}function xs(t){let e={...t,updatedAt:new Date().toISOString()};return{path:lt(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},Bs(e),e)}}function Rs(){const t=Xt();return pt(t,{recursive:!0}),cr(t).map(e=>at(e)).filter(e=>e!==void 0)}function Ts(t){if(t!==void 0){const r=at(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=Rs().filter(_s);if(e.length===0)throw new Error("No active sessions");if(e.length>1)throw new Error("Multiple active sessions; specify --session-id");return e[0]}function at(t){try{return JSON.parse(lr(lt(t),"utf8"))}catch{return}}function Ps(t){return te(ke(t),"control.sock")}function Yt(t){return te(ke(t),"daemon.log")}function Cs(t){return te(ke(t),"device.log.jsonl")}function Us(t,e){return{daemon:Yt(t),device:Cs(t),...e==="intercept"?{network:Ls(t)}:void 0}}function Ls(t){return te(ke(t),"network.jsonl")}function ke(t){const e=te(Xt(),t);return pt(e,{recursive:!0}),e}function lt(t){return te(ke(t),"state.json")}function Xt(){return process.env.APPETIZE_CLI_HOME??te(fr(),".appetize","cli","sessions")}function _s(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:ot(t.pid)}function Bs(t){const e=lt(t.sessionId),r=`${e}.tmp`;or(r,`${JSON.stringify(t,null,2)}
2
+ `),ar(r,e)}const ct="APPETIZE_DAEMON_CONFIG";function Ns(){const t=process.env[ct];if(!t)throw new Error(`${ct} is not set`);return JSON.parse(t)}function Ds(t){return JSON.stringify(t)}const Fs=["SIGINT","SIGTERM"],zs=150;function js(t){const e=new AbortController,r=setInterval(()=>{ot(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},zs);return r.unref(),e.signal}function Vs(){const t=new AbortController;for(const e of Fs)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function Ks(){"CloseEvent"in globalThis||(globalThis.CloseEvent=class 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}})}export{kr as A,Qe as B,$t as C,ws as D,Ce as E,Ns as F,xs as G,Ms as H,tt as I,Ps as J,Bt as S,Ae as T,qt as a,Zt as b,Ht as c,Dr as d,Es as e,Gt as f,Yt as g,ct as h,Is as i,at as j,vs as k,Wt as l,Us as m,Vs as n,ot as o,it as p,ms as q,Jt as r,Ds as s,Dt as t,Ts as u,js as v,rt as w,Ks as x,Tr as y,T as z};
package/daemon.js CHANGED
@@ -1,2 +1,2 @@
1
- import{T as W,x as T,y as U,z as b,A as M,D as O,B as _,C as z,E as F,l as V,F as N,G as j,S as Q,H as J,I as G,m as H,w as K}from"./close-event-DSfV7BZf.js";import S from"debug";import{createServer as k}from"node:net";import{pipeline as L}from"node:stream";import{rm as B}from"node:fs/promises";import{createWriteStream as Z,existsSync as X,rmSync as Y}from"node:fs";import{pipeline as ee}from"node:stream/promises";import{EncodedVideoPacketSource as te,Output as ne,FilePathTarget as re,Mp4OutputFormat as oe,EncodedPacket as se}from"mediabunny";import"stream";import"module";import"json-rpc-2.0";import"node:os";import"node:path";const ie=S("appetize.io:transport:ws-ping"),ae=3e4;function ce(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const r=setInterval(()=>{if(!t){clearInterval(r),ie("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},ae);return{destroy(){clearInterval(r),e.off("pong",n)},pong:n}}const g=S("appetize.io:trace:transport:websocket");class A extends W{constructor(t,{signal:n}={}){super(async o=>{this.#e.send(T(o))},{signal:n}),this.wsOrUrl=t,typeof t=="string"?(this.#e=new WebSocket(t),this.#e.binaryType="arraybuffer"):this.#e=t;const r=this.#e;if(r instanceof WebSocket?(r.addEventListener("open",this.#s),r.addEventListener("message",this.#o),r.addEventListener("error",this.#r),r.addEventListener("close",this.#n),this.#t.push(()=>{r.removeEventListener("open",this.#s),r.removeEventListener("message",this.#o),r.removeEventListener("error",this.#r),r.removeEventListener("close",this.#n)})):(r.addEventListener("open",this.#s),r.addEventListener("message",this.#o),r.addEventListener("error",this.#r),r.addEventListener("close",this.#n),this.#t.push(()=>{r.removeEventListener("open",this.#s),r.removeEventListener("message",this.#o),r.removeEventListener("error",this.#r),r.removeEventListener("close",this.#n)})),this.send=r.send.bind(r),"ping"in r){const{destroy:o,pong:s}=ce(r);this.#c=s,this.#t.push(o)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#e.bufferedAmount}get readyState(){return this.#e.readyState}#t=[];#i=!1;#a=!1;#c;#e;close({destroyWs:t=!1,...n}={}){this.closed||(this.#i=t,super.close(n))}handleClose(t){g("close()");for(const n of this.#t.splice(0))n();if((typeof this.wsOrUrl=="string"||this.#i)&&(this.#e.close(t.code,t.reason),"terminate"in this.#e)){const n=this.#e;setTimeout(()=>{n.terminate()},100)}this.#d(),super.handleClose(t)}#d(t){this.#a||(this.#a=!0,this.onclose?.(t))}#n=t=>{g("handleWebSocketClose()",t);try{this.#d(t)}finally{this.close()}};#r=t=>{g("handleWebSocketError()",t),this.onerror?.(t)};#o=async t=>{g("handleWebSocketMessage()",t),this.#c?.();const n=this.#u(t);if(!n){g("handleWebSocketMessage() -> legacy"),this.onmessage?.(t);return}g("handleWebSocketMessage() -> jsonrpc",n),this[U].dispatchMessage(n)};#s=t=>{g("handleWebSocketOpen()",t),this.onopen?.(t)};#u(t){try{const n=b(new Uint8Array(t.data));return M(n)?n:null}catch{return null}}}function v(e){return typeof e=="object"&&e!==null}function R(e){try{const t=b(new Uint8Array(e.data));if(v(t)&&typeof t.name=="string")return{name:t.name,payload:"payload"in t?t.payload:void 0}}catch{}}async function de(e,t={}){const n=t.baseUrl??(typeof e=="string"?new URL(e).origin:void 0),r=typeof e=="string"?new A(e,{signal:t.signal}):e,o=new O(r,{...t,baseUrl:n});return typeof e=="string"&&await ue(r,o,t),o}function ue(e,t,n){const r=_(n)?.onLegacyMessage;return new Promise((o,s)=>{e.onopen=()=>{o()},e.onclose=()=>{t.close(),n.signal?.aborted?s(n.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},e.onerror=s,e.onmessage=i=>{const c=R(i);c&&r?.(c)}})}async function le(e,{device:t,onStateChange:n,signal:r}){r?.throwIfAborted(),n?.({device:t,phase:"starting"}),await new Promise((o,s)=>{const i=()=>{c(),s(r?.reason)},c=()=>{e.onmessage=void 0,e.onclose=void 0,r?.removeEventListener("abort",i)};e.onmessage=a=>{const d=fe(R(a),t);d&&(n?.(d),d.phase==="ready"&&(c(),o()))},e.onclose=()=>{c(),s(new Error("The device closed before it was ready"))},r?.addEventListener("abort",i,{once:!0})})}function fe(e,t){if(!e)return;if(e.name==="ready")return{device:t,phase:"ready"};if(e.name!=="launchStatus")return;switch(v(e.payload)&&typeof e.payload.status=="string"?e.payload.status:void 0){case"downloadingApp":return{device:t,phase:"downloadingApp"};case"installingApp":return{device:t,phase:"installingApp"};case"launchingApp":return{device:t,phase:"launchingApp"};default:return}}function pe(){return typeof process>"u"?void 0:process}function he(e){return{deviceType:e.id,osVersion:e.osVersion}}function we(e){return e==="intercept"?"interceptOnDemand":e}class y extends Error{code;constructor(t,n){super(n),this.name="SessionRequestError",this.code=t}}function ge(e,{onClose:t,onEvent:n,signal:r}={}){return new Promise((o,s)=>{const i=new WebSocket(e);i.binaryType="arraybuffer",i.onopen=()=>{$(i,{capabilities:{},t:"handshake"})},i.onmessage=c=>{ye(i,c,{onEvent:n,onHandshake:a=>{o({close:()=>{i.close()},id:a})}})},i.onclose=()=>{s(new y("disconnected",`The connection to ${e} closed`)),t?.()},r?.addEventListener("abort",()=>{s(r.reason),i.close()},{once:!0})})}function ye(e,t,n){const r=b(new Uint8Array(t.data));v(r)&&(r.t==="handshake"&&typeof r.id=="string"?n.onHandshake(r.id):r.name==="ping"?$(e,{name:"pong"}):typeof r.name=="string"&&n.onEvent?.(r.name,r.payload))}function $(e,t){e.send(T(t))}async function ve(e,t,{apiToken:n,onQueue:r,signal:o}={}){const s=z();Ee(s.reject,o);const i=await ge(Te(e),{onClose:()=>{s.reject(me())},onEvent:(c,a)=>{be(c,a,s,r)},signal:o});return Se(e,{apiToken:n,data:t,socketid:i.id},o).catch(s.reject),await s.promise.finally(()=>{i.close()})}function me(){return new y("disconnected","The webserver connection closed before a session was granted")}function P(e,t){return v(e)?e[t]:void 0}function be(e,t,n,r){if(e==="queue"||e==="concurrentQueue"){const o=e==="queue"?Le(t):Ae(t);o&&r?.(o)}else e==="newSession"?ke(n,t):e==="userError"&&n.reject(new y("denied",Re(t)))}function q(e,t){const n=P(e,t);return typeof n=="number"?n:void 0}function m(e,t){const n=P(e,t);return typeof n=="string"?n:void 0}async function Se(e,t,n){const r=await fetch(new URL("/api/session/request",e),{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST",signal:n});if(!r.ok)throw new y("denied",`The webserver rejected the session request (${String(r.status)})`)}function Ee(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function Te(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function ke(e,t){const n=m(t,"path"),r=m(t,"sessionToken");n!==void 0&&r!==void 0?e.resolve({path:n,sessionToken:r}):e.reject(new y("denied","The granted session is missing its address"))}function Le(e){const t=q(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function Ae(e){const t=q(e,"position");if(t!==void 0)return{limit:m(e,"name")??"Queue",position:t,reason:"concurrency"}}function Re(e){return m(e,"message")??"The session request was denied"}async function $e({apiToken:e=Pe(),codec:t="h264",device:n,endpoint:r="https://appetize.io",onStateChange:o,proxy:s,signal:i,target:c}){if(i?.throwIfAborted(),!c)throw new TypeError("target is required");if(!n.id)throw new TypeError("device.id is required");o?.({phase:"requesting"});const a=await ve(r,{codec:t,noVideo:!0,proxy:we(s),publicKey:c,...he(n)},{apiToken:e,onQueue:d=>{o?.({phase:"queued",queue:d})},signal:i});return{baseUrl:new URL(a.path).origin,url:qe(a)}}function Pe(){return pe()?.env.APPETIZE_API_TOKEN}function qe(e){const t=new URL("/client",e.path);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.searchParams.set("sessionToken",e.sessionToken),t.href}const Ie=S("appetize:daemon");function u(e){Ie(e)}function Ce(e,{message:t="The operation timed out"}={}){const n=new AbortController,r=setTimeout(()=>{n.abort(new Error(t))},e),o=()=>{clearTimeout(r)};return{cancel:o,signal:n.signal,[Symbol.dispose]:o}}var xe=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),I=e=>{throw TypeError(e)},De=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&I("Object expected");var r,o;r===void 0&&(r=t[xe("dispose")]),typeof r!="function"&&I("Object not disposable"),o&&(r=function(){try{o.call(this)}catch(s){return Promise.reject(s)}}),e.push([n,r,t])}return t},We=(e,t,n)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,d){return d=Error(a),d.name="SuppressedError",d.error=i,d.suppressed=c,d},o=i=>t=n?new r(i,t,"An error was suppressed during disposal"):(n=!0,i),s=i=>{for(;i=e.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(s,a=>(o(a),s()))}catch(a){o(a)}if(n)throw t};return s()};const Ue=1e4;async function Me(e,t,{onClose:n,signal:r}={}){var o=[];try{const c=De(o,Ce(Ue,{message:"Timed out waiting for session request state"})),a=AbortSignal.any([r,c.signal].filter(w=>!!w)),d=w=>{t.save({state:w}),u(w.phase),w.phase!=="requesting"&&c.cancel()},{baseUrl:f,url:p}=await $e({device:e.device,endpoint:e.endpoint,onStateChange:d,proxy:e.proxy,signal:a,target:e.target});t.save({baseUrl:f});const l=new A(p,{signal:a});return await le(l,{device:e.device,onStateChange:d,signal:a}),l.onclose=()=>{n?.("The device connection closed")},{device:await de(l,{baseUrl:f,signal:a}),transport:l}}catch(c){var s=c,i=!0}finally{We(o,s,i)}}function Oe(){const e=F(),t=V(e.sessionId,e.proxy),n=N({device:e.device,endpoint:e.endpoint,pid:process.pid,proxy:e.proxy,sessionId:e.sessionId,startedAt:new Date().toISOString(),target:e.target});return n.save({logs:t}),{config:e,logs:t,store:n}}async function _e(e,{host:t="127.0.0.1",onError:n,port:r=0,signal:o}={}){o?.throwIfAborted();let s;const i=()=>{const p=s;s=void 0,p&&(p.tunnel?.close(),p.socket.destroy())},c=async p=>{const{socket:l}=p;try{const h=await e.debug.createAdbTunnel();if(l.destroyed){h.close();return}p.tunnel=h,h.closed.catch(w=>{n?.(w)}),ze(l,h)}catch(h){l.destroyed||n?.(h),l.destroy()}},a=k(p=>{i();const l={socket:p};s=l,p.once("close",()=>{s===l&&(s=void 0)}),c(l)}),d=()=>{o?.removeEventListener("abort",d),i(),a.close()};o?.addEventListener("abort",d,{once:!0});const f=await Fe(a,t,r);return{close:d,url:new URL(`adb://${f.address}:${String(f.port)}`)}}function ze(e,t){L(t.readable,e,C),L(e,async n=>{const r=t.writable.getWriter();try{for await(const o of n)await r.write(o);await r.close()}catch(o){throw await r.abort(o),o}},C)}function C(){}function Fe(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen({host:t,port:n},()=>{e.off("error",o);const s=e.address();if(s===null||typeof s=="string"){o(new Error("The listener has no tcp address"));return}r(s)})})}async function Ve(e,t,n,{signal:r}={}){try{if(!await Ne(t))return;const o=await _e(e,{onError:s=>{u(`adb endpoint error: ${x(s)}`)},signal:r});n.save({adbSerial:o.url.host}),u(`adb endpoint listening at ${o.url.host}`)}catch(o){u(`adb endpoint unavailable: ${x(o)}`)}}async function Ne(e){return await j(e.device.id,{endpoint:e.endpoint})==="android"}function x(e){return e instanceof Error?e.message:String(e)}async function je(e,t,{methods:n={},signal:r}={}){await B(t,{force:!0});const o=new Set,s=k(i=>{u("control client connected"),o.add(i),i.once("close",()=>{o.delete(i)});const c=new Q(i,{signal:r});J(c,e,{leftEffects:()=>n})});r?.addEventListener("abort",()=>{for(const i of o)i.destroy()},{once:!0}),await new Promise((i,c)=>{s.once("error",c),s.listen({path:t,signal:r},()=>{s.off("error",c),i()})})}async function Qe(e,t,n,{recorder:r,signal:o}){const s=G(n);return await je(e,s,{methods:{"appetizeio.cli.record.start":async i=>await r.start(i),"appetizeio.cli.record.stop":async()=>await r.stop()},signal:o}),t.save({controlSocket:s}),s}function Je(e){const t=new AbortController,n=Ge(e,t),r=H();return r.addEventListener("abort",()=>{const{reason:o}=r;n(o instanceof Error?o.message:String(o))},{once:!0}),{shutdown:n,signal:t.signal}}function Ge(e,t){let n=!1;return r=>{n||(n=!0,e.save({endedAt:new Date().toISOString(),endedReason:r,state:{phase:"ended"}}),u(r),t.abort())}}async function D(e,t,{label:n,signal:r}){try{const o=await e();await ee(o.readable.pipeThrough(He()),Z(t,{flags:"a"}))}catch(o){if(r?.aborted)return;const s=o instanceof Error?o.message:String(o);u(`${n} ended with an error: ${s}`)}}function He(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
2
- `)}})}async function Ke(e,t,{signal:n}={}){await D(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function Be(e,t,{signal:n}={}){await D(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}const E=30;async function Ze(e,t){await e.pipeTo(Ye(t))}function Xe(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function Ye(e){let t;const n=async()=>{await t?.output.finalize()};return new WritableStream({abort:n,close:n,write:async r=>{r.data.byteLength!==0&&(t??=await et(nt(r),e),tt(t,r),await rt(t,r))}})}async function et(e,t){const n=new te("avc"),r=new ne({format:new oe({fastStart:"fragmented"}),target:new re(t,{chunked:!1})});return r.addVideoTrack(n,{frameRate:E}),await r.start(),{frame:0,output:r,seen:{height:e.height,width:e.width},size:{height:e.height,width:e.width},source:n}}function tt(e,t){if(t.type!=="key")return;const{seen:n,size:r}=e;t.width===n.width&&t.height===n.height||(e.seen={height:t.height,width:t.width},u(`video resized to ${String(t.width)}x${String(t.height)}; keeping ${String(r.width)}x${String(r.height)}`))}function nt(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function rt(e,t){const n=new se(t.data,t.type,e.frame/E,1/E);e.frame+=1,await e.source.add(n,Xe(e.size))}function ot(e,t,{signal:n}={}){let r,o;const s=async(a,{force:d=!1}={})=>{if(X(a)){if(!d)throw new Error(`A recording already exists at ${a}; pass --force to overwrite`);Y(a)}const f=await e.video.createStream({signal:n});return r={done:st(f,a),path:a,stream:f},t.save({video:{path:a,recording:!0}}),u(`recording video to ${a}`),{path:a}},i=async a=>{a.stream.close();try{await a.done,t.save({video:{path:a.path,recording:!1}})}finally{r=void 0,o=void 0}},c=async()=>{if(!r)return;const{path:a}=r;await i(r),u(`closed the video recording: ${a}`)};return n?.addEventListener("abort",()=>{c()},{once:!0}),{start:async({force:a=!1,path:d})=>{const f=r?.path??o;if(f!==void 0)throw new Error(`Already recording to ${f}`);o=d;try{return await s(d,{force:a})}finally{o=void 0}},stop:async()=>{if(!r)throw new Error("No video recording in progress");const{path:a}=r;return await i(r),{path:a}}}}async function st(e,t){try{await Ze(e.readable,t)}catch(n){u(`video capture ended with an error: ${String(n)}`)}}async function it(){const{config:e,logs:t,store:n}=Oe();u(`recording to ${n.path}`);const{shutdown:r,signal:o}=Je(n);try{const{device:s,transport:i}=await Me(e,n,{onClose:r,signal:o}),c=ot(s,n,{signal:o});await Ve(s,e,n,{signal:o});const a=await Qe(i,n,e.sessionId,{recorder:c,signal:o});u(`control socket listening at ${a}`),Ke(s,t.device,{signal:o}),u(`recording device logs to ${t.device}`),t.network&&(Be(s,t.network,{signal:o}),u(`recording network events to ${t.network}`))}catch(s){if(o.aborted)return;const i=s instanceof Error?s.message:String(s);n.save({endedAt:new Date().toISOString(),endedReason:i,state:{message:i,phase:"error"}}),u(`error: ${i}`),process.exitCode=1}}K(),it();
1
+ import{T as M,y as L,z as O,A as b,B as z,D as _,C as F,E as V,F as N,m as j,G as H,H as J,S as Q,I as k,J as G,n as K,x as B}from"./close-event-BFzpneqE.js";import S from"debug";import{createServer as A}from"node:net";import{pipeline as $}from"node:stream";import{rm as Z}from"node:fs/promises";import{readFileSync as X,createWriteStream as Y,existsSync as ee,rmSync as te}from"node:fs";import{createServer as ne}from"node:http";import{WebSocketServer as re}from"ws";import{pipeline as oe}from"node:stream/promises";import{EncodedVideoPacketSource as se,Output as ie,FilePathTarget as ae,Mp4OutputFormat as ce,EncodedPacket as de}from"mediabunny";import"stream";import"module";import"json-rpc-2.0";import"node:os";import"node:path";const ue=S("appetize.io:transport:ws-ping"),le=3e4;function fe(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const r=setInterval(()=>{if(!t){clearInterval(r),ue("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},le);return{destroy(){clearInterval(r),e.off("pong",n)},pong:n}}const v=S("appetize.io:trace:transport:websocket");class E extends M{constructor(t,{signal:n}={}){super(async o=>{this.#e.send(L(o))},{signal:n}),this.wsOrUrl=t,typeof t=="string"?(this.#e=new WebSocket(t),this.#e.binaryType="arraybuffer"):this.#e=t;const r=this.#e;if(r instanceof WebSocket?(r.addEventListener("open",this.#s),r.addEventListener("message",this.#o),r.addEventListener("error",this.#r),r.addEventListener("close",this.#n),this.#t.push(()=>{r.removeEventListener("open",this.#s),r.removeEventListener("message",this.#o),r.removeEventListener("error",this.#r),r.removeEventListener("close",this.#n)})):(r.addEventListener("open",this.#s),r.addEventListener("message",this.#o),r.addEventListener("error",this.#r),r.addEventListener("close",this.#n),this.#t.push(()=>{r.removeEventListener("open",this.#s),r.removeEventListener("message",this.#o),r.removeEventListener("error",this.#r),r.removeEventListener("close",this.#n)})),this.send=r.send.bind(r),"ping"in r){const{destroy:o,pong:s}=fe(r);this.#c=s,this.#t.push(o)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#e.bufferedAmount}get readyState(){return this.#e.readyState}#t=[];#i=!1;#a=!1;#c;#e;close({destroyWs:t=!1,...n}={}){this.closed||(this.#i=t,super.close(n))}handleClose(t){v("close()");for(const n of this.#t.splice(0))n();if((typeof this.wsOrUrl=="string"||this.#i)&&(this.#e.close(t.code,t.reason),"terminate"in this.#e)){const n=this.#e;setTimeout(()=>{n.terminate()},100)}this.#d(),super.handleClose(t)}#d(t){this.#a||(this.#a=!0,this.onclose?.(t))}#n=t=>{v("handleWebSocketClose()",t);try{this.#d(t)}finally{this.close()}};#r=t=>{v("handleWebSocketError()",t),this.onerror?.(t)};#o=async t=>{v("handleWebSocketMessage()",t),this.#c?.();const n=this.#u(t);if(!n){v("handleWebSocketMessage() -> legacy"),this.onmessage?.(t);return}v("handleWebSocketMessage() -> jsonrpc",n),this[O].dispatchMessage(n)};#s=t=>{v("handleWebSocketOpen()",t),this.onopen?.(t)};#u(t){try{const n=b(new Uint8Array(t.data));return z(n)?n:null}catch{return null}}}function y(e){return typeof e=="object"&&e!==null}function R(e){try{const t=b(new Uint8Array(e.data));if(y(t)&&typeof t.name=="string")return{name:t.name,payload:"payload"in t?t.payload:void 0}}catch{}}async function pe(e,t={}){const n=t.baseUrl??(typeof e=="string"?new URL(e).origin:void 0),r=typeof e=="string"?new E(e,{signal:t.signal}):e,o=new _(r,{...t,baseUrl:n});return typeof e=="string"&&await he(r,o,t),o}function he(e,t,n){const r=F(n)?.onLegacyMessage;return new Promise((o,s)=>{e.onopen=()=>{o()},e.onclose=()=>{t.close(),n.signal?.aborted?s(n.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},e.onerror=s,e.onmessage=i=>{const c=R(i);c&&r?.(c)}})}async function we(e,{device:t,onStateChange:n,signal:r}){r?.throwIfAborted(),n?.({device:t,phase:"starting"}),await new Promise((o,s)=>{const i=()=>{c(),s(r?.reason)},c=()=>{e.onmessage=void 0,e.onclose=void 0,r?.removeEventListener("abort",i)};e.onmessage=a=>{const d=ve(R(a),t);d&&(n?.(d),d.phase==="ready"&&(c(),o()))},e.onclose=()=>{c(),s(new Error("The device closed before it was ready"))},r?.addEventListener("abort",i,{once:!0})})}function ve(e,t){if(!e)return;if(e.name==="ready")return{device:t,phase:"ready"};if(e.name!=="launchStatus")return;switch(y(e.payload)&&typeof e.payload.status=="string"?e.payload.status:void 0){case"downloadingApp":return{device:t,phase:"downloadingApp"};case"installingApp":return{device:t,phase:"installingApp"};case"launchingApp":return{device:t,phase:"launchingApp"};default:return}}function ge(){return typeof process>"u"?void 0:process}function ye(e){return{deviceType:e.id,osVersion:e.osVersion}}function me(e){return e==="intercept"?"interceptOnDemand":e}class g extends Error{code;constructor(t,n){super(n),this.name="SessionRequestError",this.code=t}}function be(e,{onClose:t,onEvent:n,signal:r}={}){return new Promise((o,s)=>{const i=new WebSocket(e);i.binaryType="arraybuffer",i.onopen=()=>{P(i,{capabilities:{},t:"handshake"})},i.onmessage=c=>{Se(i,c,{onEvent:n,onHandshake:a=>{o({close:()=>{i.close()},id:a})}})},i.onclose=()=>{s(new g("disconnected",`The connection to ${e} closed`)),t?.()},r?.addEventListener("abort",()=>{s(r.reason),i.close()},{once:!0})})}function Se(e,t,n){const r=b(new Uint8Array(t.data));y(r)&&(r.t==="handshake"&&typeof r.id=="string"?n.onHandshake(r.id):r.name==="ping"?P(e,{name:"pong"}):typeof r.name=="string"&&n.onEvent?.(r.name,r.payload))}function P(e,t){e.send(L(t))}async function Ee(e,t,{apiToken:n,onQueue:r,signal:o}={}){const s=V();Ae(s.reject,o);const i=await be($e(e),{onClose:()=>{s.reject(Te())},onEvent:(c,a)=>{Le(c,a,s,r)},signal:o});return ke(e,{apiToken:n,data:t,socketid:i.id},o).catch(s.reject),await s.promise.finally(()=>{i.close()})}function Te(){return new g("disconnected","The webserver connection closed before a session was granted")}function C(e,t){return y(e)?e[t]:void 0}function Le(e,t,n,r){if(e==="queue"||e==="concurrentQueue"){const o=e==="queue"?Pe(t):Ce(t);o&&r?.(o)}else e==="newSession"?Re(n,t):e==="userError"&&n.reject(new g("denied",Ie(t)))}function I(e,t){const n=C(e,t);return typeof n=="number"?n:void 0}function m(e,t){const n=C(e,t);return typeof n=="string"?n:void 0}async function ke(e,t,n){const r=await fetch(new URL("/api/session/request",e),{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST",signal:n});if(!r.ok)throw new g("denied",`The webserver rejected the session request (${String(r.status)})`)}function Ae(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function $e(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function Re(e,t){const n=m(t,"path"),r=m(t,"sessionToken");n!==void 0&&r!==void 0?e.resolve({path:n,sessionToken:r}):e.reject(new g("denied","The granted session is missing its address"))}function Pe(e){const t=I(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function Ce(e){const t=I(e,"position");if(t!==void 0)return{limit:m(e,"name")??"Queue",position:t,reason:"concurrency"}}function Ie(e){return m(e,"message")??"The session request was denied"}async function Ue({apiToken:e=We(),codec:t="h264",device:n,endpoint:r="https://appetize.io",onStateChange:o,proxy:s,signal:i,target:c}){if(i?.throwIfAborted(),!c)throw new TypeError("target is required");if(!n.id)throw new TypeError("device.id is required");o?.({phase:"requesting"});const a=await Ee(r,{codec:t,noVideo:!0,proxy:me(s),publicKey:c,...ye(n)},{apiToken:e,onQueue:d=>{o?.({phase:"queued",queue:d})},signal:i});return{baseUrl:new URL(a.path).origin,url:xe(a)}}function We(){return ge()?.env.APPETIZE_API_TOKEN}function xe(e){const t=new URL("/client",e.path);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.searchParams.set("sessionToken",e.sessionToken),t.href}const De=S("appetize:daemon");function f(e){De(e)}function qe(e,{message:t="The operation timed out"}={}){const n=new AbortController,r=setTimeout(()=>{n.abort(new Error(t))},e),o=()=>{clearTimeout(r)};return{cancel:o,signal:n.signal,[Symbol.dispose]:o}}var Me=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),U=e=>{throw TypeError(e)},Oe=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&U("Object expected");var r,o;r===void 0&&(r=t[Me("dispose")]),typeof r!="function"&&U("Object not disposable"),o&&(r=function(){try{o.call(this)}catch(s){return Promise.reject(s)}}),e.push([n,r,t])}return t},ze=(e,t,n)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,d){return d=Error(a),d.name="SuppressedError",d.error=i,d.suppressed=c,d},o=i=>t=n?new r(i,t,"An error was suppressed during disposal"):(n=!0,i),s=i=>{for(;i=e.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(s,a=>(o(a),s()))}catch(a){o(a)}if(n)throw t};return s()};const _e=1e4;async function Fe(e,t,{onClose:n,signal:r}={}){var o=[];try{const c=Oe(o,qe(_e,{message:"Timed out waiting for session request state"})),a=AbortSignal.any([r,c.signal].filter(w=>!!w)),d=w=>{t.save({state:w}),f(w.phase),w.phase!=="requesting"&&c.cancel()},{baseUrl:p,url:u}=await Ue({device:e.device,endpoint:e.endpoint,onStateChange:d,proxy:e.proxy,signal:a,target:e.target});t.save({baseUrl:p});const l=new E(u,{signal:a});return await we(l,{device:e.device,onStateChange:d,signal:a}),l.onclose=()=>{n?.("The device connection closed")},{device:await pe(l,{baseUrl:p,signal:a}),transport:l}}catch(c){var s=c,i=!0}finally{ze(o,s,i)}}function Ve(){const e=N(),t=j(e.sessionId,e.proxy),n=H({device:e.device,endpoint:e.endpoint,pid:process.pid,proxy:e.proxy,sessionId:e.sessionId,startedAt:new Date().toISOString(),target:e.target});return n.save({logs:t}),{config:e,logs:t,store:n}}async function Ne(e,{host:t="127.0.0.1",onError:n,port:r=0,signal:o}={}){o?.throwIfAborted();let s;const i=()=>{const u=s;s=void 0,u&&(u.tunnel?.close(),u.socket.destroy())},c=async u=>{const{socket:l}=u;try{const h=await e.debug.createAdbTunnel();if(l.destroyed){h.close();return}u.tunnel=h,h.closed.catch(w=>{n?.(w)}),je(l,h)}catch(h){l.destroyed||n?.(h),l.destroy()}},a=A(u=>{i();const l={socket:u};s=l,u.once("close",()=>{s===l&&(s=void 0)}),c(l)}),d=()=>{o?.removeEventListener("abort",d),i(),a.close()};o?.addEventListener("abort",d,{once:!0});const p=await He(a,t,r);return{close:d,url:new URL(`adb://${p.address}:${String(p.port)}`)}}function je(e,t){$(t.readable,e,W),$(e,async n=>{const r=t.writable.getWriter();try{for await(const o of n)await r.write(o);await r.close()}catch(o){throw await r.abort(o),o}},W)}function W(){}function He(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen({host:t,port:n},()=>{e.off("error",o);const s=e.address();if(s===null||typeof s=="string"){o(new Error("The listener has no tcp address"));return}r(s)})})}async function Je(e,t,n,{signal:r}={}){try{if(!await Qe(t))return;const o=await Ne(e,{onError:s=>{f(`adb endpoint error: ${x(s)}`)},signal:r});n.save({adbSerial:o.url.host}),f(`adb endpoint listening at ${o.url.host}`)}catch(o){f(`adb endpoint unavailable: ${x(o)}`)}}async function Qe(e){return await J(e.device.id,{endpoint:e.endpoint})==="android"}function x(e){return e instanceof Error?e.message:String(e)}async function Ge(e,t,{methods:n={},signal:r}={}){await Z(t,{force:!0});const o=new Set,s=A(i=>{f("control client connected"),o.add(i),i.once("close",()=>{o.delete(i)});const c=new Q(i,{signal:r});k(c,e,{leftEffects:()=>n})});r?.addEventListener("abort",()=>{for(const i of o)i.destroy()},{once:!0}),await new Promise((i,c)=>{s.once("error",c),s.listen({path:t,signal:r},()=>{s.off("error",c),i()})})}async function Ke(e,t,n,{recorder:r,signal:o}){const s=G(n);return await Ge(e,s,{methods:{"appetizeio.cli.record.start":async i=>await r.start(i),"appetizeio.cli.record.stop":async()=>await r.stop()},signal:o}),t.save({controlSocket:s}),s}const D="127.0.0.1";async function Be(e,t,n={}){try{const r=await Ze(e,n);return t.save({viewerUrl:r.url.href}),f(`web endpoint listening at ${r.url.href}`),r}catch(r){f(`web endpoint unavailable: ${nt(r)}`);return}}async function Ze(e,{port:t=0,signal:n,viewerHtml:r=X(new URL("./viewer.html",import.meta.url),"utf8")}){n?.throwIfAborted();const o=ne((u,l)=>{Ye(u,l,r)}),s=new Set,i=new re({noServer:!0,perMessageDeflate:!1});let c;i.on("connection",u=>{if(s.size>0){u.close(1013,"Viewer already connected");return}s.add(u);const l=new E(u);k(l,e),u.once("close",()=>{s.delete(u)})}),o.on("upgrade",(u,l,h)=>{et(i,u,l,h)});const a=()=>(c??=new Promise((u,l)=>{n?.removeEventListener("abort",d);for(const h of s)Xe(h);i.close(),o.close(h=>{h?l(h):u()})}),c),d=()=>{a()};await tt(o,t),n?.addEventListener("abort",d,{once:!0});const p=o.address();if(!p||typeof p=="string")throw await a(),new Error("Web address unavailable");return{close:a,url:new URL(`http://${D}:${String(p.port)}/`)}}function Xe(e){e.close(1001)}function Ye(e,t,n){if(e.method==="GET"&&e.url==="/"){t.writeHead(200,{"Cache-Control":"no-store","Content-Type":"text/html; charset=utf-8"}),t.end(n);return}t.writeHead(404).end()}function et(e,t,n,r){if(t.url!=="/ws"){n.destroy();return}e.handleUpgrade(t,n,r,o=>{e.emit("connection",o,t)})}function tt(e,t){return new Promise((n,r)=>{const o=s=>{r(s)};e.once("error",o),e.listen(t,D,()=>{e.removeListener("error",o),n()})})}function nt(e){return e instanceof Error?e.message:String(e)}function rt(e){const t=new AbortController,n=ot(e,t),r=K();return r.addEventListener("abort",()=>{const{reason:o}=r;n(o instanceof Error?o.message:String(o))},{once:!0}),{shutdown:n,signal:t.signal}}function ot(e,t){let n=!1;return r=>{n||(n=!0,e.save({endedAt:new Date().toISOString(),endedReason:r,state:{phase:"ended"}}),f(r),t.abort())}}async function q(e,t,{label:n,signal:r}){try{const o=await e();await oe(o.readable.pipeThrough(st()),Y(t,{flags:"a"}))}catch(o){if(r?.aborted)return;const s=o instanceof Error?o.message:String(o);f(`${n} ended with an error: ${s}`)}}function st(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
2
+ `)}})}async function it(e,t,{signal:n}={}){await q(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function at(e,t,{signal:n}={}){await q(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}const T=30;async function ct(e,t){await e.pipeTo(ut(t))}function dt(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function ut(e){let t;const n=async()=>{await t?.output.finalize()};return new WritableStream({abort:n,close:n,write:async r=>{r.data.byteLength!==0&&(t??=await lt(pt(r),e),ft(t,r),await ht(t,r))}})}async function lt(e,t){const n=new se("avc"),r=new ie({format:new ce({fastStart:"fragmented"}),target:new ae(t,{chunked:!1})});return r.addVideoTrack(n,{frameRate:T}),await r.start(),{frame:0,output:r,seen:{height:e.height,width:e.width},size:{height:e.height,width:e.width},source:n}}function ft(e,t){if(t.type!=="key")return;const{seen:n,size:r}=e;t.width===n.width&&t.height===n.height||(e.seen={height:t.height,width:t.width},f(`video resized to ${String(t.width)}x${String(t.height)}; keeping ${String(r.width)}x${String(r.height)}`))}function pt(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function ht(e,t){const n=new de(t.data,t.type,e.frame/T,1/T);e.frame+=1,await e.source.add(n,dt(e.size))}function wt(e,t,{signal:n}={}){let r,o;const s=async(a,{force:d=!1}={})=>{if(ee(a)){if(!d)throw new Error(`A recording already exists at ${a}; pass --force to overwrite`);te(a)}const p=await e.video.createStream({signal:n});return r={done:vt(p,a),path:a,stream:p},t.save({video:{path:a,recording:!0}}),f(`recording video to ${a}`),{path:a}},i=async a=>{a.stream.close();try{await a.done,t.save({video:{path:a.path,recording:!1}})}finally{r=void 0,o=void 0}},c=async()=>{if(!r)return;const{path:a}=r;await i(r),f(`closed the video recording: ${a}`)};return n?.addEventListener("abort",()=>{c()},{once:!0}),{start:async({force:a=!1,path:d})=>{const p=r?.path??o;if(p!==void 0)throw new Error(`Already recording to ${p}`);o=d;try{return await s(d,{force:a})}finally{o=void 0}},stop:async()=>{if(!r)throw new Error("No video recording in progress");const{path:a}=r;return await i(r),{path:a}}}}async function vt(e,t){try{await ct(e.readable,t)}catch(n){f(`video capture ended with an error: ${String(n)}`)}}async function gt(){const{config:e,logs:t,store:n}=Ve();f(`recording to ${n.path}`);const{shutdown:r,signal:o}=rt(n);try{const{device:s,transport:i}=await Fe(e,n,{onClose:r,signal:o}),c=wt(s,n,{signal:o});await Je(s,e,n,{signal:o}),await Be(i,n,{signal:o});const a=await Ke(i,n,e.sessionId,{recorder:c,signal:o});f(`control socket listening at ${a}`),it(s,t.device,{signal:o}),f(`recording device logs to ${t.device}`),t.network&&(at(s,t.network,{signal:o}),f(`recording network events to ${t.network}`))}catch(s){if(o.aborted)return;const i=s instanceof Error?s.message:String(s);n.save({endedAt:new Date().toISOString(),endedReason:i,state:{message:i,phase:"error"}}),f(`error: ${i}`),process.exitCode=1}}B(),gt();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appetize/cli",
3
- "version": "0.15.2",
3
+ "version": "0.16.0",
4
4
  "description": "Run, inspect and control iOS and Android apps on Appetize cloud devices",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://appetize.io",
@@ -31,7 +31,8 @@
31
31
  "debug": "^4.4.3",
32
32
  "human-id": "^4.2.1",
33
33
  "json-rpc-2.0": "^1.8.0",
34
- "mediabunny": "^1.55.5",
35
- "sade": "^1.8.1"
34
+ "mediabunny": "^1.56.1",
35
+ "sade": "^1.8.1",
36
+ "ws": "^8.21.3"
36
37
  }
37
38
  }
@@ -10,7 +10,7 @@ description: >-
10
10
  or answering what is currently on screen — even if Appetize is not mentioned
11
11
  by name.
12
12
  metadata:
13
- cli-version: '0.15.2'
13
+ cli-version: '0.16.0'
14
14
  ---
15
15
 
16
16
  # Appetize
@@ -68,12 +68,14 @@ This blocks until the device is ready, then prints the session:
68
68
  "daemon": "/home/you/.appetize/cli/sessions/tidy-pandas-jump/daemon.log",
69
69
  "device": "/home/you/.appetize/cli/sessions/tidy-pandas-jump/device.log.jsonl"
70
70
  },
71
- "sessionId": "tidy-pandas-jump"
71
+ "sessionId": "tidy-pandas-jump",
72
+ "viewerUrl": "http://127.0.0.1:4321/"
72
73
  }
73
74
  ```
74
75
 
75
76
  - `sessionId` — what every later command takes
76
77
  - `adbSerial` — Android only; `adb connect` it to use adb
78
+ - `viewerUrl` — local browser viewer for co-driving
77
79
  - `baseUrl` — the streaming host serving the session
78
80
  - `controlSocket` — where the daemon listens
79
81
  - `logs.device` — the device's own logs; `logs.daemon` is the CLI's
@@ -46,11 +46,12 @@ appetize session start <device-id> <target> [options]
46
46
  | `--session-id` | Name the session; defaults to a generated 3-word id |
47
47
 
48
48
  Spawns a daemon that holds the session open and prints JSON on stdout. Waiting
49
- (the default) prints `{ adbSerial, baseUrl, controlSocket, logs, sessionId }`
49
+ (the default) prints
50
+ `{ adbSerial, baseUrl, controlSocket, logs, sessionId, viewerUrl }`
50
51
  once the device is ready; `--no-wait` prints `{ logs, sessionId }` immediately.
51
52
  `adbSerial` is present only for an Android session, and only while adb is
52
53
  available to it: `adb connect <adbSerial>` attaches to the device until the
53
- session ends. `logs`
54
+ session ends. `viewerUrl` opens the local browser viewer. `logs`
54
55
  carries a `device` and a `daemon` path, plus a `network` path — the JSONL capture
55
56
  of the app's traffic — when started with `--proxy` (or `--proxy intercept`). Progress phases are logged to stderr:
56
57
  `requesting`, `queued`, `starting`, `downloadingApp`, `installingApp`,
package/viewer.html ADDED
@@ -0,0 +1,2 @@
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>Appetize device</title><style>body,html{height:100%;margin:0;background:#111318}body{display:grid;place-items:center}canvas{max-width:100vw;max-height:100vh;background:#000;touch-action:none}</style></head><body><canvas aria-label="Device screen" tabindex="0"></canvas><script type="module">function nr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ne={exports:{}},Ke,wt;function ir(){if(wt)return Ke;wt=1;var t=1e3,e=t*60,r=e*60,n=r*24,s=n*7,i=n*365.25;Ke=function(w,p){p=p||{};var v=typeof w;if(v==="string"&&w.length>0)return o(w);if(v==="number"&&isFinite(w))return p.long?c(w):y(w);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(w))};function o(w){if(w=String(w),!(w.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(w);if(p){var v=parseFloat(p[1]),f=(p[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return v*i;case"weeks":case"week":case"w":return v*s;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*r;case"minutes":case"minute":case"mins":case"min":case"m":return v*e;case"seconds":case"second":case"secs":case"sec":case"s":return v*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function y(w){var p=Math.abs(w);return p>=n?Math.round(w/n)+"d":p>=r?Math.round(w/r)+"h":p>=e?Math.round(w/e)+"m":p>=t?Math.round(w/t)+"s":w+"ms"}function c(w){var p=Math.abs(w);return p>=n?h(w,p,n,"day"):p>=r?h(w,p,r,"hour"):p>=e?h(w,p,e,"minute"):p>=t?h(w,p,t,"second"):w+" ms"}function h(w,p,v,f){var C=p>=v*1.5;return Math.round(w/v)+" "+f+(C?"s":"")}return Ke}var Ve,vt;function sr(){if(vt)return Ve;vt=1;function t(e){n.debug=n,n.default=n,n.coerce=h,n.disable=y,n.enable=i,n.enabled=c,n.humanize=ir(),n.destroy=w,Object.keys(e).forEach(p=>{n[p]=e[p]}),n.names=[],n.skips=[],n.formatters={};function r(p){let v=0;for(let f=0;f<p.length;f++)v=(v<<5)-v+p.charCodeAt(f),v|=0;return n.colors[Math.abs(v)%n.colors.length]}n.selectColor=r;function n(p){let v,f=null,C,m;function N(...O){if(!N.enabled)return;const b=N,g=Number(new Date),I=g-(v||g);b.diff=I,b.prev=v,b.curr=g,v=g,O[0]=n.coerce(O[0]),typeof O[0]!="string"&&O.unshift("%O");let _=0;O[0]=O[0].replace(/%([a-zA-Z%])/g,(q,z)=>{if(q==="%%")return"%";_++;const X=n.formatters[z];if(typeof X=="function"){const L=O[_];q=X.call(b,L),O.splice(_,1),_--}return q}),n.formatArgs.call(b,O),(b.log||n.log).apply(b,O)}return N.namespace=p,N.useColors=n.useColors(),N.color=n.selectColor(p),N.extend=s,N.destroy=n.destroy,Object.defineProperty(N,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(C!==n.namespaces&&(C=n.namespaces,m=n.enabled(p)),m),set:O=>{f=O}}),typeof n.init=="function"&&n.init(N),N}function s(p,v){const f=n(this.namespace+(typeof v>"u"?":":v)+p);return f.log=this.log,f}function i(p){n.save(p),n.namespaces=p,n.names=[],n.skips=[];const v=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of v)f[0]==="-"?n.skips.push(f.slice(1)):n.names.push(f)}function o(p,v){let f=0,C=0,m=-1,N=0;for(;f<p.length;)if(C<v.length&&(v[C]===p[f]||v[C]==="*"))v[C]==="*"?(m=C,N=f,C++):(f++,C++);else if(m!==-1)C=m+1,N++,f=N;else return!1;for(;C<v.length&&v[C]==="*";)C++;return C===v.length}function y(){const p=[...n.names,...n.skips.map(v=>"-"+v)].join(",");return n.enable(""),p}function c(p){for(const v of n.skips)if(o(p,v))return!1;for(const v of n.names)if(o(p,v))return!0;return!1}function h(p){return p instanceof Error?p.stack||p.message:p}function w(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}return Ve=t,Ve}var gt;function or(){return gt||(gt=1,(function(t,e){e.formatArgs=n,e.save=s,e.load=i,e.useColors=r,e.storage=o(),e.destroy=(()=>{let c=!1;return()=>{c||(c=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let c;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(c=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(c[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(c){if(c[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+c[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const h="color: "+this.color;c.splice(1,0,h,"color: inherit");let w=0,p=0;c[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(w++,v==="%c"&&(p=w))}),c.splice(p,0,h)}e.log=console.debug||console.log||(()=>{});function s(c){try{c?e.storage.setItem("debug",c):e.storage.removeItem("debug")}catch{}}function i(){let c;try{c=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!c&&typeof process<"u"&&"env"in process&&(c=process.env.DEBUG),c}function o(){try{return localStorage}catch{}}t.exports=sr()(e);const{formatters:y}=t.exports;y.j=function(c){try{return JSON.stringify(c)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(Ne,Ne.exports)),Ne.exports}var ar=or(),Se=nr(ar),fe={},oe={},Ce={},mt;function _e(){return mt||(mt=1,(function(t){var e=Ce&&Ce.__extends||(function(){var f=function(C,m){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(N,O){N.__proto__=O}||function(N,O){for(var b in O)Object.prototype.hasOwnProperty.call(O,b)&&(N[b]=O[b])},f(C,m)};return function(C,m){if(typeof m!="function"&&m!==null)throw new TypeError("Class extends value "+String(m)+" is not a constructor or null");f(C,m);function N(){this.constructor=C}C.prototype=m===null?Object.create(m):(N.prototype=m.prototype,new N)}})();Object.defineProperty(t,"__esModule",{value:!0}),t.createJSONRPCNotification=t.createJSONRPCRequest=t.createJSONRPCSuccessResponse=t.createJSONRPCErrorResponse=t.JSONRPCErrorCode=t.JSONRPCErrorException=t.isJSONRPCResponses=t.isJSONRPCResponse=t.isJSONRPCRequests=t.isJSONRPCRequest=t.isJSONRPCID=t.JSONRPC=void 0,t.JSONRPC="2.0";var r=function(f){return typeof f=="string"||typeof f=="number"||f===null};t.isJSONRPCID=r;var n=function(f){return f.jsonrpc===t.JSONRPC&&f.method!==void 0&&f.result===void 0&&f.error===void 0};t.isJSONRPCRequest=n;var s=function(f){return Array.isArray(f)&&f.every(t.isJSONRPCRequest)};t.isJSONRPCRequests=s;var i=function(f){return f.jsonrpc===t.JSONRPC&&f.id!==void 0&&(f.result!==void 0||f.error!==void 0)};t.isJSONRPCResponse=i;var o=function(f){return Array.isArray(f)&&f.every(t.isJSONRPCResponse)};t.isJSONRPCResponses=o;var y=function(f,C,m){var N={code:f,message:C};return m!=null&&(N.data=m),N},c=(function(f){e(C,f);function C(m,N,O){var b=f.call(this,m)||this;return Object.setPrototypeOf(b,C.prototype),b.code=N,b.data=O,b}return C.prototype.toObject=function(){return y(this.code,this.message,this.data)},C})(Error);t.JSONRPCErrorException=c,(function(f){f[f.ParseError=-32700]="ParseError",f[f.InvalidRequest=-32600]="InvalidRequest",f[f.MethodNotFound=-32601]="MethodNotFound",f[f.InvalidParams=-32602]="InvalidParams",f[f.InternalError=-32603]="InternalError"})(t.JSONRPCErrorCode||(t.JSONRPCErrorCode={}));var h=function(f,C,m,N){return{jsonrpc:t.JSONRPC,id:f,error:y(C,m,N)}};t.createJSONRPCErrorResponse=h;var w=function(f,C){return{jsonrpc:t.JSONRPC,id:f,result:C??null}};t.createJSONRPCSuccessResponse=w;var p=function(f,C,m){return{jsonrpc:t.JSONRPC,id:f,method:C,params:m}};t.createJSONRPCRequest=p;var v=function(f,C){return{jsonrpc:t.JSONRPC,method:f,params:C}};t.createJSONRPCNotification=v})(Ce)),Ce}var Ee={},bt;function St(){return bt||(bt=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.DefaultErrorCode=void 0,Ee.DefaultErrorCode=0),Ee}var Ct;function cr(){if(Ct)return oe;Ct=1;var t=oe&&oe.__awaiter||function(o,y,c,h){function w(p){return p instanceof c?p:new c(function(v){v(p)})}return new(c||(c=Promise))(function(p,v){function f(N){try{m(h.next(N))}catch(O){v(O)}}function C(N){try{m(h.throw(N))}catch(O){v(O)}}function m(N){N.done?p(N.value):w(N.value).then(f,C)}m((h=h.apply(o,y||[])).next())})},e=oe&&oe.__generator||function(o,y){var c={label:0,sent:function(){if(p[0]&1)throw p[1];return p[1]},trys:[],ops:[]},h,w,p,v;return v={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(v[Symbol.iterator]=function(){return this}),v;function f(m){return function(N){return C([m,N])}}function C(m){if(h)throw new TypeError("Generator is already executing.");for(;v&&(v=0,m[0]&&(c=0)),c;)try{if(h=1,w&&(p=m[0]&2?w.return:m[0]?w.throw||((p=w.return)&&p.call(w),0):w.next)&&!(p=p.call(w,m[1])).done)return p;switch(w=0,p&&(m=[m[0]&2,p.value]),m[0]){case 0:case 1:p=m;break;case 4:return c.label++,{value:m[1],done:!1};case 5:c.label++,w=m[1],m=[0];continue;case 7:m=c.ops.pop(),c.trys.pop();continue;default:if(p=c.trys,!(p=p.length>0&&p[p.length-1])&&(m[0]===6||m[0]===2)){c=0;continue}if(m[0]===3&&(!p||m[1]>p[0]&&m[1]<p[3])){c.label=m[1];break}if(m[0]===6&&c.label<p[1]){c.label=p[1],p=m;break}if(p&&c.label<p[2]){c.label=p[2],c.ops.push(m);break}p[2]&&c.ops.pop(),c.trys.pop();continue}m=y.call(o,c)}catch(N){m=[6,N],w=0}finally{h=p=0}if(m[0]&5)throw m[1];return{value:m[0]?m[1]:void 0,done:!0}}};Object.defineProperty(oe,"__esModule",{value:!0}),oe.JSONRPCClient=void 0;var r=_e(),n=St(),s=(function(){function o(y,c){this._send=y,this.createID=c,this.idToResolveMap=new Map,this.id=0}return o.prototype._createID=function(){return this.createID?this.createID():++this.id},o.prototype.timeout=function(y,c){var h=this;c===void 0&&(c=function(v){return(0,r.createJSONRPCErrorResponse)(v,n.DefaultErrorCode,"Request timeout")});var w=function(v,f){var C=setTimeout(function(){v.forEach(function(m){var N=h.idToResolveMap.get(m);N&&(h.idToResolveMap.delete(m),N(c(m)))})},y);return f().then(function(m){return clearTimeout(C),m},function(m){return clearTimeout(C),Promise.reject(m)})},p=function(v,f){var C=(Array.isArray(v)?v:[v]).map(function(m){return m.id}).filter(i);return w(C,function(){return h.requestAdvanced(v,f)})};return{request:function(v,f,C){var m=h._createID();return w([m],function(){return h.requestWithID(v,f,C,m)})},requestAdvanced:function(v,f){return p(v,f)}}},o.prototype.request=function(y,c,h){return this.requestWithID(y,c,h,this._createID())},o.prototype.requestWithID=function(y,c,h,w){return t(this,void 0,void 0,function(){var p,v;return e(this,function(f){switch(f.label){case 0:return p=(0,r.createJSONRPCRequest)(w,y,c),[4,this.requestAdvanced(p,h)];case 1:return v=f.sent(),v.result!==void 0&&!v.error?[2,v.result]:v.result===void 0&&v.error?[2,Promise.reject(new r.JSONRPCErrorException(v.error.message,v.error.code,v.error.data))]:[2,Promise.reject(new Error("An unexpected error occurred"))]}})})},o.prototype.requestAdvanced=function(y,c){var h=this,w=Array.isArray(y);Array.isArray(y)||(y=[y]);var p=y.filter(function(C){return i(C.id)}),v=p.map(function(C){return new Promise(function(m){return h.idToResolveMap.set(C.id,m)})}),f=Promise.all(v).then(function(C){return w||!C.length?C:C[0]});return this.send(w?y:y[0],c).then(function(){return f},function(C){return p.forEach(function(m){h.receive((0,r.createJSONRPCErrorResponse)(m.id,n.DefaultErrorCode,C&&C.message||"Failed to send a request"))}),f})},o.prototype.notify=function(y,c,h){var w=(0,r.createJSONRPCNotification)(y,c);this.send(w,h).then(void 0,function(){})},o.prototype.send=function(y,c){return t(this,void 0,void 0,function(){return e(this,function(h){return[2,this._send(y,c)]})})},o.prototype.rejectAllPendingRequests=function(y){this.idToResolveMap.forEach(function(c,h){return c((0,r.createJSONRPCErrorResponse)(h,n.DefaultErrorCode,y))}),this.idToResolveMap.clear()},o.prototype.receive=function(y){var c=this;Array.isArray(y)||(y=[y]),y.forEach(function(h){var w=c.idToResolveMap.get(h.id);w&&(c.idToResolveMap.delete(h.id),w(h))})},o})();oe.JSONRPCClient=s;var i=function(o){return o!=null};return oe}var We={},Et;function lr(){return Et||(Et=1,Object.defineProperty(We,"__esModule",{value:!0})),We}var ne={},Rt;function ur(){return Rt||(Rt=1,(function(t){var e=ne&&ne.__assign||function(){return e=Object.assign||function(O){for(var b,g=1,I=arguments.length;g<I;g++){b=arguments[g];for(var _ in b)Object.prototype.hasOwnProperty.call(b,_)&&(O[_]=b[_])}return O},e.apply(this,arguments)},r=ne&&ne.__awaiter||function(O,b,g,I){function _(M){return M instanceof g?M:new g(function(q){q(M)})}return new(g||(g=Promise))(function(M,q){function z(Z){try{L(I.next(Z))}catch(ve){q(ve)}}function X(Z){try{L(I.throw(Z))}catch(ve){q(ve)}}function L(Z){Z.done?M(Z.value):_(Z.value).then(z,X)}L((I=I.apply(O,b||[])).next())})},n=ne&&ne.__generator||function(O,b){var g={label:0,sent:function(){if(M[0]&1)throw M[1];return M[1]},trys:[],ops:[]},I,_,M,q;return q={next:z(0),throw:z(1),return:z(2)},typeof Symbol=="function"&&(q[Symbol.iterator]=function(){return this}),q;function z(L){return function(Z){return X([L,Z])}}function X(L){if(I)throw new TypeError("Generator is already executing.");for(;q&&(q=0,L[0]&&(g=0)),g;)try{if(I=1,_&&(M=L[0]&2?_.return:L[0]?_.throw||((M=_.return)&&M.call(_),0):_.next)&&!(M=M.call(_,L[1])).done)return M;switch(_=0,M&&(L=[L[0]&2,M.value]),L[0]){case 0:case 1:M=L;break;case 4:return g.label++,{value:L[1],done:!1};case 5:g.label++,_=L[1],L=[0];continue;case 7:L=g.ops.pop(),g.trys.pop();continue;default:if(M=g.trys,!(M=M.length>0&&M[M.length-1])&&(L[0]===6||L[0]===2)){g=0;continue}if(L[0]===3&&(!M||L[1]>M[0]&&L[1]<M[3])){g.label=L[1];break}if(L[0]===6&&g.label<M[1]){g.label=M[1],M=L;break}if(M&&g.label<M[2]){g.label=M[2],g.ops.push(L);break}M[2]&&g.ops.pop(),g.trys.pop();continue}L=b.call(O,g)}catch(Z){L=[6,Z],_=0}finally{I=M=0}if(L[0]&5)throw L[1];return{value:L[0]?L[1]:void 0,done:!0}}},s=ne&&ne.__spreadArray||function(O,b,g){if(g||arguments.length===2)for(var I=0,_=b.length,M;I<_;I++)(M||!(I in b))&&(M||(M=Array.prototype.slice.call(b,0,I)),M[I]=b[I]);return O.concat(M||Array.prototype.slice.call(b))};Object.defineProperty(t,"__esModule",{value:!0}),t.JSONRPCServer=t.createMethodNotFoundResponse=t.createInvalidRequestResponse=void 0;var i=_e(),o=St(),y=function(){return(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.ParseError,"Parse error")},c=function(O){return(0,i.createJSONRPCErrorResponse)((0,i.isJSONRPCID)(O.id)?O.id:null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")};t.createInvalidRequestResponse=c;var h=function(O){return(0,i.createJSONRPCErrorResponse)(O,i.JSONRPCErrorCode.MethodNotFound,"Method not found")};t.createMethodNotFoundResponse=h;var w=(function(){function O(b){b===void 0&&(b={});var g;this.mapErrorToJSONRPCErrorResponse=C,this.handleMethodNotFound=m,this.nameToMethodDictionary={},this.middleware=null,this.errorListener=(g=b.errorListener)!==null&&g!==void 0?g:console.warn}return O.prototype.hasMethod=function(b){return!!this.nameToMethodDictionary[b]},O.prototype.addMethod=function(b,g){this.addMethodAdvanced(b,this.toJSONRPCMethod(g))},O.prototype.removeMethod=function(b){delete this.nameToMethodDictionary[b]},O.prototype.toJSONRPCMethod=function(b){return function(g,I){var _=b(g.params,I);return Promise.resolve(_).then(function(M){return f(g.id,M)})}},O.prototype.addMethodAdvanced=function(b,g){var I;this.nameToMethodDictionary=e(e({},this.nameToMethodDictionary),(I={},I[b]=g,I))},O.prototype.receiveJSON=function(b,g){var I=this.tryParseRequestJSON(b);return I?this.receive(I,g):Promise.resolve(y())},O.prototype.tryParseRequestJSON=function(b){try{return JSON.parse(b)}catch{return null}},O.prototype.receive=function(b,g){return Array.isArray(b)?this.receiveMultiple(b,g):this.receiveSingle(b,g)},O.prototype.receiveMultiple=function(b,g){return r(this,void 0,void 0,function(){var I,_=this;return n(this,function(M){switch(M.label){case 0:return b.length===0?[2,(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")]:[4,Promise.all(b.map(function(q){return _.receiveSingle(q,g)}))];case 1:return I=M.sent().filter(p),I.length===1?[2,I[0]]:I.length?[2,I]:[2,null]}})})},O.prototype.receiveSingle=function(b,g){return r(this,void 0,void 0,function(){var I,_;return n(this,function(M){switch(M.label){case 0:return I=this.nameToMethodDictionary[b.method],(0,i.isJSONRPCRequest)(b)?[3,1]:[2,(0,t.createInvalidRequestResponse)(b)];case 1:return[4,this.callMethod(I,b,g)];case 2:return _=M.sent(),[2,N(b,_)]}})})},O.prototype.applyMiddleware=function(){for(var b=[],g=0;g<arguments.length;g++)b[g]=arguments[g];this.middleware?this.middleware=this.combineMiddlewares(s([this.middleware],b,!0)):this.middleware=this.combineMiddlewares(b)},O.prototype.combineMiddlewares=function(b){return b.length?b.reduce(this.middlewareReducer):null},O.prototype.middlewareReducer=function(b,g){return function(I,_,M){return b(function(q,z){return g(I,q,z)},_,M)}},O.prototype.callMethod=function(b,g,I){var _=this,M=function(z,X){return b?b(z,X):_.handleMethodNotFound(z,X)},q=function(z){return _.errorListener('An unexpected error occurred while executing "'.concat(g.method,'" JSON-RPC method:'),z),Promise.resolve(_.mapErrorToJSONRPCErrorResponseIfNecessary(g.id,z))};try{return(this.middleware||v)(M,g,I).then(void 0,q)}catch(z){return q(z)}},O.prototype.mapErrorToJSONRPCErrorResponseIfNecessary=function(b,g){return b!==void 0?this.mapErrorToJSONRPCErrorResponse(b,g):null},O})();t.JSONRPCServer=w;var p=function(O){return O!==null},v=function(O,b,g){return O(b,g)},f=function(O,b){return O!==void 0?(0,i.createJSONRPCSuccessResponse)(O,b):null},C=function(O,b){var g,I=(g=b?.message)!==null&&g!==void 0?g:"An unexpected error occurred",_=o.DefaultErrorCode,M;return b instanceof i.JSONRPCErrorException&&(_=b.code,M=b.data),(0,i.createJSONRPCErrorResponse)(O,_,I,M)},m=function(O){return r(void 0,void 0,void 0,function(){return n(this,function(b){return O.id!==void 0?[2,(0,t.createMethodNotFoundResponse)(O.id)]:[2,null]})})},N=function(O,b){return b||(O.id!==void 0?(0,i.createJSONRPCErrorResponse)(O.id,i.JSONRPCErrorCode.InternalError,"Internal error"):null)}})(ne)),ne}var ae={},Ot;function fr(){if(Ot)return ae;Ot=1;var t=ae&&ae.__awaiter||function(s,i,o,y){function c(h){return h instanceof o?h:new o(function(w){w(h)})}return new(o||(o=Promise))(function(h,w){function p(C){try{f(y.next(C))}catch(m){w(m)}}function v(C){try{f(y.throw(C))}catch(m){w(m)}}function f(C){C.done?h(C.value):c(C.value).then(p,v)}f((y=y.apply(s,i||[])).next())})},e=ae&&ae.__generator||function(s,i){var o={label:0,sent:function(){if(h[0]&1)throw h[1];return h[1]},trys:[],ops:[]},y,c,h,w;return w={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(w[Symbol.iterator]=function(){return this}),w;function p(f){return function(C){return v([f,C])}}function v(f){if(y)throw new TypeError("Generator is already executing.");for(;w&&(w=0,f[0]&&(o=0)),o;)try{if(y=1,c&&(h=f[0]&2?c.return:f[0]?c.throw||((h=c.return)&&h.call(c),0):c.next)&&!(h=h.call(c,f[1])).done)return h;switch(c=0,h&&(f=[f[0]&2,h.value]),f[0]){case 0:case 1:h=f;break;case 4:return o.label++,{value:f[1],done:!1};case 5:o.label++,c=f[1],f=[0];continue;case 7:f=o.ops.pop(),o.trys.pop();continue;default:if(h=o.trys,!(h=h.length>0&&h[h.length-1])&&(f[0]===6||f[0]===2)){o=0;continue}if(f[0]===3&&(!h||f[1]>h[0]&&f[1]<h[3])){o.label=f[1];break}if(f[0]===6&&o.label<h[1]){o.label=h[1],h=f;break}if(h&&o.label<h[2]){o.label=h[2],o.ops.push(f);break}h[2]&&o.ops.pop(),o.trys.pop();continue}f=i.call(s,o)}catch(C){f=[6,C],c=0}finally{y=h=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}};Object.defineProperty(ae,"__esModule",{value:!0}),ae.JSONRPCServerAndClient=void 0;var r=_e(),n=(function(){function s(i,o,y){y===void 0&&(y={});var c;this.server=i,this.client=o,this.errorListener=(c=y.errorListener)!==null&&c!==void 0?c:console.warn}return s.prototype.applyServerMiddleware=function(){for(var i,o=[],y=0;y<arguments.length;y++)o[y]=arguments[y];(i=this.server).applyMiddleware.apply(i,o)},s.prototype.hasMethod=function(i){return this.server.hasMethod(i)},s.prototype.addMethod=function(i,o){this.server.addMethod(i,o)},s.prototype.addMethodAdvanced=function(i,o){this.server.addMethodAdvanced(i,o)},s.prototype.removeMethod=function(i){this.server.removeMethod(i)},s.prototype.timeout=function(i){return this.client.timeout(i)},s.prototype.request=function(i,o,y){return this.client.request(i,o,y)},s.prototype.requestAdvanced=function(i,o){return this.client.requestAdvanced(i,o)},s.prototype.notify=function(i,o,y){this.client.notify(i,o,y)},s.prototype.rejectAllPendingRequests=function(i){this.client.rejectAllPendingRequests(i)},s.prototype.receiveAndSend=function(i,o,y){return t(this,void 0,void 0,function(){var c,h;return e(this,function(w){switch(w.label){case 0:return(0,r.isJSONRPCResponse)(i)||(0,r.isJSONRPCResponses)(i)?(this.client.receive(i),[3,4]):[3,1];case 1:return(0,r.isJSONRPCRequest)(i)||(0,r.isJSONRPCRequests)(i)?[4,this.server.receive(i,o)]:[3,3];case 2:return c=w.sent(),c?[2,this.client.send(c,y)]:[3,4];case 3:return h="Received an invalid JSON-RPC message",this.errorListener(h,i),[2,Promise.reject(new Error(h))];case 4:return[2]}})})},s})();return ae.JSONRPCServerAndClient=n,ae}var At;function dr(){return At||(At=1,(function(t){var e=fe&&fe.__createBinding||(Object.create?(function(n,s,i,o){o===void 0&&(o=i);var y=Object.getOwnPropertyDescriptor(s,i);(!y||("get"in y?!s.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return s[i]}}),Object.defineProperty(n,o,y)}):(function(n,s,i,o){o===void 0&&(o=i),n[o]=s[i]})),r=fe&&fe.__exportStar||function(n,s){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(s,i)&&e(s,n,i)};Object.defineProperty(t,"__esModule",{value:!0}),r(cr(),t),r(lr(),t),r(_e(),t),r(ur(),t),r(fr(),t)})(fe)),fe}var ke=dr();class hr{#e=new EventTarget;addEventListener(e,r,n){return this.#e.addEventListener(e,r,n),()=>{this.#e.removeEventListener(e,r,n)}}removeEventListener(e,r,n){this.#e.removeEventListener(e,r,n)}dispatchEvent(e){return this.#e.dispatchEvent(e)}}const j=Symbol.for("@appetizeio/rpc:rpcMethods");class pr extends hr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(new CloseEvent("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}const Mt=Se("appetize.io:error:rpc");function $e(t,e){const r=new ke.JSONRPCServerAndClient(new ke.JSONRPCServer({errorListener:Mt}),wr(t),{errorListener:Mt}),n=t[j].addEventListener("message",({detail:i})=>{r.receiveAndSend(i)}),s=t[j].addEventListener("close",()=>{n(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const i in e){const o=e[i];o&&r.addMethod(i,o.bind(e))}return{rpc:r,unsub:()=>{n(),s()}}}function yr(t,e){const{rpc:r,unsub:n}=$e(t,e);return{client:r.client,unsub:n}}function Fe(t,e){const r=t[j].addEventListener("message",({detail:s})=>{if("method"in s)try{e({method:s.method,param:s.params})}catch{}}),n=t[j].addEventListener("close",r,{once:!0});return()=>{r(),n()}}function wr(t){return new ke.JSONRPCClient(t[j].send.bind(t[j]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}const vr=(...t)=>yr(...t),He=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],gr=33333,mr=[[99,10],[396,11],[792,21],[1620,22],[3600,31],[5120,32],[8192,40],[8704,42],[22080,50],[36864,51],[139264,60]],br=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Sr=new Set(He);class Cr{#e;#r=!1;#t;#n;#i;#s;#o;#a;#c;#l=0;#u=!1;constructor({canvas:e,context:r,onClose:n,onError:s,signal:i,stream:o}){this.#e=e,this.#t=r,this.#s=n,this.#o=s,this.#a=i,this.#c=o,this.#a?.addEventListener("abort",this.close,{once:!0}),this.#p()}close=()=>{this.#r||(this.#r=!0,this.#f(),this.#n=void 0,this.#c.close(),this.#a?.removeEventListener("abort",this.close),this.#s?.())};#f(){this.#n&&this.#n.state!=="closed"&&this.#n.close()}#h(e){const r=Ar(e.data,e.width,e.height),n=`${r}:${String(e.width)}x${String(e.height)}`;this.#n&&this.#i===n||(this.#f(),this.#i=n,this.#e.height=e.height,this.#e.width=e.width,this.#n=new VideoDecoder({error:this.#d,output:s=>{this.#t.drawImage(s,0,0,this.#e.width,this.#e.height),s.close()}}),this.#n.configure({codec:r,codedHeight:e.height,codedWidth:e.width,hardwareAcceleration:"no-preference",optimizeForLatency:!0}))}async#p(){try{for await(const e of this.#c){if(this.#r)return;if(e.data.byteLength!==0){if(e.type==="key"&&e.codec==="jpeg"){this.#u=!1,this.#i=void 0,this.#f(),this.#n=void 0,await this.#y(e);continue}if(!(e.type==="delta"&&this.#u)&&(e.type==="key"&&(this.#u=!1,this.#h(e)),this.#n?.state==="configured")){if(this.#n.decodeQueueSize>2&&e.type==="delta"){this.#d();continue}this.#n.decode(new EncodedVideoChunk({data:new Uint8Array(e.data),timestamp:this.#l,type:e.type})),this.#l+=gr}}}}catch(e){this.#r||this.#o?.(e)}finally{this.close()}}#d=()=>{this.#u=!0,this.#i=void 0,this.#f(),this.#n=void 0,this.#c.requestKeyFrame()};async#y(e){const r=await createImageBitmap(new Blob([new Uint8Array(e.data)],{type:"image/jpeg"}));this.#e.height=e.height,this.#e.width=e.width,this.#t.drawImage(r,0,0,e.width,e.height),r.close()}}function Er(t,e,{signal:r}={}){if(r?.aborted)return()=>{};const n=i=>{i.altKey||i.ctrlKey||i.metaKey||!Mr(i.key)||(i.preventDefault(),t.keyboard.press(i.key))},s=()=>{e.removeEventListener("keydown",n),r?.removeEventListener("abort",s)};return e.addEventListener("keydown",n),r?.addEventListener("abort",s,{once:!0}),s}function Rr(t,e,{signal:r}={}){let n,s;const i=h=>{n===void 0&&(h.preventDefault(),n=h.pointerId,s=Ge(e,h),e.focus(),e.setPointerCapture(h.pointerId),t.touch.down(s.x,s.y))},o=h=>{h.pointerId===n&&(h.preventDefault(),s=Ge(e,h),t.touch.move(s.x,s.y))},y=h=>{if(h.pointerId!==n)return;h.preventDefault();const w=Ge(e,h);t.touch.up(w.x,w.y),It(e,h.pointerId),n=void 0,s=void 0},c=()=>{n!==void 0&&It(e,n),s&&t.touch.up(s.x,s.y),n=void 0,s=void 0,e.removeEventListener("pointercancel",y),e.removeEventListener("pointerdown",i),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",y),r?.removeEventListener("abort",c)};return r?.aborted||(e.addEventListener("pointercancel",y),e.addEventListener("pointerdown",i),e.addEventListener("pointermove",o),e.addEventListener("pointerup",y),r?.addEventListener("abort",c,{once:!0})),c}async function Or(t,e,{onClose:r,onError:n,signal:s}={}){const i=e.getContext("2d");if(!i)throw new Error("Canvas context unavailable");s?.throwIfAborted();const o=await t.video.createStream({signal:s});return{close:new Cr({canvas:e,context:i,onClose:r,onError:n,signal:s,stream:o}).close}}function Pt(t){return Math.max(0,Math.min(1,t))}function Ar(t,e,r){const n=Math.ceil(e/16)*Math.ceil(r/16),s=mr.find(([i])=>n<=i)?.[1]??62;for(let i=0;i<t.length-7;i+=1){const o=t[i]===0&&t[i+1]===0&&t[i+2]===1,y=t[i]===0&&t[i+1]===0&&t[i+2]===0&&t[i+3]===1,c=o?i+3:y?i+4:-1;if(c>=0&&(t[c]&31)===7)return`avc1.${[t[c+1],t[c+2],Math.max(t[c+3],s)].map(h=>h.toString(16).padStart(2,"0")).join("")}`}return"avc1.42e01e"}function Mr(t){return Array.from(br.segment(t)).length===1||Sr.has(t)}function Ge(t,e){const r=t.getBoundingClientRect();return{x:Pt((e.clientX-r.left)/r.width),y:Pt((e.clientY-r.top)/r.height)}}function It(t,e){t.hasPointerCapture(e)&&t.releasePointerCapture(e)}let Ze;try{Ze=new TextDecoder}catch{}let A,Q,d=0;const Pr=105,Ir=57342,Nr=57343,Nt=57337,_t=6,ge={};let Re=11281e4,ce=1681e4,J={},K,Le,xe=0,Oe=0,W,te,V=[],Ye=[],Y,G,Ae,kt={useRecords:!1,mapsAsObjects:!0},Me=!1,Ft=2;try{new Function("")}catch{Ft=1/0}class Ie{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,n]of Object.entries(e.keyMap))this.mapKey.set(n,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[n,s]of Object.entries(e))r.set(this._keyMap.hasOwnProperty(n)?this._keyMap[n]:n,s);return r}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[n,s]of Object.entries(this._keyMap))this._mapKey.set(s,n)}let r={};return e.forEach((n,s)=>r[re(this._mapKey.has(s)?this._mapKey.get(s):s)]=n),r}mapDecode(e,r){let n=this.decode(e);return this._keyMap&&n.constructor.name==="Array"?n.map(s=>this.decodeKeys(s)):n}decode(e,r){if(A)return Dt(()=>(rt(),this?this.decode(e,r):Ie.prototype.decode.call(kt,e,r)));Q=r>-1?r:e.length,d=0,Oe=0,Le=null,W=null,A=e;try{G=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(n){throw A=null,e instanceof Uint8Array?n:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof Ie){if(J=this,Y=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return K=this.structures,Te();(!K||K.length>0)&&(K=[])}else J=kt,(!K||K.length>0)&&(K=[]),Y=null;return Te()}decodeMultiple(e,r){let n,s=0;try{let i=e.length;Me=!0;let o=this?this.decode(e,i):it.decode(e,i);if(r){if(r(o)===!1)return;for(;d<i;)if(s=d,r(Te())===!1)return}else{for(n=[o];d<i;)s=d,n.push(Te());return n}}catch(i){throw i.lastPosition=s,i.values=n,i}finally{Me=!1,rt()}}}function Te(){try{let t=U();if(W){if(d>=W.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}d=W.postBundlePosition,W=null}if(d==Q)K=null,A=null,te&&(te=null);else if(d>Q){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Me)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw rt(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function de(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function U(){if(!(d<Q))throw de();let t=A[d++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(d>=Q)throw de();t=A[d++];break;case 25:if(e==7)return Lr();t=G.getUint16(d),d+=2;break;case 26:if(e==7){let r=G.getFloat32(d);if(J.useFloat32>2){let n=nt[(A[d]&127)<<1|A[d+1]>>7];return d+=4,(n*r+(r>0?.5:-.5)>>0)/n}return d+=4,r}if(t=G.getUint32(d),d+=4,e===1)return-1-t;break;case 27:if(e==7){let r=G.getFloat64(d);return d+=8,r}if(e>1){if(G.getUint32(d)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=G.getUint32(d+4)}else J.int64AsNumber?(t=G.getUint32(d)*4294967296,t+=G.getUint32(d+4)):t=G.getBigUint64(d);d+=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=[],n,s=0;for(;(n=U())!=ge;){if(s>=Re)throw new Error(`Array length exceeds ${Re}`);r[s++]=n}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let i;if(J.mapsAsObjects){let o={},y=0;if(J.keyMap)for(;(i=U())!=ge;){if(y++>=ce)throw new Error(`Property count exceeds ${ce}`);o[re(J.decodeKey(i))]=U()}else for(;(i=U())!=ge;){if(y++>=ce)throw new Error(`Property count exceeds ${ce}`);o[re(i)]=U()}return o}else{Ae&&(J.mapsAsObjects=!0,Ae=!1);let o=new Map;if(J.keyMap){let y=0;for(;(i=U())!=ge;){if(y++>=ce)throw new Error(`Map size exceeds ${ce}`);o.set(J.decodeKey(i),U())}}else{let y=0;for(;(i=U())!=ge;){if(y++>=ce)throw new Error(`Map size exceeds ${ce}`);o.set(i,U())}}return o}case 7:return ge;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:return Fr(t);case 3:if(Oe>=d)return Le.slice(d-xe,(d+=t)-xe);if(Oe==0&&Q<140&&t<32){let s=t<16?xt(t):kr(t);if(s!=null)return s}return _r(t);case 4:if(t>=Re)throw new Error(`Array length exceeds ${Re}`);if(t>Q-d)throw de();let r=new Array(t);for(let s=0;s<t;s++)r[s]=U();return r;case 5:if(t>=ce)throw new Error(`Map size exceeds ${Re}`);if(t>(Q-d)/2)throw de();if(J.mapsAsObjects){let s={};if(J.keyMap)for(let i=0;i<t;i++)s[re(J.decodeKey(U()))]=U();else for(let i=0;i<t;i++)s[re(U())]=U();return s}else{Ae&&(J.mapsAsObjects=!0,Ae=!1);let s=new Map;if(J.keyMap)for(let i=0;i<t;i++)s.set(J.decodeKey(U()),U());else for(let i=0;i<t;i++)s.set(U(),U());return s}case 6:if(t>=Nt){let s=K[t&8191];if(s)return s.read||(s.read=Xe(s)),s.read();if(t<65536){if(t==Nr){let i=be(),o=U(),y=U();et(o,y);let c={};if(J.keyMap)for(let h=2;h<i;h++){let w=J.decodeKey(y[h-2]);c[re(w)]=U()}else for(let h=2;h<i;h++){let w=y[h-2];c[re(w)]=U()}return c}else if(t==Ir){let i=be(),o=U();for(let y=2;y<i;y++)et(o++,U());return U()}else if(t==Nt)return jr();if(J.getShared&&(tt(),s=K[t&8191],s))return s.read||(s.read=Xe(s)),s.read()}}let n=V[t];if(n)return n.handlesRead?n(U):n(U());{let s=U();for(let i=0;i<Ye.length;i++){let o=Ye[i](t,s);if(o!==void 0)return o}return new he(s,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let s=(Y||pe())[t];if(s!==void 0)return s;throw new Error("Unknown token "+t)}default:throw isNaN(t)?de():new Error("Unknown CBOR token "+t)}}const Lt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Xe(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=A[d++];if(r=r&31,r>23)switch(r){case 24:r=A[d++];break;case 25:r=G.getUint16(d),d+=2;break;case 26:r=G.getUint32(d),d+=4;break;default:throw new Error("Expected array header, but got "+A[d-1])}let n=this.compiledReader;for(;n;){if(n.propertyCount===r)return n(U);n=n.next}if(this.slowReads++>=Ft){let i=this.length==r?this:this.slice(0,r);return n=J.keyMap?new Function("r","return {"+i.map(o=>J.decodeKey(o)).map(o=>Lt.test(o)?re(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"):new Function("r","return {"+i.map(o=>Lt.test(o)?re(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"),this.compiledReader&&(n.next=this.compiledReader),n.propertyCount=r,this.compiledReader=n,n(U)}let s={};if(J.keyMap)for(let i=0;i<r;i++)s[re(J.decodeKey(this[i]))]=U();else for(let i=0;i<r;i++)s[re(this[i])]=U();return s}return t.slowReads=0,e}function re(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 _r=Qe;function Qe(t){let e;if(t<16&&(e=xt(t)))return e;if(t>64&&Ze)return Ze.decode(A.subarray(d,d+=t));const r=d+t,n=[];for(e="";d<r;){const s=A[d++];if((s&128)===0)n.push(s);else if((s&224)===192)if(s<194||d>=r||(A[d]&192)!==128)n.push(65533);else{const i=A[d++]&63;n.push((s&31)<<6|i)}else if((s&240)===224){const i=d<r?A[d]:0;if(d>=r||(i&192)!==128||s===224&&i<160||s===237&&i>=160)n.push(65533);else if(d++,d>=r||(A[d]&192)!==128)n.push(65533);else{const o=A[d++]&63;n.push((s&31)<<12|(i&63)<<6|o)}}else if((s&248)===240){const i=d<r?A[d]:0;if(s>244||d>=r||(i&192)!==128||s===240&&i<144||s===244&&i>=144)n.push(65533);else if(d++,d>=r||(A[d]&192)!==128)n.push(65533);else{const o=A[d++]&63;if(d>=r||(A[d]&192)!==128)n.push(65533);else{const y=A[d++]&63;let c=(s&7)<<18|(i&63)<<12|o<<6|y;c-=65536,n.push(c>>>10&1023|55296),n.push(56320|c&1023)}}}else n.push(65533);n.length>=4096&&(e+=H.apply(String,n),n.length=0)}return n.length>0&&(e+=H.apply(String,n)),e}let H=String.fromCharCode;function kr(t){let e=d,r=new Array(t);for(let n=0;n<t;n++){const s=A[d++];if((s&128)>0){d=e;return}r[n]=s}return H.apply(String,r)}function xt(t){if(t<4)if(t<2){if(t===0)return"";{let e=A[d++];if((e&128)>1){d-=1;return}return H(e)}}else{let e=A[d++],r=A[d++];if((e&128)>0||(r&128)>0){d-=2;return}if(t<3)return H(e,r);let n=A[d++];if((n&128)>0){d-=3;return}return H(e,r,n)}else{let e=A[d++],r=A[d++],n=A[d++],s=A[d++];if((e&128)>0||(r&128)>0||(n&128)>0||(s&128)>0){d-=4;return}if(t<6){if(t===4)return H(e,r,n,s);{let i=A[d++];if((i&128)>0){d-=5;return}return H(e,r,n,s,i)}}else if(t<8){let i=A[d++],o=A[d++];if((i&128)>0||(o&128)>0){d-=6;return}if(t<7)return H(e,r,n,s,i,o);let y=A[d++];if((y&128)>0){d-=7;return}return H(e,r,n,s,i,o,y)}else{let i=A[d++],o=A[d++],y=A[d++],c=A[d++];if((i&128)>0||(o&128)>0||(y&128)>0||(c&128)>0){d-=8;return}if(t<10){if(t===8)return H(e,r,n,s,i,o,y,c);{let h=A[d++];if((h&128)>0){d-=9;return}return H(e,r,n,s,i,o,y,c,h)}}else if(t<12){let h=A[d++],w=A[d++];if((h&128)>0||(w&128)>0){d-=10;return}if(t<11)return H(e,r,n,s,i,o,y,c,h,w);let p=A[d++];if((p&128)>0){d-=11;return}return H(e,r,n,s,i,o,y,c,h,w,p)}else{let h=A[d++],w=A[d++],p=A[d++],v=A[d++];if((h&128)>0||(w&128)>0||(p&128)>0||(v&128)>0){d-=12;return}if(t<14){if(t===12)return H(e,r,n,s,i,o,y,c,h,w,p,v);{let f=A[d++];if((f&128)>0){d-=13;return}return H(e,r,n,s,i,o,y,c,h,w,p,v,f)}}else{let f=A[d++],C=A[d++];if((f&128)>0||(C&128)>0){d-=14;return}if(t<15)return H(e,r,n,s,i,o,y,c,h,w,p,v,f,C);let m=A[d++];if((m&128)>0){d-=15;return}return H(e,r,n,s,i,o,y,c,h,w,p,v,f,C,m)}}}}}function Fr(t){return J.copyBuffers?Uint8Array.prototype.slice.call(A,d,d+=t):A.subarray(d,d+=t)}let Tt=new Float32Array(1),Je=new Uint8Array(Tt.buffer,0,4);function Lr(){let t=A[d++],e=A[d++],r=(t&127)>>2;if(r===31)return e||t&3?NaN:t&128?-1/0:1/0;if(r===0){let n=((t&3)<<8|e)/16777216;return t&128?-n:n}return Je[3]=t&128|(r>>1)+56,Je[2]=(t&7)<<5|e>>3,Je[1]=e<<5,Je[0]=0,Tt[0]}new Array(4096);class he{constructor(e,r){this.value=e,this.tag=r}}V[0]=t=>new Date(t),V[1]=t=>new Date(Math.round(t*1e3)),V[2]=t=>{let e=BigInt(0);for(let r=0,n=t.byteLength;r<n;r++)e=BigInt(t[r])+(e<<BigInt(8));return e},V[3]=t=>BigInt(-1)-V[2](t),V[4]=t=>+(t[1]+"e"+t[0]),V[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const et=(t,e)=>{t=t-57344;let r=K[t];r&&r.isShared&&((K.restoreStructures||(K.restoreStructures=[]))[t]=r),K[t]=e,e.read=Xe(e)};V[Pr]=t=>{let e=t.length,r=t[1];et(t[0],r);let n={};for(let s=2;s<e;s++){let i=r[s-2];n[re(i)]=t[s]}return n},V[14]=t=>W?W[0].slice(W.position0,W.position0+=t):new he(t,14),V[15]=t=>W?W[1].slice(W.position1,W.position1+=t):new he(t,15);let xr={Error,RegExp};V[27]=t=>(xr[t[0]]||Error)(t[1],t[2]);const Jt=t=>{if(A[d++]!=132){let r=new Error("Packed values structure must be followed by a 4 element array");throw A.length<d&&(r.incomplete=!0),r}let e=t();if(!e||!e.length){let r=new Error("Packed values structure must be followed by a 4 element array");throw r.incomplete=!0,r}return Y=Y?e.concat(Y.slice(e.length)):e,Y.prefixes=t(),Y.suffixes=t(),t()};Jt.handlesRead=!0,V[51]=Jt,V[_t]=t=>{if(!Y)if(J.getShared)tt();else return new he(t,_t);if(typeof t=="number")return Y[16+(t>=0?2*t:-2*t-1)];let e=new Error("No support for non-integer packed references yet");throw t===void 0&&(e.incomplete=!0),e},V[28]=t=>{te||(te=new Map,te.id=0);let e=te.id++,r=d,n=A[d],s;n>>5==4?s=[]:s={};let i={target:s};te.set(e,i);let o=t();return i.used?(Object.getPrototypeOf(s)!==Object.getPrototypeOf(o)&&(d=r,s=o,te.set(e,{target:s}),o=t()),Object.assign(s,o)):(i.target=o,o)},V[28].handlesRead=!0,V[29]=t=>{let e=te.get(t);return e.used=!0,e.target},V[258]=t=>new Set(t),(V[259]=t=>(J.mapsAsObjects&&(J.mapsAsObjects=!1,Ae=!0),t())).handlesRead=!0;function me(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function pe(){if(!Y)if(J.getShared)tt();else throw new Error("No packed values available");return Y}const Tr=1399353956;Ye.push((t,e)=>{if(t>=225&&t<=255)return me(pe().prefixes[t-224],e);if(t>=28704&&t<=32767)return me(pe().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return me(pe().prefixes[t-1879048192],e);if(t>=216&&t<=223)return me(e,pe().suffixes[t-216]);if(t>=27647&&t<=28671)return me(e,pe().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return me(e,pe().suffixes[t-1811939328]);if(t==Tr)return{packedValues:Y,structures:K.slice(0),version:e};if(t==55799)return e});const Jr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Ut=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],Ur=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<Ut.length;t++)Dr(Ut[t],Ur[t]);function Dr(t,e){let r="get"+t.name.slice(0,-5),n;typeof t=="function"?n=t.BYTES_PER_ELEMENT:t=null;for(let s=0;s<2;s++){if(!s&&n==1)continue;let i=n==2?1:n==4?2:n==8?3:0;V[s?e:e-4]=n==1||s==Jr?o=>{if(!t)throw new Error("Could not find typed array for code "+e);return!J.copyBuffers&&(n===1||n===2&&!(o.byteOffset&1)||n===4&&!(o.byteOffset&3)||n===8&&!(o.byteOffset&7))?new t(o.buffer,o.byteOffset,o.byteLength>>i):new t(Uint8Array.prototype.slice.call(o,0).buffer)}:o=>{if(!t)throw new Error("Could not find typed array for code "+e);let y=new DataView(o.buffer,o.byteOffset,o.byteLength),c=o.length>>i,h=new t(c),w=y[r];for(let p=0;p<c;p++)h[p]=w.call(y,p<<i,s);return h}}}function jr(){let t=be(),e=d+U();for(let n=2;n<t;n++){let s=be();d+=s}let r=d;return d=e,W=[Qe(be()),Qe(be())],W.position0=0,W.position1=0,W.postBundlePosition=d,d=r,U()}function be(){if(!(d<Q))throw de();let t=A[d++]&31;if(t>23)switch(t){case 24:if(d>=Q)throw de();t=A[d++];break;case 25:t=G.getUint16(d),d+=2;break;case 26:t=G.getUint32(d),d+=4;break}return t}function tt(){if(J.getShared){let t=Dt(()=>(A=null,J.getShared()))||{},e=t.structures||[];J.sharedVersion=t.version,Y=J.sharedValues=t.packedValues,K===!0?J.structures=K=e:K.splice.apply(K,[0,e.length].concat(e))}}function Dt(t){let e=Q,r=d,n=xe,s=Oe,i=Le,o=te,y=W,c=new Uint8Array(A.slice(0,Q)),h=K,w=J,p=Me,v=t();return Q=e,d=r,xe=n,Oe=s,Le=i,te=o,W=y,A=c,Me=p,K=h,J=w,G=new DataView(A.buffer,A.byteOffset,A.byteLength),v}function rt(){A=null,te=null,K=null}const nt=new Array(147);for(let t=0;t<256;t++)nt[t]=+("1e"+Math.floor(45.15-t*.30103));let it=new Ie({useRecords:!1});const jt=it.decode;it.decodeMultiple;let Ue;try{Ue=new TextEncoder}catch{}let st,Bt;const De=typeof globalThis=="object"&&globalThis.Buffer,Pe=typeof De<"u",ot=Pe?De.allocUnsafeSlow:Uint8Array,qt=Pe?De:Uint8Array,zt=256,Kt=Pe?4294967296:2144337920;let at,u,B,a=0,ue,$=null;const Br=61440,qr=/[\u0080-\uFFFF]/,ee=Symbol("record-id");class zr extends Ie{constructor(e){super(e),this.offset=0;let r,n,s,i,o;e=e||{};let y=qt.prototype.utf8Write?function(l,P){return u.utf8Write(l,P,u.byteLength-P)}:Ue&&Ue.encodeInto?function(l,P){return Ue.encodeInto(l,u.subarray(P)).written}:!1,c=this,h=e.structures||e.saveStructures,w=e.maxSharedStructures;if(w==null&&(w=h?128:0),w>8190)throw new Error("Maximum maxSharedStructure is 8190");let p=e.sequential;p&&(w=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let v,f,C=e.sharedValues,m;if(C){m=Object.create(null);for(let l=0,P=C.length;l<P;l++)m[C[l]]=l}let N=[],O=0,b=0;this.mapEncode=function(l,P){return this._keyMap&&!this._mapped&&l.constructor.name==="Array"&&(l=l.map(E=>this.encodeKeys(E))),this.encode(l,P)},this.encode=function(l,P){if(u||(u=new ot(8192),B=new DataView(u.buffer,0,8192),a=0),ue=u.length-10,ue-a<2048?(u=new ot(u.length),B=new DataView(u.buffer,0,u.length),ue=u.length-10,a=0):P===Ht&&(a=a+7&2147483640),r=a,c.useSelfDescribedHeader&&(B.setUint32(a,3654940416),a+=3),o=c.structuredClone?new Map:null,c.bundleStrings&&typeof l!="string"?($=[],$.size=1/0):$=null,n=c.structures,n){if(n.uninitialized){let R=c.getShared()||{};c.structures=n=R.structures||[],c.sharedVersion=R.version;let S=c.sharedValues=R.packedValues;if(S){m={};for(let k=0,F=S.length;k<F;k++)m[S[k]]=k}}let E=n.length;if(E>w&&!p&&(E=w),!n.transitions){n.transitions=Object.create(null);for(let R=0;R<E;R++){let S=n[R];if(!S)continue;let k,F=n.transitions;for(let x=0,T=S.length;x<T;x++){F[ee]===void 0&&(F[ee]=R);let D=S[x];k=F[D],k||(k=F[D]=Object.create(null)),F=k}F[ee]=R|1048576}}p||(n.nextId=E)}if(s&&(s=!1),i=n||[],f=m,e.pack){let E=new Map;if(E.values=[],E.encoder=c,E.maxValues=e.maxPrivatePackedValues||(m?16:1/0),E.objectMap=m||!1,E.samplingPackedValues=v,je(l,E),E.values.length>0){u[a++]=216,u[a++]=51,ie(4);let R=E.values;g(R),ie(0),ie(0),f=Object.create(m||null);for(let S=0,k=R.length;S<k;S++)f[R[S]]=S}}at=P&ft;try{if(at)return;if(g(l),$&&$t(r,g),c.offset=a,o&&o.idsToInsert){a+=o.idsToInsert.length*2,a>ue&&_(a),c.offset=a;let E=Wr(u.subarray(r,a),o.idsToInsert);return o=null,E}return P&Ht?(u.start=r,u.end=a,u):u.subarray(r,a)}finally{if(n){if(b<10&&b++,n.length>w&&(n.length=w),O>1e4)n.transitions=null,b=0,O=0,N.length>0&&(N=[]);else if(N.length>0&&!p){for(let E=0,R=N.length;E<R;E++)N[E][ee]=void 0;N=[]}}if(s&&c.saveShared){c.structures.length>w&&(c.structures=c.structures.slice(0,w));let E=u.subarray(r,a);return c.updateSharedData()===!1?c.encode(l):E}P&Hr&&(a=r)}},this.findCommonStringsToPack=()=>(v=new Map,m||(m=Object.create(null)),l=>{let P=l&&l.threshold||4,E=this.pack?l.maxPrivatePackedValues||16:0;C||(C=this.sharedValues=[]);for(let[R,S]of v)S.count>P&&(m[R]=E++,C.push(R),s=!0);for(;this.saveShared&&this.updateSharedData()===!1;);v=null});const g=l=>{a>ue&&(u=_(a));var P=typeof l,E;if(P==="string"){if(f){let F=f[l];if(F>=0){F<16?u[a++]=F+224:(u[a++]=198,F&1?g(15-F>>1):g(F-16>>1));return}else if(v&&!e.pack){let x=v.get(l);x?x.count++:v.set(l,{count:1})}}let R=l.length;if($&&R>=4&&R<1024){if(($.size+=R)>Br){let x,T=($[0]?$[0].length*3+$[1].length:0)+10;a+T>ue&&(u=_(a+T)),u[a++]=217,u[a++]=223,u[a++]=249,u[a++]=$.position?132:130,u[a++]=26,x=a-r,a+=4,$.position&&$t(r,g),$=["",""],$.size=0,$.position=x}let F=qr.test(l);$[F?0:1]+=l,u[a++]=F?206:207,g(R);return}let S;R<32?S=1:R<256?S=2:R<65536?S=3:S=5;let k=R*3;if(a+k>ue&&(u=_(a+k)),R<64||!y){let F,x,T,D=a+S;for(F=0;F<R;F++)x=l.charCodeAt(F),x<128?u[D++]=x:x<2048?(u[D++]=x>>6|192,u[D++]=x&63|128):(x&64512)===55296&&((T=l.charCodeAt(F+1))&64512)===56320?(x=65536+((x&1023)<<10)+(T&1023),F++,u[D++]=x>>18|240,u[D++]=x>>12&63|128,u[D++]=x>>6&63|128,u[D++]=x&63|128):(u[D++]=x>>12|224,u[D++]=x>>6&63|128,u[D++]=x&63|128);E=D-a-S}else E=y(l,a+S,k);E<24?u[a++]=96|E:E<256?(S<2&&u.copyWithin(a+2,a+1,a+1+E),u[a++]=120,u[a++]=E):E<65536?(S<3&&u.copyWithin(a+3,a+2,a+2+E),u[a++]=121,u[a++]=E>>8,u[a++]=E&255):(S<5&&u.copyWithin(a+5,a+3,a+3+E),u[a++]=122,B.setUint32(a,E),a+=4),a+=E}else if(P==="number")if(!this.alwaysUseFloat&&l>>>0===l)l<24?u[a++]=l:l<256?(u[a++]=24,u[a++]=l):l<65536?(u[a++]=25,u[a++]=l>>8,u[a++]=l&255):(u[a++]=26,B.setUint32(a,l),a+=4);else if(!this.alwaysUseFloat&&l>>0===l)l>=-24?u[a++]=31-l:l>=-256?(u[a++]=56,u[a++]=~l):l>=-65536?(u[a++]=57,B.setUint16(a,~l),a+=2):(u[a++]=58,B.setUint32(a,~l),a+=4);else if(!this.alwaysUseFloat&&l<0&&l>=-4294967296&&Math.floor(l)===l)u[a++]=58,B.setUint32(a,-1-l),a+=4;else{let R;if((R=this.useFloat32)>0&&l<4294967296&&l>=-2147483648){u[a++]=250,B.setFloat32(a,l);let S;if(R<4||(S=l*nt[(u[a]&127)<<1|u[a+1]>>7])>>0===S){a+=4;return}else a--}u[a++]=251,B.setFloat64(a,l),a+=8}else if(P==="object")if(!l)u[a++]=246;else{if(o){let S=o.get(l);if(S){if(u[a++]=216,u[a++]=29,u[a++]=25,!S.references){let k=o.idsToInsert||(o.idsToInsert=[]);S.references=[],k.push(S)}S.references.push(a-r),a+=2;return}else o.set(l,{offset:a-r})}let R=l.constructor;if(R===Object)this.skipFunction===!0&&(l=Object.fromEntries([...Object.keys(l).filter(S=>typeof l[S]!="function").map(S=>[S,l[S]])])),I(l);else if(R===Array){E=l.length,E<24?u[a++]=128|E:ie(E);for(let S=0;S<E;S++)g(l[S])}else if(R===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(u[a++]=217,u[a++]=1,u[a++]=3),E=l.size,E<24?u[a++]=160|E:E<256?(u[a++]=184,u[a++]=E):E<65536?(u[a++]=185,u[a++]=E>>8,u[a++]=E&255):(u[a++]=186,B.setUint32(a,E),a+=4),c.keyMap)for(let[S,k]of l)g(c.encodeKey(S)),g(k);else for(let[S,k]of l)g(S),g(k);else{for(let S=0,k=st.length;S<k;S++){let F=Bt[S];if(l instanceof F){let x=st[S],T=x.tag;T==null&&(T=x.getTag&&x.getTag.call(this,l)),T<24?u[a++]=192|T:T<256?(u[a++]=216,u[a++]=T):T<65536?(u[a++]=217,u[a++]=T>>8,u[a++]=T&255):T>-1&&(u[a++]=218,B.setUint32(a,T),a+=4),x.encode.call(this,l,g,_);return}}if(l[Symbol.iterator]){if(at){let S=new Error("Iterable should be serialized as iterator");throw S.iteratorNotHandled=!0,S}u[a++]=159;for(let S of l)g(S);u[a++]=255;return}if(l[Symbol.asyncIterator]||ct(l)){let S=new Error("Iterable/blob should be serialized as iterator");throw S.iteratorNotHandled=!0,S}if(this.useToJSON&&l.toJSON){const S=l.toJSON();if(S!==l)return g(S)}I(l)}}else if(P==="boolean")u[a++]=l?245:244;else if(P==="bigint"){if(l<BigInt(1)<<BigInt(64)&&l>=0)u[a++]=27,B.setBigUint64(a,l);else if(l>-(BigInt(1)<<BigInt(64))&&l<0)u[a++]=59,B.setBigUint64(a,-l-BigInt(1));else if(this.largeBigIntToFloat)u[a++]=251,B.setFloat64(a,Number(l));else{l>=BigInt(0)?u[a++]=194:(u[a++]=195,l=BigInt(-1)-l);let R=[];for(;l;)R.push(Number(l&BigInt(255))),l>>=BigInt(8);lt(new Uint8Array(R.reverse()),_);return}a+=8}else if(P==="undefined")u[a++]=247;else throw new Error("Unknown type: "+P)},I=this.useRecords===!1?this.variableMapSize?l=>{let P=Object.keys(l),E=Object.values(l),R=P.length;if(R<24?u[a++]=160|R:R<256?(u[a++]=184,u[a++]=R):R<65536?(u[a++]=185,u[a++]=R>>8,u[a++]=R&255):(u[a++]=186,B.setUint32(a,R),a+=4),c.keyMap)for(let S=0;S<R;S++)g(c.encodeKey(P[S])),g(E[S]);else for(let S=0;S<R;S++)g(P[S]),g(E[S])}:l=>{u[a++]=185;let P=a-r;a+=2;let E=0;if(c.keyMap)for(let R in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(R))&&(g(c.encodeKey(R)),g(l[R]),E++);else for(let R in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(R))&&(g(R),g(l[R]),E++);u[P+++r]=E>>8,u[P+r]=E&255}:(l,P)=>{let E,R=i.transitions||(i.transitions=Object.create(null)),S=0,k=0,F,x;if(this.keyMap){x=Object.keys(l).map(D=>this.encodeKey(D)),k=x.length;for(let D=0;D<k;D++){let yt=x[D];E=R[yt],E||(E=R[yt]=Object.create(null),S++),R=E}}else for(let D in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(D))&&(E=R[D],E||(R[ee]&1048576&&(F=R[ee]&65535),E=R[D]=Object.create(null),S++),R=E,k++);let T=R[ee];if(T!==void 0)T&=65535,u[a++]=217,u[a++]=T>>8|224,u[a++]=T&255;else if(x||(x=R.__keys__||(R.__keys__=Object.keys(l))),F===void 0?(T=i.nextId++,T||(T=0,i.nextId=1),T>=zt&&(i.nextId=(T=w)+1)):T=F,i[T]=x,T<w){u[a++]=217,u[a++]=T>>8|224,u[a++]=T&255,R=i.transitions;for(let D=0;D<k;D++)(R[ee]===void 0||R[ee]&1048576)&&(R[ee]=T),R=R[x[D]];R[ee]=T|1048576,s=!0}else{if(R[ee]=T,B.setUint32(a,3655335680),a+=3,S&&(O+=b*S),N.length>=zt-w&&(N.shift()[ee]=void 0),N.push(R),ie(k+2),g(57344+T),g(x),P)return;for(let D in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(D))&&g(l[D]);return}if(k<24?u[a++]=128|k:ie(k),!P)for(let D in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(D))&&g(l[D])},_=l=>{let P;if(l>16777216){if(l-r>Kt)throw new Error("Encoded buffer would be larger than maximum buffer size");P=Math.min(Kt,Math.round(Math.max((l-r)*(l>67108864?1.25:2),4194304)/4096)*4096)}else P=(Math.max(l-r<<2,u.length-1)>>12)+1<<12;let E=new ot(P);return B=new DataView(E.buffer,0,P),u.copy?u.copy(E,0,r,l):E.set(u.slice(r,l)),a-=r,r=0,ue=E.length-10,u=E};let M=100,q=1e3;this.encodeAsIterable=function(l,P){return Z(l,P,z)},this.encodeAsAsyncIterable=function(l,P){return Z(l,P,ve)};function*z(l,P,E){let R=l.constructor;if(R===Object){let S=c.useRecords!==!1;S?I(l,!0):Vt(Object.keys(l).length,160);for(let k in l){let F=l[k];S||g(k),F&&typeof F=="object"?P[k]?yield*z(F,P[k]):yield*X(F,P,k):g(F)}}else if(R===Array){let S=l.length;ie(S);for(let k=0;k<S;k++){let F=l[k];F&&(typeof F=="object"||a-r>M)?P.element?yield*z(F,P.element):yield*X(F,P,"element"):g(F)}}else if(l[Symbol.iterator]&&!l.buffer){u[a++]=159;for(let S of l)S&&(typeof S=="object"||a-r>M)?P.element?yield*z(S,P.element):yield*X(S,P,"element"):g(S);u[a++]=255}else ct(l)?(Vt(l.size,64),yield u.subarray(r,a),yield l,L()):l[Symbol.asyncIterator]?(u[a++]=159,yield u.subarray(r,a),yield l,L(),u[a++]=255):g(l);E&&a>r?yield u.subarray(r,a):a-r>M&&(yield u.subarray(r,a),L())}function*X(l,P,E){let R=a-r;try{g(l),a-r>M&&(yield u.subarray(r,a),L())}catch(S){if(S.iteratorNotHandled)P[E]={},a=r+R,yield*z.call(this,l,P[E]);else throw S}}function L(){M=q,c.encode(null,ft)}function Z(l,P,E){return P&&P.chunkThreshold?M=q=P.chunkThreshold:M=100,l&&typeof l=="object"?(c.encode(null,ft),E(l,c.iterateProperties||(c.iterateProperties={}),!0)):[c.encode(l)]}async function*ve(l,P){for(let E of z(l,P,!0)){let R=E.constructor;if(R===qt||R===Uint8Array)yield E;else if(ct(E)){let S=E.stream().getReader(),k;for(;!(k=await S.read()).done;)yield k.value}else if(E[Symbol.asyncIterator])for await(let S of E)L(),S?yield*ve(S,P.async||(P.async={})):yield c.encode(S);else yield E}}}useBuffer(e){u=e,B=new DataView(u.buffer,u.byteOffset,u.byteLength),a=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),n=new Wt(r,this.sharedValues,this.sharedVersion),s=this.saveShared(n,i=>(i&&i.version||0)==e);return s===!1?(n=this.getShared()||{},this.structures=n.structures||[],this.sharedValues=n.packedValues,this.sharedVersion=n.version,this.structures.nextId=this.structures.length):r.forEach((i,o)=>this.structures[o]=i),s}}function Vt(t,e){t<24?u[a++]=e|t:t<256?(u[a++]=e|24,u[a++]=t):t<65536?(u[a++]=e|25,u[a++]=t>>8,u[a++]=t&255):(u[a++]=e|26,B.setUint32(a,t),a+=4)}class Wt{constructor(e,r,n){this.structures=e,this.packedValues=r,this.version=n}}function ie(t){t<24?u[a++]=128|t:t<256?(u[a++]=152,u[a++]=t):t<65536?(u[a++]=153,u[a++]=t>>8,u[a++]=t&255):(u[a++]=154,B.setUint32(a,t),a+=4)}const Kr=typeof Blob>"u"?function(){}:Blob;function ct(t){if(t instanceof Kr)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function je(t,e){switch(typeof t){case"string":if(t.length>3){if(e.objectMap[t]>-1||e.values.length>=e.maxValues)return;let n=e.get(t);if(n)++n.count==2&&e.values.push(t);else if(e.set(t,{count:1}),e.samplingPackedValues){let s=e.samplingPackedValues.get(t);s?s.count++:e.samplingPackedValues.set(t,{count:1})}}break;case"object":if(t)if(t instanceof Array)for(let n=0,s=t.length;n<s;n++)je(t[n],e);else{let n=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(n&&je(r,e),je(t[r],e))}break;case"function":console.log(t)}}const Vr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;Bt=[Date,Set,Error,RegExp,he,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,Wt],st=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(u[a++]=26,B.setUint32(a,r),a+=4):(u[a++]=251,B.setFloat64(a,r),a+=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){lt(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Pe&&this.tagUint8Array!==!1))return 64},encode(t,e,r){lt(t,r)}},se(68,1),se(69,2),se(70,4),se(71,8),se(72,1),se(77,2),se(78,4),se(79,8),se(85,4),se(86,8),{encode(t,e){let r=t.packedValues||[],n=t.structures||[];if(r.values.length>0){u[a++]=216,u[a++]=51,ie(4);let s=r.values;e(s),ie(0),ie(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let i=0,o=s.length;i<o;i++)packedObjectMap[s[i]]=i}if(n){B.setUint32(a,3655335424),a+=3;let s=n.slice(0);s.unshift(57344),s.push(new he(t.version,1399353956)),e(s)}else e(new he(t.version,1399353956))}}];function se(t,e){return!Vr&&e>1&&(t-=4),{tag:t,encode:function(n,s){let i=n.byteLength,o=n.byteOffset||0,y=n.buffer||n;s(Pe?De.from(y,o,i):new Uint8Array(y,o,i))}}}function lt(t,e){let r=t.byteLength;r<24?u[a++]=64+r:r<256?(u[a++]=88,u[a++]=r):r<65536?(u[a++]=89,u[a++]=r>>8,u[a++]=r&255):(u[a++]=90,B.setUint32(a,r),a+=4),a+r>=u.length&&e(a+r),u.set(t.buffer?t:new Uint8Array(t),a),a+=r}function Wr(t,e){let r,n=e.length*2,s=t.length-n;e.sort((i,o)=>i.offset>o.offset?1:-1);for(let i=0;i<e.length;i++){let o=e[i];o.id=i;for(let y of o.references)t[y++]=i>>8,t[y]=i&255}for(;r=e.pop();){let i=r.offset;t.copyWithin(i+n,i,s),n-=2;let o=i+n;t[o++]=216,t[o++]=28,s=i}return t}function $t(t,e){B.setUint32($.position+t,a-$.position-t+1);let r=$;$=null,e(r[0]),e(r[1])}let ut=new zr({useRecords:!1});const $r=ut.encode;ut.encodeAsIterable,ut.encodeAsAsyncIterable;const Ht=512,Hr=1024,ft=2048;function Gt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}class Be{closed=!1;[j];#e;constructor(e,{signal:r}={}){this[j]=new pr(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[j].dispatchClose(e)}#r=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const Gr=Se("appetize.io:transport:ws-ping"),Zr=3e4;function Yr(t){let e=!0;const r=()=>{e=!0};t.on("pong",r);const n=setInterval(()=>{if(!e){clearInterval(n),Gr("liveness ping went unanswered, terminating"),t.terminate();return}t.readyState===t.OPEN&&(e=!1,t.ping())},Zr);return{destroy(){clearInterval(n),t.off("pong",r)},pong:r}}const ye=Se("appetize.io:trace:transport:websocket");class Xr extends Be{constructor(e,{signal:r}={}){super(async s=>{this.#i.send($r(s))},{signal:r}),this.wsOrUrl=e,typeof e=="string"?(this.#i=new WebSocket(e),this.#i.binaryType="arraybuffer"):this.#i=e;const n=this.#i;if(n instanceof WebSocket?(n.addEventListener("open",this.#l),n.addEventListener("message",this.#c),n.addEventListener("error",this.#a),n.addEventListener("close",this.#o),this.#e.push(()=>{n.removeEventListener("open",this.#l),n.removeEventListener("message",this.#c),n.removeEventListener("error",this.#a),n.removeEventListener("close",this.#o)})):(n.addEventListener("open",this.#l),n.addEventListener("message",this.#c),n.addEventListener("error",this.#a),n.addEventListener("close",this.#o),this.#e.push(()=>{n.removeEventListener("open",this.#l),n.removeEventListener("message",this.#c),n.removeEventListener("error",this.#a),n.removeEventListener("close",this.#o)})),this.send=n.send.bind(n),"ping"in n){const{destroy:s,pong:i}=Yr(n);this.#n=i,this.#e.push(s)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#i.bufferedAmount}get readyState(){return this.#i.readyState}#e=[];#r=!1;#t=!1;#n;#i;close({destroyWs:e=!1,...r}={}){this.closed||(this.#r=e,super.close(r))}handleClose(e){ye("close()");for(const r of this.#e.splice(0))r();if((typeof this.wsOrUrl=="string"||this.#r)&&(this.#i.close(e.code,e.reason),"terminate"in this.#i)){const r=this.#i;setTimeout(()=>{r.terminate()},100)}this.#s(),super.handleClose(e)}#s(e){this.#t||(this.#t=!0,this.onclose?.(e))}#o=e=>{ye("handleWebSocketClose()",e);try{this.#s(e)}finally{this.close()}};#a=e=>{ye("handleWebSocketError()",e),this.onerror?.(e)};#c=async e=>{ye("handleWebSocketMessage()",e),this.#n?.();const r=this.#u(e);if(!r){ye("handleWebSocketMessage() -> legacy"),this.onmessage?.(e);return}ye("handleWebSocketMessage() -> jsonrpc",r),this[j].dispatchMessage(r)};#l=e=>{ye("handleWebSocketOpen()",e),this.onopen?.(e)};#u(e){try{const r=jt(new Uint8Array(e.data));return Gt(r)?r:null}catch{return null}}}function Zt(t,e,{leftEffects:r=()=>({}),notifiesLeft:n,notifiesRight:s,rightEffects:i=()=>({})}={}){const o=$e(t,{}),y=$e(e,{}),c=[()=>{o.unsub(),y.unsub()}],h=()=>{for(const C of c)try{C()}catch{}},w=y.rpc.client,p=o.rpc.client;c.push(t[j].addEventListener("close",()=>{h()},{once:!0}),e[j].addEventListener("close",()=>{h()},{once:!0}));const v=r(w,p);for(const C in v){const m=v[C];m&&o.rpc.addMethod(C,m)}const f=i(p,w);for(const C in f){const m=f[C];m&&y.rpc.addMethod(C,m)}return Yt(o.rpc,y.rpc,{notifies:n}),Yt(y.rpc,o.rpc,{notifies:s}),h}function Yt(t,e,{notifies:r}={}){t.applyServerMiddleware(async(n,s)=>{const i=r?.();if(i){const{id:y,...c}=s;i[j].send(c)}if(t.hasMethod(s.method))return await n(s);if(!s.id)return e.notify(s.method,s.params),null;const o=await e.request(s.method,s.params);return{id:s.id,jsonrpc:ke.JSONRPC,result:o}})}function le(t,...e){t.notify(e[0],e[1],e[2])}function dt(){const t=new Be(async r=>{e[j].dispatchMessage(r)}),e=new Be(async r=>{t[j].dispatchMessage(r)});return t[j].addEventListener("close",()=>{e.close()},{once:!0}),e[j].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function Xt(t,e){const r=[],n=()=>{for(const s of r)s()};r.push(t[j].addEventListener("message",s=>e[j].send(s.detail))),r.push(t[j].addEventListener("close",n,{once:!0})),r.push(e[j].addEventListener("message",s=>t[j].send(s.detail))),r.push(e[j].addEventListener("close",n,{once:!0}))}const we=Se("appetize.io:trace:transport:iframe");class Qt extends Be{onmessage;#e;#r;constructor(e,{origin:r="*",signal:n}={}){super(async s=>{e.postMessage(s,this.#e)},{signal:n}),this.#r=e,this.#e=r,window.addEventListener("message",this.#t)}postMessage(e,r,n){we("postMessage(legacy)",{message:e,targetOrigin:r,transfer:n}),this.#r.postMessage(e,r??this.#e,n)}handleClose(e){we("close()"),window.removeEventListener("message",this.#t),super.handleClose(e)}#t=async e=>{if(we("handleMessage()",e),e.source!==this.#r||(we("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;we("handleMessage() -> origin ok");const r=e.data;if(!Gt(r)){we("handleMessage() -> legacy"),this.onmessage?.(e);return}we("handleMessage() -> jsonrpc"),this[j].dispatchMessage(r)}}function ht(){let t,e;return{promise:new Promise((n,s)=>{e=n,t=s}),reject:t,resolve:e}}const Qr=2*1024*1024,er=Se("appetize:client:acked-writable-stream");class en{unacked=0;#e;#r;#t;#n;#i=[];#s;constructor(e){this.#t=e,this.#s=e.window??Qr}abort(e){this.#a(e),this.#t.onAbort?.(e)}async close(){await this.#c(()=>this.unacked===0),this.#t.onClose?.()}fail(e){this.#a(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.#n&&(this.#n.acked+=r),this.#o()},n=>{this.fail(n)}),this.unacked>=this.#s&&!this.#n&&(this.#n={acked:0,at:performance.now()},er("window full: %d bytes unacked, writes stalled",this.unacked)),this.#c(()=>this.unacked<this.#s)}#o(){if(this.#n&&this.unacked<=this.#s/2){const e=performance.now()-this.#n.at;er("pressure relieved after %dms: %d bytes acked, %s MB/s",Math.round(e),this.#n.acked,(this.#n.acked/Math.max(e,1)/1e3).toFixed(2)),this.#n=void 0}this.#i=this.#i.filter(e=>e.until()?(e.resolve(void 0),!1):!0)}#a(e){if(this.#r)return!1;this.#r={reason:e},this.#e.error(e);const r=this.#i;this.#i=[];for(const n of r)n.reject(e);return!0}#c(e){if(e())return Promise.resolve();const r={...ht(),until:e};return this.#i.push(r),r.promise}}class tn extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new en(e);super({abort:n=>{r.abort(n)},close:()=>r.close(),start:n=>{r.start(n)},write:n=>r.write(n)}),this.#e=r}fail(e){this.#e.fail(e)}}const rn=1024*1024;class nn{#e;#r=!1;#t;#n;constructor(e){this.#t=e}cancel(e){this.#i(),this.#t?.(e)}close(){this.#i()&&this.#e.close()}error(e){this.#i()&&this.#e.error(e)}pull(){const e=this.#n;this.#n=void 0,e?.resolve(void 0)}async push(e){if(this.#r)return;this.#n??=ht();const{promise:r}=this.#n;this.#e.enqueue(e),await r}start(e){this.#e=e}#i(){return this.#r?!1:(this.#r=!0,this.pull(),!0)}}class sn extends ReadableStream{#e;constructor({highWaterMark:e=rn,onCancel:r}={}){const n=new nn(r);super({cancel:s=>{n.cancel(s)},pull:()=>{n.pull()},start:s=>{n.start(s)}},new ByteLengthQueuingStrategy({highWaterMark:e})),this.#e=n}close(){this.#e.close()}error(e){this.#e.error(e)}push(e){return this.#e.push(e)}}class on{closed;readable;writable;#e=[];#r;#t;#n;#i;#s;#o="starting";constructor(e,{onClose:r,receiveBuffer:n,sendWindow:s,signal:i}){if(this.#s=e,this.#r=ht(),this.closed=this.#r.promise,this.closed.catch(an),this.#n=new sn({highWaterMark:n,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#n,this.#i=new tn({onAbort:()=>{this.#a(void 0)},onClose:()=>{this.#a(void 0)},onError:o=>{this.#a(o)},send:o=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:o}),window:s}),this.writable=this.#i,i){const o=()=>{this.#a(i.reason)};i.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{i.removeEventListener("abort",o)})}this.#e.push(()=>{r(this)})}close=()=>{this.#a(void 0)};detach(){this.#a(void 0,{notifyServer:!1})}async handleData(e){this.#o==="open"&&await this.#n.push(e)}handleStopped({error:e}){this.#o==="open"&&this.#a(e?new Error(e):void 0)}async start(){try{await this.#s.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#a(e),e}if(this.#o==="closed")throw this.#t?this.#t:new Error("The adb tunnel closed before it started");this.#o="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#a(e,{notifyServer:r=!0}={}){if(this.#o!=="closed"){this.#o="closed",this.#t=e,r&&le(this.#s,"appetizeio.device.server.debug.adbTunnel.stop",void 0),e?(this.#n.error(e),this.#i.fail(e)):(this.#n.close(),this.#i.fail(new Error("The adb tunnel has stopped")));for(const n of this.#e)n();e?this.#r.reject(e):this.#r.resolve(void 0)}}}function an(){}class cn{readable;ready;#e=[];#r=!1;#t;#n;#i;constructor({label:e,onClose:r,signal:n}){this.#n=e,this.ready=new Promise((i,o)=>{this.#i={reject:o,resolve:i}});let s;if(this.readable=new ReadableStream({cancel:()=>{this.#o()},start:i=>{s=i}}),!s)throw new Error("ReadableStream controller was not initialized");if(this.#t=s,n){const i=()=>{this.fail(n.reason)};n.addEventListener("abort",i,{once:!0}),this.#e.push(()=>{n.removeEventListener("abort",i)})}this.#e.push(()=>{r(this)})}close=()=>{this.#s()};fail(e){this.#s(e)}handleItem(e){this.#t.enqueue(e)}markReady(){if(!this.#i)return;const{resolve:e}=this.#i;this.#i=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()}}#s(e){this.#r||(this.#t.close(),this.#o(e))}#o(e){this.#r=!0;for(const r of this.#e)r();this.#i?.reject(e??new Error(`${this.#n} closed before it started`)),this.#i=void 0}}class ln{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 tr extends ln{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new cn({label:this.#e,onClose:n=>{this.release(n)},signal:e});this.add(r);try{await this.ensureStarted(),r.markReady()}catch(n){r.fail(n)}return await r.ready}handleNotification(e){for(const r of this.subscribers)r.handleItem(e)}}class un{#e;#r;#t;#n;constructor(e){this.#n=e,this.#r=new tr({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{le(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#t=new tr({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{le(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 on(this.#n,{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 pt(t){return{...fn(t),index:t.index,within:t.within?pt(t.within):void 0}}function fn(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:dn(t.text)}}}function dn(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function hn(t){return{press:e=>{le(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function pn({onRequest:t,parent:e,proxyInlet:r,signal:n}){const s=new Qt(e,{signal:n}),i=[()=>{s.close()}];return Xt(s,r),t&&i.push(Fe(s,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of i)o()},notifies:()=>e===globalThis.window?void 0:s}}const yn="@appetizeio/rpc:playwrightAdapter",qe=Symbol.for(yn);function wn(t){window[qe]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[j].send(r)},subscribe(r){return t[j].addEventListener("message",n=>{r(n.detail)})}};return window[qe]=e,()=>{window[qe]===e&&delete window[qe]}}function vn({onRequest:t,proxyInlet:e}){const[r,n]=dt(),i=[wn(n),()=>{r.close()}];return Xt(r,e),t&&i.push(Fe(r,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of i)o()},notifies:()=>r}}function ze(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...pt(t),x:t.x,y:t.y}}function gn(t){return"to"in t?{from:ze(t.from),kind:"path",to:ze(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?ze(t.from):void 0,kind:"direction"}}function mn(t){return{down:(e,r)=>{le(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{le(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{le(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const bn=new Set(He),Sn=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,Cn=/(\{\{|\{[^{}]*\})/u;function En(t){const e=[];let r="";function n(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[s,i]of t.split(Cn).entries())if(s%2===0){if(i.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=i}else i==="{{"?r+="{":(n(),e.push(On(i.slice(1,-1))));return n(),e}function Rn(t,e){if(!bn.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: ${He.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function On(t){const e=Sn.exec(t)?.groups,r=e?.key??t;if(Rn(r,t),!e)return{key:r,kind:"press"};const n=Number(e.repeat);if(n<1)throw new Error(`Repeat for {${t}} must be at least 1`);return{key:r,kind:"press",repeat:n}}const An=Symbol("@appetizeio/client:v1Compat");function rr(t){return t?.[An]}class Mn{readable;ready;get dimensions(){return this.#n}#e=[];#r=!1;#t;#n;#i;#s;constructor({onClose:e,requestKeyFrame:r,signal:n}){this.#i=r,this.ready=new Promise((i,o)=>{this.#s={reject:o,resolve:i}});let s;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:i=>{s=i}}),!s)throw new Error("ReadableStream controller was not initialized");if(this.#t=s,n){const i=()=>{this.fail(n.reason)};n.addEventListener("abort",i,{once:!0}),this.#e.push(()=>{n.removeEventListener("abort",i)})}this.#e.push(()=>{e(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleChunk(e){if(this.#s){if(e.type!=="key")return;const{resolve:r}=this.#s;this.#s=void 0,this.#n={height:e.height,width:e.width},r(this)}else e.type==="key"&&(this.#n={height:e.height,width:e.width});this.#t.enqueue(e)}requestKeyFrame=()=>{this.#r||this.#i()};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.#s?.reject(e??new Error("Video stream closed before the first key chunk")),this.#s=void 0}}class Pn{#e=!1;#r;#t;#n=new Set;constructor(e){this.#r=e}close(){this.#t=void 0;for(const e of[...this.#n])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Mn({onClose:n=>{this.#s(n)},requestKeyFrame:()=>{this.#o()},signal:e});this.#n.add(r);try{await this.#i()}catch(n){r.fail(n)}return await r.ready}handleChunk(e){e.type==="key"&&(this.#e=!1);for(const r of this.#n)r.handleChunk(e)}#i(){return this.#t?(this.#o(),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)}#s(e){this.#n.delete(e),!(this.#n.size>0||!this.#t)&&(this.#t=void 0,le(this.#r,"appetizeio.device.server.video.stop",void 0))}#o(){this.#e||(this.#e=!0,le(this.#r,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class In{debug;keyboard;touch;video;#e;#r=[];#t;constructor(e,r={}){const n=rr(r)??{},{baseUrl:s,onClose:i,signal:o}=r;this.#e=s?Nn(s):void 0;const{onRequest:y,parent:c,proxyRequest:h}=n,w=_n(y);o?.addEventListener("abort",this.close);const[p,v]=dt(),[f,C]=dt();this.#r.push(()=>{p.close(),v.close(),f.close(),C.close()}),this.#r.push(Zt(C,e,{leftEffects:h}));const m=c==="playwright"?vn({onRequest:w,proxyInlet:f}):c?pn({onRequest:w,parent:c,proxyInlet:f,signal:o}):void 0;m&&this.#r.push(m.cleanup),this.#r.push(Zt(v,f,{notifiesLeft:m?.notifies}));const{client:N,unsub:O}=vr(p,{"appetizeio.device.client.debug.adbTunnel.data":I=>b.handleAdbTunnelData(I),"appetizeio.device.client.debug.adbTunnel.stopped":async I=>{b.handleAdbTunnelStopped(I)},"appetizeio.device.client.debug.log.entry":async I=>{b.handleLogEntry(I)},"appetizeio.device.client.debug.proxyIntercept.event":async I=>{b.handleProxyInterceptEvent(I)},"appetizeio.device.client.video.chunk":async I=>{g.handleChunk(I)}});this.#t=N,this.#r.push(O);const b=new un(this.#t);this.#r.push(()=>{b.close()});const g=new Pn(this.#t);this.#r.push(()=>{g.close()}),this.debug=b,this.keyboard=hn(this.#t),this.touch=mn(this.#t),this.video=g,w&&(this.#r.push(Fe(v,I=>{w(I,{source:"self"})})),e instanceof Qt&&this.#r.push(Fe(e,I=>{w(I,{source:"iframe"})}))),this.#r.push(()=>i?.())}close=()=>{for(const e of this.#r)try{e()}catch(r){console.error("Device cleanup error:",r)}};async inspect(e,r){return await this.#t.request("appetizeio.device.server.inspect",{options:r,selector:e?pt(e):void 0})}async press(e){await this.#t.request("appetizeio.device.server.press",{action:e})}async rotate(e){return await this.#t.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(){const e=await this.#t.request("appetizeio.device.server.screenshot"),r=this.#e?new URL(e.url,this.#e).href:e.url,n=await fetch(r);if(!n.ok)throw new Error(`Screenshot download failed: ${String(n.status)} ${n.statusText}`);const s=n.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await n.arrayBuffer()),mimeType:s}}async swipe(e,r){await this.#t.request("appetizeio.device.server.swipe",{gesture:gn(e),options:r})}async tap(e,r){await this.#t.request("appetizeio.device.server.tap",{options:r,selector:ze(e)})}async type(e,r){await this.#t.request("appetizeio.device.server.type",{options:r,steps:En(e)})}}function Nn(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const _n=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};function kn(t){return typeof t=="object"&&t!==null}function Fn(t){try{const e=jt(new Uint8Array(t.data));if(kn(e)&&typeof e.name=="string")return{name:e.name,payload:"payload"in e?e.payload:void 0}}catch{}}async function Ln(t,e={}){const r=e.baseUrl??(typeof t=="string"?new URL(t).origin:void 0),n=typeof t=="string"?new Xr(t,{signal:e.signal}):t,s=new In(n,{...e,baseUrl:r});return typeof t=="string"&&await xn(n,s,e),s}function xn(t,e,r){const n=rr(r)?.onLegacyMessage;return new Promise((s,i)=>{t.onopen=()=>{s()},t.onclose=()=>{e.close(),r.signal?.aborted?i(r.signal.reason):i(new Error("The websocket was closed before the device connection was established"))},t.onerror=i,t.onmessage=o=>{const y=Fn(o);y&&n?.(y)}})}async function Tn(t,e){const r=t.querySelector("canvas");if(!(r instanceof HTMLCanvasElement))throw new Error("Canvas unavailable");const n=e.protocol==="https:"?"wss:":"ws:",s=await Ln(`${n}//${e.host}/ws`);Er(s,r),Rr(s,r),await Or(s,r)}await Tn(document,location);
2
+ </script></body></html>